Get last modified file with matching name Java 8 [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm trying the retrieve the last modified file name with a matching pattern starts with Order_ and there should not be any hidden files, however it throws compilation error.
try {
File dir = new File("< dir >");
if (!dir.isDirectory()) {
Optional<File> op = Arrays.stream(dir.listFiles(File::isFile))
.max((f1, f2) -> Long.compare(f1.lastModified(), f12lastModified()))
.filter(fl -> fl.getName().startsWith("Order_") && !fl.getCanonicalPath().endsWith("~"))
; // Unhandled exception compilation error for canonicalPath method
}
} catch (Exception e) {
}
Exception: Unhandled exception: java.io.IOException
Any ideas would be greatly appreciated.

This feels like lambda abuse (using a hammer to butter your toast instead of, you know, a butter knife, because you just bought it and it's all shiny and new).
.max() returns either 1, or 0, elements, in the form of an Optional. you then filter that optional to check if the naming is right.
In other words, if the most recently modified file so happens to not start with Order_, this all returns Optional.NONE which surely wasn't your intent. You want to flip your max and your filter line.
More generally, you don't want to do this with lambdas. Inline Lambdas are the lesser evil - they are not exception transparent, not mutable local variable transparent, and not control flow transparent.
These 3 properties are fantastic when a lambda represents code that will run in some other context (e.g. another thread or much later). They are downsides when the code is going to be run then and there.
That means that when a lambda-based strategy and a non-lambda-based strategy for an inline code concept are roughly equally good, then you should prefer the non-lambda-based strategy. This becomes particularly poignant here, as the code is using obsolete API (the old java.io.File API, instead of the newer java.nio.file API).
In this case, .getCanonicalPath() is slightly odd behaviour: The only functional difference between invoking fl.getName().endsWith(...) and fl.getCanonicalPath().endsWith(...) is that the latter will first follow the link if the referenced 'file' is a soft-link.
That sounds like soft-links matter, and if they matter, you don't want this API as it is wonky and ill defined in the face of soft-links. The new API deals with it better, you'd want to use that (java.nio.file.Files's walk method, for example). If soft linking doesn't matter, then it's easy: Replace .getCanonicalPath() with .getName() and all is well. Well, after you fix your bug and flip the filter and max lines back in their right positions.
Note also that .getCanonicalPath() is slow - it needs to hit the disk, or at least, it might. (It will if it is a soft-link; the API doesn't define whether it will in other cases. The JVM impl is free to hit disk on some OSes and not on others. It may run blazingly fast on your system and run dog slow on another, making it hard to test).

Related

Does Java String.format() prevent String injection? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have been preparing for technical interview. So in one thing I am just not sure. If I write for example
try {
...
} catch (InterruptedException ie) {
throw new IllegalStateException(String.format("Player [%s]: failed to reply message [%s]"), ie);
}
Does this prevent already String injection? or Do I have to write like following:
String errorMsg = String.format("Player [%s]: failed to reply message [%s]");
throw new IllegalStateException(errorMsg, ie);
There is no difference between the two snippets. Neither protects against 'string injection'.
There are only 4 non-boneheaded mitigations against string injection attacks:
Ensure that where-ever the strings end up, it is impossible for this to be a security issue in any way or form. For example, if your data is going to a binary file where all system operators are aware the contents are straight from the web, it doesn't matter what's uploaded.
Do not render the string at all. Throwing the baby out with the bathwater.
Use a whitelist. If the string consists solely of these allowed things, allow it. By default, do not allow it.
Use escapers.
Honourable mention for the concept of blacklisting: Have a list of known-malicious stuff, and allow all strings unless they contain something on the blacklist. This is bone headed and should never be used. For example, if you scan incoming data for <script>, you messed up. Don't do this. It doesn't work. Blacklists are trivially bypassed. Whitelists are what you're looking for.
The vastly most common strategy is the 4th: Escapers. For example, when you have a web server that takes in a username and a user's telephone number and a user's full name, and then renders all this information back out on their public website, then:
The phone number should be mitigated using the whitelist strategy. A single +, digits in the range 0-9, spaces, dashes, and nothing else. If that's what the input is like, allow it. Otherwise don't.
The user's real name should be mitigated with escaping: Take the data as provided and inject it verbatim into your database, but treat this data as tainted in all interactions with that data: For example, when rendering that public page, the 'full name' string needs to be washed through an HTML escaper which e.g. replaces all < with <.
Your code doesn't do any of these 4 things (either version of it).
In general it is an extremely bad idea to consider the string returned by an exception's .getMessage() to be already 'safe' (escaped / passed the whitelist verifier). Instead, the code that invokes .getMessage() needs to apply one of the 4 mitigations as explained above.

How slow/fast is String concatenation in Java relative to other compiled languages? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm just getting started with Java and while reading through this guide I noticed the following snippet, describing a recent update to the Junit framework.
We can now write assertion messages in a lambda in JUnit 5, allowing
the lazy evaluation to skip complex message construction until needed:
#Test
public void shouldFailBecauseTheNumbersAreNotEqual_lazyEvaluation() {
Assertions.assertTrue(
2 == 3,
() -> "Numbers " + 2 + " and " + 3 + " are not equal!");
}
As someone new to Java this feels like a large implementation just to get around string concatenation.
Are evaluating strings in Java really that slow (relative to other languages?). How does it compare to other compiled languages like C, Golang, etc..?
The point is: there is no lazy string formatting in Java.
Meaning, in languages like C you might see things such as:
#define debug_print...
( see some real world examples here )
The idea is to define a macro to which you pass a complicated string. But the compiler makes sure that code gets only generated for situations that actually that string to be present.
Meaning: when using debug_print(), that complicated string concat that is might be required to build the messages passed to the macro call only happens when the message is really needed! The message is concatenated lazily.
In Java, we simply have no way to express that. You always have to go
if (someCondition) {
then pull together that large string
which isn't nice, especially when doing it for tracing. Some people in our group write that code, and it is just overly annoying that each and any trace statement has that leading if statement. That renders your whole code much less readable.
Therefore: this is not at all about the cost of string concats. It is about only spending the required CPU cycles if that string is truly needed.
And to answer the actual question: in the end, when that code gets invoked often enough, the JIT will turn it into carefully optimized machine code anyway. Thus: the actual string concat is not the issue.
In other words: you don't think of "performance" for Java in terms of source code. What matters is what happens at runtime, by the JIT.
Here's the bottom line. Starting out in Java, don't worry about minor performance issues like String concatenation. It may be a small issue for a large application server where lots of String concatenation is done but the results are not used. An example would be logging, where the log level of causes the event to be ignored. Also, Java uses a StringBuilder to concatenate a series of literals separated by the "+' operator, which is reasonably performant.

Output of JESS in Java

I want to send a "fact" to a JESS file within java and get the results back. I basicly batch the JESS file and then send my data (structure in here) into the engine by .add(). I tried to get the JESS results, which should be a string, into a "Value".
Rete engine = new Rete();
engine.batch("file.clp");
Value = AAAnull;
try{
engine.add(structure)
AAA = engine.eval("(run)");
} catch ...
System.out.println(AAA);
The result is always a number, although the result should be a string. I have worked it out in a simple java project and the AAA is returning the string, but here it is not working.
The (run) function returns the number of rules fired; that's the number you're seeing here.
The real results of running your program are the side effects it causes; getting the result in Java depends on what side effects you're expecting. That may mean anything from collecting output printed to the screen, finding newly created facts in working memory, or having your Jess program call Java methods that effect the outside world. Without seeing the contents of file.clp I can't say what you're expecting, but all of these things listed are covered in the Jess manual; the phrases above are links to the appropriate sections. I'm happy to answer any followup questions you might have.

Handling division by zero in graphics code

I'm writing a library for procedural image generation (Clisk) which allows users to define their own mathematical functions to generate images.
It's clearly possible for them to define a function which could result in a divide by zero for some pixels, e.g. (pseudocode)
red = 1.0 / (xposition - 0.5)
This would result in a divide by zero whenever xposition = 0.5 (the middle of the image)
Ideally I don't want image generation to crash... but at the same time I don't want to create a clunky hack to ignore divide by zeros that will cause problems later.
What would be a good, robust, systematic approach to handling these cases?
Ideally I don't want image generation to crash... but at the same time I don't want to create a clunky hack to ignore divide by zeros that will cause problems later.
(I'm assuming you mean the snippet to be an example of some user-supplied code ...)
Clearly, if the user-supplied code could throw exceptions, then you can't stop that happening. (And the advice to check before division is obviously irrelevant ... to you.)
So what could you do apart from "crash"? Generate an empty image? Ignore the user's function? You'd be producing garbage ... and that's not what the user needs.
You certainly can't reach in and fix his / her java code. (And if that snippet is meant to be code written in some custom language, then you can't reach in and correct that either. You / your library doesn't know what the user-supplied code should be doing ...)
No. I reckon that the best answer is to wrap any unexpected (unchecked) exceptions coming out of the user-supplied code in an exception of your own that tells the user clearly that the error occurred in his code. It is then up to the application code calling your library code whether to deal with the exception or "crash".
If you are asking for a "good, robust, systematic approach" for users to write their functions, I think you are barking up the wrong tree. And it is not really your concern ...
I'm not a graphics programmer really, but you could do
private static final double MIN_X = 0.0000001
red = 1.0 / Math.max(xpos - 0.5, MIN_X);
Obviously, you will probably have to drop an absolute value in there if you allow negatives
You could always just supply a parameter asking them what to do on divide-by-zero. It's their code, after all - they should know what's best for their case.
Then the question becomes, what's a reasonable default for that parameter? I'd say "return 0.0" or "throw an exception" are both reasonable for this application. Just make sure you document it.

How to find nested conditons count in java

I have to read java file by java code and to determine the greatest nested count of if statements in it.
for example:
if (someCondition)
{
if (someCondition)
{
// Expression
}
}
In this case program should display greatest nested if depth is 2.
Now the problem is that position of curly brace after if is uncertain.
for example it can be like :
Curly brace start and end comes in same line
if (someCondition){}
OR
Curly brace start in next line
if (someCondition)
{
}
OR
Conditions without curly brace
if (someCondition)
if (someCondition) // Single line without curly brace
Can anybody suggest what will be the best way to get the required nested count?
You'll need to parse the Abstract Syntax Tree (AST) of the Java source code. See Java library for code analysis. Once you have the AST, you can do a search to find the longest path of nested conditionals.
As the answer already said, you should rely on the AST rather than viewing code manually for this. The AST will never be wrong, your own reading abilities most often will.
I don't know a complete solution right now, but I suggest you spend some time looking at existing tools for computing software metrics. Nesting depth is a typical metric and there should be tools around.
If you can't find anything, you can at least fall back to writing something like an Eclipse plugin. In that case, you could simply load the Java file in the Eclipse editor, and Eclipse performs all the hard work for you and gives you the AST for free. Determining the nesting depth of a given AST is then rendered a simple task. Developing a prototype for that shouldn't take more than a few hours. And it's easy to extend it to cover your whole project and have it answer questions like "which java file in our project has the maximum nesting depth and what depth is that?". But then again.. someone else will surely point out an existing tool that already does this and much more.
I82Much's answer will certainly get you there, but feels a little like cheating.
Knowing little about your project, I would think that a simple stack mechanism with a max value record would do the trick push on { and pop on }. Once you have that basic model working, simply add the special case of control statements with one line bodies (this is valid for if, for, while ...). In those cases, you'll be looking for those keywords, followed by ( and a ). Once you've encountered that combination, if the scan encounters either another control statement or a semi-colon before it encounters a { then this is one of those special cases and you should push (using a special marker indicating to pop on ; rather than }).

Categories