Feeds:
Posts
Comments

So, this post serves as a wiki for how to deploy a wildfly application into openshift and connect it to a MySql database.

In my scenario, i had a maven web application created locally, as well as a local database. As a newbie to Openshift, i spent sometime learning commands and performing my deployment. As such, i’ll go step-by-step, from the domain configuration to the actual application testing for anyone doing the same.

1. Setting the domain

The first thing you have to do is to get an openshift account. To do so, just access openshift and follow their steps… (i’ll skip this part). After doing so, access applications and add a new application.

In this page, you’ll find a list of cartridges (kind of like bundles) which can be configured for the application. Select a wildfly instance (8, 9 or 10, it’s up to you). If at this time, you have not yet configured your domain, you’ll be asked to do so, as well as provide your application name. For instances, if you write your application name as ‘app1’, and your domain as ‘mydomainxpto’, your application address will follow a configuration similar to http://app1-mydomainxpto.rhcloud.com. At the end of the page, confirm your cartidge selection and wait (can take a while).

After completing this step, you’ll receive admin/password for your wildlfy instance. Save them. Perform similar steps for the mysql database by adding it from the application detail page. I recommend adding phpmyadmin as well. Save the credentials.

At this stage, your ‘server’ is ready to receive the code.

2. Setting the access tools

When shifting to code, you should verify that you possess the rhc tools and git installed. If not, install them. You’ll need ruby (add executables to path when installing) and git, and then install rhc tools by doing ‘gem install rhc‘. These steps are all very well described on the openshift getting started page.

3. Setting the application git repository 

To start building your app, start by selecting a folder where you want your git repository to be in. After that, open a git cmd window on it.

At this stage, we already built our application on the server, so we’ll use clone to get the app into our local repository. To do that, access the openshift page and obtain the ssh key for your app. It is right there on your application details page. Do ‘git clone <sshkey>‘. Ok. You now should have your app in your selected folder.

4. Editing the standalone.xml

As we’ll be using MySQL, we have to obtain the datasource to place it in our persistence.xml. There is no need to search for username, password, hosts or ports. Openshift already creates this for you in the standalone.xml file through environment variables that are set at deployment. The MySQLDS datasource however comes disabled by default so access the file, and edit the parameter ‘enabled’ to true (similar to what is in the ExampleDS). This file can be found inside .openshift/config in your app folder.

5. Editing your pom.xml 

Your created app folder already has a pom.xml. Do not delete it. Instead, access your local application pom.xml and copy all dependencies into the app’s pom.xml. Leave the profile as it is. Generally, you’ll not need to change it.

6. Copy all of your code 

Access your local application maven folder and copy the src folder into your new app folder.

7. Edit persistence.xml 

Access the persistence.xml on the new app and edit its datasources as it is declared on the standalone.xml file. For MySQL, it normally looks like ‘java:jboss/datasources/MySQLDS’.

8. Create your database

By rule, your database name will be the same as the application name (in our example ‘app1’). This is changeable. Note however that you’ll need to edit the standalone.xml datasource.

Some applications create their own tables, but if yours does not, simply access use phpmyadmin to create them using a SQL script. To access phpmyadmin just add ‘/phpmyadmin‘ to your application url.

 9. Deploy the application

To deploy the application, start by accessing your main app folder via cmd. Then use ‘git add –all’ followed by ‘git commit -m “Some message”‘. After doing this, do ‘git push’. The server will restart, compile your application and deploy it. It all goes well, it should be up and running at your defined url.

10. Troubleshooting

As we know, in programming, things rather do not go well in their first try. As such, here’s some tips to help:

A) The git push cmd does not provide a lot of information regarding the deployment of the app into the wildfly server. Rhc tools has a command to help you check the log files in an updated way, so you can actually see what’s happening during the deploying. Open a new cmd window, and do ‘rhc tail -a <yourappname>‘.

B) The wildfly administration panel can also assist in editing operations or verifying errors. For instance, rather than changing the standalone.xml file regarding the datasource, you can do it here. To access it, you have to call ‘rhc port-forward app1‘. This will allow you to access server the admin panel via a localhost address.

C) Persistence errors. These are normally the biggest problem. Verify that entity table names are according to what’s on the mysql instance (uppercase problems are common!). Entering hibernate in pom.xml with provided scope can be a solution.

 

And this is it! Hope it helps any one. 🙂

 

 

Quick post that cost me the entire afternoon. 🙂

If you’re trying to launch applications from a java application and having trouble with relative paths to files that those applications require, use the ProcessBuilder class.

With it, you can call the “directory” method where you can specify the root directory for the app you’re about to launch. By doing so, the app will run exactly in the same way that it would if it was launched natively.

Here’s an example:


ProcessBuilder builder = new ProcessBuilder();
builder.command("java", "-jar", rootPathOfApp+ "app.jar");
builder.directory(new File(<rootPathOfApp>));
Process process = builder.start();

Hope it helps!

Came up with some issues on configuring a new instance of Glassfish 4 when i already had a Glassfish 3 instance installed and running as a service.

The following are some steps to install both Glassfish 3 and 4 on a Windows Server environment:

1) Stop existing services

2) Change your existing service DisplayName if necessary. For this use (as an example, consider a existing domain1, the default name):

</pre>
sc config domain1 DisplayName= "GlassFish 3"

3) Go to the Glassfish bin folder and do:

</pre>
asadmin create-service --name "GlassFish3" domain1

4) Go to the domain bin folder and run the newly created service with the ‘start’ instruction.

5) Repeat steps 3 and 2 in this order for the GlassFish4 instance.

Cheers!

Quick post today 🙂

If you’re trying to pass parameters from client code (Javascript functions for instances) to your ManagedBeans/EJBs there’s a simple way to do it – Use hidden values.

Now, let’s suppose that i want each selection/change the user makes in a radio set to be persisted in my database . As it’s obvious, if the form is submitted, JSF will assign the parameters to your Managed Beans classes. However, if by some chance, the user doesn’t submit the form, then you’ll lose your data.

So, how to do it. We’ll need three items:

1) A Javascript function. Something like this:


function changedValues(buttonValue){

document.getElementById('formsTab:hiddenButton').value = buttonValue;
remoteChangeCommand();
}

2) Two HTML tags on your form (form id is formsTab btw)


<h:inputHidden id="hiddenButton" value="#{yourManagedBean.buttonValue}"/>

<p:remoteCommand name="remoteChangeCommand" process="hiddenButton"/>

…and of course your radio set:

<input type="radio" name="Opt1" value="1" onclick="changedValues('1');"/>
<input type="radio" name="Opt2" value="2" onclick="changedValues('2');"/>

3) Finally, your Managed Bean:


@ManagedBean(name = yourManagedBean")
@ViewScoped
public class MyManagedBean {

private String buttonValue;

...

public void setButtonValue(String buttonValue) {
this.buttonValue = buttonValue;

//call business logic here!! Ex:
....persist(buttonValue);
}

public String getButtonValue() {
return buttonValue;
}

}

So, how does this work. Well its something like this. When a radioButton is selected, the JavaScript function is called.

This function does two things:
A) First, sets the hidden input tag with the argument from the call.
B) Second, calls the remoteCommand.

The remoteCommand is a special Primefaces tag that allows you to set a Managed Bean Parameter. In this case, we call setButtonValue method (this is abstracted of course by JSF).
The rest is a small trick. We just have to put a small call within the ManagedBean set operation to another method to perform the required business operation (persist in this case).

Hope it helps someone! Well, it helped me!! 😀
Cumps!

Important post today 🙂

How to create a flawless login logout with JSF Facelets and a Java Application Server (JBoss, Glassfish) without much effort. Previously i’ve posted a similar article but small errors persisted. This post corrects that.

Four items are required:

1) Include a <META HTTP-EQUIV=”refresh” CONTENT=”15″> on your login page. This is make your login page refresh preventing an error with our methodology regarding context.

2) Edit your web.xml with the following. This will indicate that when a ViewExpiredException happens then the browser will redirect the client to its login page


<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/faces/login.xhtml</location>
</error-page>

Also add a session timeout:


<session-config>
<session-timeout>
30
</session-timeout>
</session-config>

3) Implement a phase-listener for checking your credentials and preventing pagejumps. First, add the following to your faces-config.xml:


<lifecycle>
<phase-listener>yourpackge.security.AuthorizationListener</phase-listener>
</lifecycle>

Here’s your Java Class:


public class AuthorizationListener implements PhaseListener {

public void afterPhase(PhaseEvent event) {

FacesContext facesContext = event.getFacesContext();
String currentPage = facesContext.getViewRoot().getViewId();

boolean isLoginPage = (currentPage.lastIndexOf("login.xhtml") > -1);
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);

if(session==null){
NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
nh.handleNavigation(facesContext, null, "loginPage");
}

else{
Object currentUser = session.getAttribute("username");

if (!isLoginPage && (currentUser == null || currentUser == "")) {
NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
nh.handleNavigation(facesContext, null, "loginPage");
}
}
}

public void beforePhase(PhaseEvent event) {

}

public PhaseId getPhaseId() {
return PhaseId.RESTORE_VIEW;
}
}

Im sum, this class will check if your session credentials are ok and if not, redirect you to the login page.This will happen everytime a request is made on your app. Btw, ‘LoginPage’ is a navigation handler for login.xhtml specified on faces-config.xml

4) To complement this you’ll only need a Authentication class which puts your credentials on session with the following:


FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username", idUser);

To close it, simply do the following:


FacesContext.getCurrentInstance().getExternalContext().invalidateSession();

And that’s it! Hope it helps!! Cumps!! 😀

Didn’t really know how to title this post well because its a really tricky issue. Nonetheless i hope who needs it, is able to find it 🙂

If you’re creating a web system with multiple apps which share the same database, be very careful with your persistence settings.

If one app changes the database and the other has already loaded data from it, the data will not updated due to default caching. A better example, imagine that App1 loads database data. Then, App2 changes an entry on that database and exits. App1 will NOT update its state and keep outdated information. This can be critical to the integrity of your data and global functioning of your system.

The solution however is pretty simple. This process is a default configuration by ORM/Persistence Units like EclipseTopLink. To change it, simply add the following to your persistence file, inside the persistence-unit tag:

<shared-cache-mode>NONE</shared-cache-mode>

There. No more outdated info. The downpart of this method is that everytime a call is made by your frontend/business which involves database info, a new call on the database will be needed. If your app is aimed at massive utilization, this can be an issue on efficiency. To decrease this, another possibility is to use Enable Selective or Disable Selective. With it and a @Cache annotation on your entities, your specify which entities must be reloaded (or not). Here’s a link for it – http://wiki.eclipse.org/EclipseLink/Examples/JPA/Caching

Cheers!! 🙂

Hi there! Very quick note today 🙂

If you’re having issues with your h:commandButton with your ManagedBean refusing to run the action method, don’t dispair. There is a simple tutorial to fix it:

1) Watch out for your validation method syntax. The validation method in your ManagedBean MUST return a String and take no argument when using the ‘action’ attribute of your h:commandButton. This will be the page where you’ll end up (if you want,you can also return “” and use navigation strategies to redirect the user) .  However, if you’re using actionListener, you must use ActionEvent as an argument to your validation method.

2) Check if your h:commandButton its nested inside a h:form. It must be. Also, it’s better to also use f:view and nest the form inside it.

3) Don’t go around the web searching, ‘oh my god my form action doesn’t work!!’. Most times the error is in the attributes inside the form, not in the method itself. A common one is to forget those ‘required=true’ on your h:inputText and simply push the “submit” button without filling them. Most times, nothing will happen (especially when you don’t have error messages) and leave you wondering!

Well that’s it!! Cumps! 😀

Quick tutorial today!

If you’re experimenting on JSF and wanna check out the features that ajax can provide you but like me, you don’t like your business code on the client side, then this is for you 😀

First, of all, a super important note. Don’t mix your imports when dealing with ManagedBeans!! Make sure you’re either using CDI or JSF. For this example, i’ll be using javax.faces.bean package. Please make sure this is ok. It can give you really weird bugs…

So, what’s the idea. Let’s try and make a simple validator (which can be done in JSF ressorting to other methods but that will do as an example) which checks if a field is a INT and if not, then shows an error message.

We’ll need a .xhtml for the page and the managedBean.

In your .xhtml put something like this:


<h:form id=myForm>
<h:inputText value="#{bean.myvalue}" styleClass="someStyle">
<f:ajax event="change" render="error_sub" listener="#{bean.validateMyValue}"/>
</h:inputText>

<h:panelGroup id="error_sub">
<h:outputText value="Incorrect Format for Value!!" styleClass="someErrorStyle"  rendered="#{bean.show}" />
</h:panelGroup>
</h:form>

Two important/cool notes in this html.

First, ajax in JSF will only work if nested in a form.

Second, to make a ‘section/tag’ of your page disappear you cannot use rendered on that same tag with ajax! Ajax only sees rendered=true tags! So, to do that, apply the ajax to a ‘superior’ tag, like i’m doing with panelGroup. In your validation function however, you can use a boolean like ‘show’ which can be used to declare if outputText is to be display or not.

Got it? Ajax invokes validateMyBean which sets show to true or false… Renders error_sub again which this time, in case of an error, is display or not according to ‘show’. Got it? This is very important.


import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean(name="bean")
@RequestScoped
public class MyBean {

private String myvalue;
private boolean show;

//Getters and Setters for myvalue!! Don't forget these!!

public boolean validateMyValue(){
try{
show=false;
Integer.parseInt(myvalue);
}
catch(Exception e){
System.out.println("Error...");
show=true;
return false;
}
return true;
}
}

The above bean is used to place the variables, your getters and setters and your validation method.

Simple right? Well… now it is! 😀

Cumps!!

 

Hi there!

If you’re developing a website with JSF v2 and are having issues with page jumping/direct access when credentials should be applied first, then this post is for you. 🙂

Normally, when applying such mechanisms one resorts to filters with servlet association. However, with JSF this can be tricky because (in my experience at least) the filter is initialized before your managed beans and FacesContext are. This is an issue for most examples out there, because the filter will give ‘null’ when accessing the sessionScoped bean (or in any other managedBean) where your credentials are supposed to be checked. So, how to achieve this? Using a PhaseListener.

A PhaseListener is a something that you can apply whenever a ‘request’ happens. So before the actual call to your ManagedBean happens, a routine can be called in your PhaseListener. With it, you can limit right there what will happen. So, first here is your listener:


public class AuthorizationListener implements PhaseListener {

public void afterPhase(PhaseEvent event) {

FacesContext facesContext = event.getFacesContext();
String currentPage = facesContext.getViewRoot().getViewId();

boolean isLoginPage = currentPage.lastIndexOf("index.xhtml");
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
Object currentUser = session.getAttribute("username");

if (!isLoginPage && (currentUser == null || currentUser == "")) {
NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
nh.handleNavigation(facesContext, null, "loginPage");
}
}

public void beforePhase(PhaseEvent event) {
}

public PhaseId getPhaseId() {
return PhaseId.RESTORE_VIEW;
}
}

What we are describing here is that whenever a call is made for a page, then first, the attribute ‘username’ must be checked. For this however we also need two more things. First, declare your faces-config.xml like so:


<faces-config version="2.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">
<navigation-rule>
<from-view-id>/*</from-view-id>
<navigation-case>
<from-outcome>loginPage</from-outcome>
<to-view-id>index.xhtml</to-view-id>
</navigation-case>
</navigation-rule>

<lifecycle>
<phase-listener>org.views.security.AuthorizationListener</phase-listener>
</lifecycle>

</faces-config>

And your login method (which will be in your ManagedBean):


public void login(){

boolean result = businessBean.checkCredentiais(username, password);

if(result){
try {
errorMessageLogin="";
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username", username);
FacesContext.getCurrentInstance().getExternalContext().redirect("main.xhtml");

} catch (IOException ex) {
Logger.getLogger(UserCredentiaisView.class.getName()).log(Level.SEVERE, null, ex);
}
}
else{
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username", "");
errorMessageLogin = "Credentials not supported.";
}
}

And that’s it! Just don’t forget to clear your credentials in your logout method!! 😀

Stay cool! 🙂

Hi there!

If you need to store random passwords on your database and want to encrypt them for more safety, good for you! 😀

Here are some easy steps to help you on the way. First a Sha1Convertion Class:


public class Sha1Convertion {

public Sha1Convertion(){
}

public String makeSHA1Hash(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.reset();
byte[] buffer = input.getBytes();
md.update(buffer);
byte[] digest = md.digest();

String hexStr = "";
for (int i = 0; i < digest.length; i++) {
hexStr +=  Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return hexStr;
}
}

Second, a random generator for your passwords:


public class PassPhrase {
/** Length for password */
public static final int MIN_LENGTH = 10;

/** The random number generator. */
protected static java.util.Random r = new java.util.Random();

/*
* Set of characters. This is limited to numbers and letters for error issues.
*/
protected static char[] goodChar = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'2', '3', '4', '5', '6', '7', '8', '9', };

/* Generate a Password object with a random password. */
public static String getNext() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < MIN_LENGTH; i++) {
sb.append(goodChar[r.nextInt(goodChar.length)]);
}
return sb.toString();
}

}

Finally, your main (this is for 20 passwords):


Sha1Convertion shc = new Sha1Convertion();

for (int i = 0; i < 20; i++) {
String pass = PassPhrase.getNext();
System.out.println("Current - " + pass);
String result = shc.makeSHA1Hash(pass);
System.out.println("SHA1 - " + result);
}

And that’s it!! Stay cool! 🙂