Go Premium for a chance to win a PS4. Enter to Win

x

Java

98K

Solutions

32K

Contributors

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

Share tech news, updates, or what's on your mind.

Sign up to Post

#TodayILearned: #Gradle for #EclipseIDE is quite stubborn when it comes to adding a JVM container to one's #Java projects.
 
Every time I update the JVM (in this case to 1.8.0_152) I need to tell Eclipse and Gradle which JVM to run, and which JVM to apply to my Java projects. When we tell Gradle to apply the java plug-in to a project, it automatically inserts some random JRE that isn't defined anywhere. It most certainly isn't the SDK that my projects need.
 
To solve this, we can set the Eclipse classpath from the Gradle build script, after we tell Gradle to apply the eclipse plug-in to a project. It looks like this:
 
def sdkName = 'SDK 1.8.0_152'
def sdkContainerPrefix = 'org.eclipse.jdt.launching.JRE_CONTAINER'
def sdkContainer = sdkContainerPrefix +  '/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/' + sdkName

eclipse.classpath.containers sdkContainer

And then Gradle nicely adds TWO (2) JVM containers: the random JRE it defined in some unknown location, plus the SDK we just specified.
 
(Note: the SDK specified above bears the name 'SDK 1.8.0_152'. This is a custom name chosen by me. It is the same as I chose in Eclipse' preferences for Java -> Installed JREs. In my set-up, it is the only JRE I specified, and therefore the default.)
 
To fix this, with Gradle 4.3.1, we get to undo part of what Gradle's java plug-in does. Instead of the above instruction, we do this:
 
project.afterEvaluate {
  project.eclipse.classpath {
    containers.removeAll …
0
Concerto Cloud for Software Providers & ISVs
LVL 5
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

#TodayILearned how to get Gradle to deploy my application distributions and their dependencies to target application servers and library repositories.
 
It has been a missing piece in the automation of my deployments. Gradle already generates the application distributions, but the deployment there-of still was a manual affair.
 
My applications usually are grouped in suites. All applications in a suite share the same base library. That gets assembled and deployed first. Both happen via Gradle. For deployment, I use Gradle's uploadArchives task, from its Java-Library plug-in. This is my script:
 
uploadArchives {
  repositories {
    flatDir {
      dirs localLibFolder
    }
    flatDir {
      dirs sourceRepository
    }
    flatDir {
      dirs targetLibFolder
    }
  }
}
 
My script fills in folder paths for the parameters localLibFolder, targetLibFolder, and sourceRepository.
 
The script also uses that targetLibFolder  in my custom task of type Copy, that generates the individual application distributions. Each app will be distributed in a handful of flavors, and they need to know where to find the libraries on which they depend. Those are stored in the targetLibFolder.
 
Next, another custom task of type Copy depends on my custom task generateDistribution, and copies the distribution to a target folder on the target app server.
 
Each distribution and deployment gets timestamped, so multiple versions can exist next to each other.
 
The last challenge I …
0
We are almost up to Java 9 and there still seems to be no way of copying streams in Java without putting all the boilerplate. So i still seem to need THIS
Please let me know if i'm wrong
0
 
LVL 28

Expert Comment

by:rrz
The first thing I wrote with Java 9.
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/inOut")
public class InOut extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    response.setContentType("text/plain");
		request.getInputStream().transferTo(response.getOutputStream());
	}
}

Open in new window

and called it with
<html>
	<body>
        <form action="inOut" method="post">
		    param1:<input type="text" name="p1"/>
			param2:<input type="text" name="p2"/>
            <input type='submit' value='Submit'/>
        </form>
	</body>
</html>

Open in new window

0
 
LVL 86

Author Comment

by:CEHJ
There are probably other instances of other long overdue boilerplate breakers too, but i can't think of them

Of course with my stream copier, you can decide about the closure of both streams ;)
0
Just saw some advertisement where there was code catching a null pointer exception. Are people really out there catching null pointer exceptions. Seems like poor coding style when you can check if the variable is null before hand. We have also been using Java annotations to mark something as null able or not null. This has been really helpful in making potential null pointers compile time errors. Just a random thought.
2
#TodayILearned that sometimes, the #Java #CharBuffer can't give an #array of the #CharSequence it #wrap ped.
 
That happened with a #StringBuilder instance, which implements CharSequence.
 
A CharBuffer's array() method normally returns the char[] array that backs it. But the method will throw an #UnsupportedOperationException if no such array is available. And that is exactly the case I encountered today, when I had it wrap a StringBuilder.
 
So instead, we use CharBuffer.get(dest), in which we define dest as a char buffer of the desired size.
 
In my case:
 
final char[] buffer = new char[input.length()];
CharBuffer.wrap(input).get(buffer);
 
Happy coding!
0
A technology that has been really helpful as a Java developer is the ability to hot swap code using a technology like jRebel. Not having to restart the application server every time I make a change has really sped up development.
1
Last chance! Today is the final day to enroll in courseofmonth-native.JPGJuly’s Course of the Month, which prepares you for HTML5 certification. Premium Members, Team Account members, and Qualified Experts unlock this course for free as part of their membership! Once you enroll, you’ll have 30 days to take the course.
4
Boasting Java's speed.
 
Java suffers the myth that it is slow. Those who perpetuate this myth, seldomnly explain exactly what's slow. Benchmarks that do exist, oppose this myth in some cases, and strengthen it in others.
 
So here's some anecdotal evidence to boast Java's speed.
 
I've been developing a JavaFX-based data-editing GUI, to be used by lay people. Its start up from the IDE (Eclipse) is so fast, that its first screen gets displayed in under 3 seconds.
 
Now, I'm assuming that it'll be a bit slower on a client computer, where the JVM isn't running yet. And those computers might be restricted in memory, slowing down the application over all.
 
I'm also developing and maintaining several tens of data-integration applications, for which I frequently run integration tests.
 
Running on their application server, from starting in Windows Task Scheduler, to the moment where they read and archive their input file, tends to take less 5 to 10 seconds.
 
Running in my copy of their IDE (Eclipse), from starting in JUnit, to the moment they read and archive their input file, tends to take 2 to 5  seconds.
 
A factor in the difference between start-up times between IDE-run or Task-Scheduler-run is, well, the Windows Task Scheduler. My IDE might have a bit more memory to run, but the individual applications get restricted in the same way as they are on the app server. Maybe JUnit performs some wizardry that keeps the compilation "hot"?
 
Yes, I have seen some of …
2
 
LVL 7

Expert Comment

by:Brian Matis
Good to hear! Personally, I've never learned any Java (the syntax has always just looked really weird to me—but I'm sure part of that is just that I'm only a hobbyist, with only some basic experience in C, ASP, PHP, and Python) but I've certainly heard some of the grumbling of Java's speed. I've always been a bit intrigued to learn some Java, especially given its popularity, and it's nice to hear a positive viewpoint. Thanks for sharing!
0
3
 
LVL 54

Author Comment

by:Scott Fell, EE MVE
I don't think I shared it for how to catch a bullshitter, but more for the good points to think about in how we work.  A lot of this may be standard operating procedures in their daily lives and others may not.  

My big takeaway is understanding the problem objectively and asking the right questions before forging ahead,.  What problem is this going to solve, what are the costs (not just $$ but time/people),

Some good points for day to day work process.
3
 
LVL 11

Expert Comment

by:Jeffrey Dake
I totally agree, there are some good points in there about questions we should ask ourselves before we continue developing. I have seen plenty of "refactors" that made the code more reusable but there were no plans to reuse the code. By the time another developer got the chance to reuse it, the original assumptions were no longer valid and another refactor was needed.

As developers we should always be trying to balance how we solve problems with the benefits of how we solve them.
3
#TodayILearned that #OData presents a problem for #XSLT. The #JSON element named "@odata.context" can't be translated into an #XML element with the same name, using XSLT 2 or 3 as provided in #Java by #Saxonica.
 
The problem is that XSLT uses that @ in XPATH statements to match element attributes, and in other places within curly brackets, like {@attribute}, to copy that attribute's content into the output.
 
The solution is to differentiate between nodes/attributes that do, and ones that don't contain an @-sign,  and either replace() or translate() that into something else.
 
In my case, I use fx:json-to-xml() from XSLT3, implemented by Saxonica, to transform received JSON-formatted data into raw XML. This leads to a map element that contains elements array, boolean, map, null, number, and string. The JSON element names become the XML elelements' "@key" attribute.
 
A 2nd XSL transformation produces the domain-specific XML-format. As stated above, we must take heed with producing the "@odata.context" element. This can occur, a.f.a.i.k., in either a null element or a string element. So, we differ between those with and without an "@" in the key attribute:
 
Without:
<xsl:template match="xf:string[@key][not(contains(@key, '@'))]">
<xsl:element name="{@key}">
<xsl:value-of select="text()" />
</xsl:element>
</xsl:template>
 
With:
<xsl:template match="xf:string[@key][contains(@key, '@')]">
<xsl:variable name="newName"><xsl:value-of select="translate(@key, '@', '')" …
0
 

Author Comment

by:A.E. Veltstra
Hi, Andrew Leniart. Funny, we have the same first name.
 
Thank you for your concern. I did search before I found a way to solve my problem and published it. As far as the search could tell me, I'm literally the first person to encounter and solve this problem. Hence the publication.
0
 
LVL 12

Expert Comment

by:Andrew Leniart
My apologies Andrew, I didn't read your entire post carefully enough and took it to be a problem you were still trying to solve. I think the hash tag # at the start threw me off! These new fandangled ways you younger generation have of talking can get confusing for oldies like me! lol..

Cheers :)
1
Vote for the Most Valuable Expert
LVL 7
Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

#TodayILearned a #gotcha with #Predicate in #Java. You can learn, too!
 
Here's 1 way to write a Predicate:
 
static Predicate<String> isEmpty() {
    return p -> 0 == p.length();
}

And here's another way:
 
static Predicate<String> isEmpty = (p) -> {
    return 0 == p.length();
}
 
Erm. What's the difference?
 
Well. The first is a method that generates a function, and you call it like this:
 
boolean test = isEmpty().test("Hello!");
 
Or, from a stream in a method in a class named World:

.filter(World::isEmpty())
 
The second is a field with a pregenerated function, and you call it like this:
 
boolean test = isEmpty.test("Hello!");
 
Or, from a stream in a method in a class named World:

.filter(World.isEmpty)
 
Notice how the method-based Predicate still has to generate a function, and thus has to be called with parentheses.
 
The field-based predicate already generated its function by the time it gets called, and because it's a field, no parentheses are used for accessing it.
 
Why Predicates at all, rather than a simple boolean-returning method?
 
Beats the heck out of me. 
2
Apple is no longer just for the tech-savvy millennial and professional crowd. Check out today's product release, where developers as young as 7 and as old as 84 are releasing new apps to the App Store. https://www.apple.com/apple-events/june-2017/
6
 
LVL 14

Expert Comment

by:Joseph Hornsey
Wait... Apple users are "tech-savvy"?  Huh.
3
Is Java a terrible first programming language to learn? Do you agree with Stanford switching their intro course to JavaScript? Or would you have picked something else?

https://thenextweb.com/dd/2017/04/24/universities-finally-realize-java-bad-introductory-programming-language/#.tnw_AFXiESVy
2
 
LVL 11

Expert Comment

by:Jeffrey Dake
I definitely think there is something better to start with than Java, but not sure JavaScript is the answer.
1
 
LVL 7

Author Comment

by:Brian Matis
I imagine the appeal of JavaScript is how you can run it in a browser and don't need to worry about dev environment setup or learning a command line to get started.

What language would you choose, Jeff?
0
When I went to school to get my degree in SE I had the importance of Java Docs beaten into me on a daily basis. Now that I am in industry, I find that Java Docs are the last place I look - instead opting for Q&A sites or google searches for blog articles due to the specificity of the problems I come across.

I was never encouraged to do this sort of research in practice, in fact, it was often discouraged. There definitely seems to be a disconnect in school professors and their outdated methods and actual industry practices. Maybe in schools that are research oriented this is better since engineering professors are actively working in their field, but at my public university I had professors who were perplexed by syntactic sugar that is now common place such as the
for ( x : y )

Open in new window

loop.
5
 
LVL 9

Author Comment

by:James Bilous
I had an interesting situation where I earned my BS and MS in computer science from the same university in a blended program ( I earned both degrees at the same time ). My school prided itself in project based learning, in fact the motto of the school was "Learn by Doing". I definitely got a great education because of this philosophy and most of the professors were great, but the ones that taught fundamentals (read 101, 102, 103 programming courses) were absolutely horrific.

By the time I hit graduate level coursework the professors were, again, fantastic. These were all instructors who were very active in industry and research and many had side companies they worked on. I think the critical missing piece from the earlier instructors was their lack of participation in the real world. Of course, all of these professors were tenured, so that should tell you something.
3
 

Expert Comment

by:Daniella Barion
I believe that when we study the theories, we can develop better and also discuss and bring new contributions.
2
Used Jsoup for the first time this week on trying to load in an html page and parse it.  It was really handy to use for parsing the dom.  Really cool to be able to use more CSS like selectors to do what I needed.

https://jsoup.org/
5
 
LVL 7

Expert Comment

by:Brian Matis
@kyle: I love the idea of being able to share it more! But I don't understand the "convert to article" idea... Isn't this a little short for an article?
0
 
LVL 17

Expert Comment

by:Kyle Santos
It is if you're following Jeff.
0
Ever write code that you look at, and think "no language should let me do this".


private void createURLButtonAction() throws Exception
      {
            m_view.m_loadURLButton.setOnAction(e -> {
                  try{
                        loadURL(m_view.m_urlField.getText());
                  }
                  catch (Exception exception)
                  {
                        
                  }
            });
      }
0
 
LVL 17

Expert Comment

by:Kyle Santos
*plane flies over my head*
2
 
LVL 9

Expert Comment

by:James Bilous
*no framework
Don't blame the lambdas
0
Do you think endorsements will be well moderated?
2
 
LVL 17

Expert Comment

by:Kyle Santos
*downvote*

:3
0
 
LVL 7

Expert Comment

by:Craig Kehler
Sure, but in this case I can just walk out my office door and "moderate" the user personally :P
2

Java

98K

Solutions

32K

Contributors

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.