java

Creating a Oracle IN clause with more than 1000 values

Instead of
select name from table1 where id in (1,...,2500)
use a disjunction of IN clauses:
select name from table1 where id in (1,.. .,1000) or id in (1001,..,2000) or id in (2001,..,2500)

In the attachment you can find helper methods, which are creating the IN query automatically for you (either with a Query or Criteria).

Query usage example:
List idList = Arrays.asList(1L, ... , 2500L);
String queryString = "update table1 set verarbeitungsStatus = 'DONE' where {INQUERY}";
query = JPAUtil.createInDisjunctionQuery(entityManager, queryString, "id", idList);
query.executeUpdate();

Criteria usage example:
Criteria criteria=entityManager.unwrap(Session.class).createCriteria(Entity1.class);
JPAUtil.createInDisjunction(idList, criteria, "id");
criteria.list();

Taggings:

Building a webapp using java

If you want to build a new webapp from scratch you should use a building tool and a framework for the webapplication part.

I suggest using maven as building and dependency management tool.
With maven you just have to configure which libraries you want to use and it will download the library and it's sources (if available) automatically for you. Even the classpath is handled by maven.

As Framework for webapplications Spring-MVC is a good choice.
Just go to the spring-mvc homepage and get the needed dependencies for maven and you have everything you need to start.

To get Spring to work in the application server you have to do the following:

  • Register the SpringContextLoaderListener in the web.xml of your web application
  • Register the Servlet for all URL-Pattern you want to serve with your web app
  • In the application concext you have to register an URL-Handler
  • Create the Controller beans in the application context or configure the package scanning
  • Create the Controller classes

In the Controller classes you can now register methods for specific URLs.

Now you have everything you need for a REST web application.

For a more detailed description of each step look at the official spring tutorial: http://docs.spring.io/docs/Spring-MVC-step-by-step/

Taggings:

How can i create fast and easily a web application using java (and MVC)

Using Servlets directly in an application server is not flexible enough and too much code and too complex for simple tasks like providing a webservice interface (REST/SOAP) The solution should contain everything needed to create a new project and describe the concepts of the used tools/frameworks.

Execute a Windows Native Command via Java

I hava used Standard Java to solve this. Detailed Comments are below:

public class ExecuteCmd {
public static void main(String[] args) throws Exception {
//the process to be started -> netstat -> shows some statistics about open connections
String[] processArgs = new String[]{"netstat"};
//the process itself
Process process = new ProcessBuilder(processArgs).start();

//get only the inputStream, because we don't want to send command's to process
BufferedReader processReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String received;
while ((received = processReader.readLine()) != null){
System.out.println(received);
}
processReader.close(); //clase it
System.out.println("process ended");
}
}

Execute a Windows Native Command via Java

A Windows native Command like for example "netstat" or any other should be executed inside a Java Application. The Application is able to read the output that the native command is producing.

Make a Screenshot and Send an Email with Java Application

I have used
Standard Java,
Java Mail API and
Java Activation Framework
to solve the problem. Detailed description is commented in the sourcecode below.

Java sourcefile content :

public class SendMail {

public static void main(String[] args) {

/**
* create a screenshot
*/
try {
//capture screen as image
BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
//create directory to store the image to
File folderForSaving = new File("C:\\screenshot_folder");
if(!folderForSaving.exists()){
folderForSaving.mkdir();
}
//store screenshot into folder
ImageIO.write(image, "png", new File("C:\\screenshot_folder\\screenshot.png"));
} catch (HeadlessException | AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

/**
* we also want to create some text file
*/

String text = "some text inside the file";
try {
File file = new File("C:\\screenshot_folder\\example.txt");
if(!file.exists()){
file.createNewFile();
}
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
} catch ( IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}

/**
* here beginns the email part
*/

final String username = "your_username@gmail.com"; //sender's email
final String password = "your_password"; //sender's password

/**
* setup properties for gmail's smtp server
*/
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

/*
* create a session
*/
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your_username@gmail.com"));//senders email
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("some_other_email@xyz.com")); // receivers email
message.setSubject("Testing Subject");

// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();

// Fill the message
messageBodyPart.setText("hi, how are you?");

// Create a multipart message, for the body text and the attachment(s)
Multipart multipart = new MimeMultipart();

// Set text message part
multipart.addBodyPart(messageBodyPart);

// attachment 1
messageBodyPart = new MimeBodyPart();
String filename = "C:\\km_ws14\\some_text_file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);

// attachment 2
messageBodyPart = new MimeBodyPart();
filename = "C:\\screenshot_folder\\screenshot.png";
source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);

// Send the complete message parts (body text and the attachments)
message.setContent(multipart );

//send
Transport.send(message);

System.out.println("Done");

//delete files after sending
File file1 = new File("C:\\km_ws14\\some_text_file.txt");
File file2 = new File("C:\\km_ws14\\some_video.mp4");
if (file1.exists()) {
file1.delete();
}
if (file2.exists()) {
file2.delete();
}

} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}

Make a Screenshot and Send an Email with Java Application

Sending an email with Java. The Application can connect to some email provider server. The Application should be able to make screenshots and send them via email. It should be possible to create the Email-Subject, Body text, and to add Attachments.

Taggings:

Debugging Aids using Temporal Visualization

One way to debug running programs without interrupting the is to visualize the value of the variable through recording read or write accesses on variables. For instance we created an Eclipse plugin which captured all accesses on selected code variables by examining watchpoints, provided by the Java Debug Interface. The read accesses as well as the write accesses were then tracked in a diagram, in order to make it possible to the code developer to inspect the value history of variables over the runtime. In case a variable history showed distortions, the developer had therefore a hint at which point of runtime his program might have failed.

Taggings:

How to Debug time critical code without stopping it

Software is oftenly time dependent. For instance if it interacts with another component on a remote server, the interaction might be time critical, which means that it shall not be stopped or interrupted as it otherwise might change the behavior of its system. The problem is, that even such software is prone to errors, but in case its runtime is stopped in order to debug the error it might change its behavior which might make it difficult to find out the problem behind the error.

JBehave plugin for eclipse

jBehave plugin brings the following features:
- Step auto-completion
- Syntax highlighting
- Step hyperlink detection and link to corresponding Java step method
- Step validation, detecting both unimplemented steps and ambiguous steps

How to install and use the jBehave plugin:
- In Eclipse go to Help > Install New Software
- Add the new site location http://jbehave.org/reference/eclipse/updates/
- Select JBehave Eclipse feature and click next
- Take defaults for the rest of the prompts
- Restart Eclipse

Create a jBehave story
- right click on the package where you want to place you feature file
- select New->Other and the jBehave->New Story wizard
- in the Story dialog, name the story file name
- click finish

Example file:
Sample story

Narrative:
In order to communicate effectively to the business some functionality
As a development team
I want to use Behaviour-Driven Development

Scenario: A scenario is a collection of executable steps of different type
Given step represents a precondition to an event
When step represents the occurrence of the event
Then step represents the outcome of the event

Create a class with the step automation from a scenario
- right click on the package you want to put the step automation
- select New->Class
- in the New Java Class enter the class name you have choosen
- click finish

For the example scenario file above we could genearte the following step implementations

package com.joe.steps;

import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import org.jbehave.core.steps.Steps;

public class ExampleSteps extends Steps{

@Given("step represents a precondition to an event")
public void givenStepRepresentsTheOccurrenceOfTheEvent(){
//ToDo implementation
}

@When("step represents the occurrence of the event")
public void whenStepRepresentsTheOccurrenceOfTheEvent(){
//ToDo implementation
}

@Then("step represents the outcome of the event")
public void thenStepRepresentsTheOccurrenceOfTheEvent(){
//ToDo implementation
}
}

A simple way for running the tests is:
private static Embedder embedder = new Embedder();
private static List storyPaths = Arrays
.asList("[[Package]]/[StoryName].story");

public static void main(String[] args) {
embedder.candidateSteps().add(new ExampleSteps());
embedder.runStoriesAsPaths(storyPaths);
}

Taggings:

Pages

Subscribe to java