Saturday, September 8, 2018

One-To-Many with JSF/Eclipselink using netbeans

Hi,

I am writing this post regarding JSF/Eclipselink JPA using netbeans, although, it is logical and straight forward in netbeans website, but it still has some pitfalls need to be pointed out (and I spent the last two days in one of them although I knew it before).

Let us start demonstrating with simple example in netbeans. In order to create the below example,  you need prerequisites

  • Postgressql jdbc driver as I'm using postgres database
  • Database connection from service tab
  • Jeddict plugin for database modelling(add this to netbeans from tools->plugins->downloaded->add plugins)
Now to the example


  1. create new web application choosing glassfish as your application server and JSF framework
  2. create jdbc connection pool and jdbc resource such as jdbc/example JNDI
  3. using jeddict create Jpa Modeler 
  4. drag and drop entities 
  5. put the required names, attributes and relationships
  6. go to the project and create a persistence unit selecting the JNDI you created earlier
  7. copy the persistence unit name to the properties of the diagram and save
  8. right click on the Jpa Modeler screen and click on Generate Source Code, then put entity in the Package name then click on Generate
  9. right click on the project and JSF Pages from Entity Classes, name Session Bean Package facade and JSF Classes Package entity.domain
  10. Now you will have all the controllers/Managed Beans and EJBs/Session Beans in addition to the entities which were created already in the previous step, in addition to the jsf pages for all the entities CRUD operations
  11. NOW, pay attention to the pitfalls so you application works correctly,
  • all entities will not be serializable by default neither have (no argument constructor) nor (equals and hashcode functions), WHICH are must in order to have your application works properly.
Optional, when you create the departments and navigate to employees to create employee, you will find drop down list looks like the snapshot, and you can rectify this using toString() in the respective entity which is Department here

Troubleshooting few issues:
  • Sometime the application doesn't work properly if you have already created tables with the same name but not the same attributes before, and you can fix it by making the persistence as Drop and Create, then Clean and Compile and Run. DON'T forget to return the persistence back it to Create.
  • Sometimes you face issue of "Unreachable, identifier 'departmentController' resolved to null" for example which can be solved by restarting the glassfish.




Wednesday, August 15, 2018

JSF ManyToMany application tips

Hello,

As many of you know that you can use netbeans in an extremely efficient way to deploy your application entities, backing beans, facade (session beans) and even pages for CRUD operations using "JSF Pages from Entity Classes" or "PrimeFaces Pages frin Entity Classes".

However, this works perfectly when you are using the second (PrimeFaces one) while it doesn't in the first (JSF one).

JSF works well with OneToMany relationships while it doesn't (automatically creating h:selectManyListbox for example) in the ManyToMany relationships. So, you find yourself have to create (h:selectManyListbox) manually and it will not work as you would have the same classic conversion issue from String to List of Objects. In order to get around this you can follow the below simple way.

Create your multiple options control code,

<h:selectManyListbox value="#{furnitureController.materials}">
<f:selectItems value="#{materialController.findAll()}" 
var="c"
itemLabel="#{c.material}" 
itemValue="#{c.id}" />
</h:selectManyListbox >

create the findAll() method in the controller materialController to retrieve the list of the options to you

public List<Material> findAll() {
        return ejbFacade.findAll();
}

Add list of string variable, setter and getter in the controller  furnitureController to hold the primary key values until processing.

private List<String> materials;

    public List<String> getMaterials() {
        return materials;
    }

    public void setMaterials(List<String> materials) {
        this.materials = materials;
    }

Lastly, update the create method with the following code BEFORE the getFacade().create(current);
to loop on the list of IDs and add sub objects to the main object and therefore associate them together in the joined table.

for (String id : materials) {
          current.addMaterial(materialFacade.find(Long.parseLong(id)));
}

Tuesday, July 31, 2018

Using Pdfbox to fill PDF template with data which might be in Arabic

Hello,

In my previous post I shared how we can create a pdf and write in Arabic in it.

However, in many cases there is a need to fill a pdf template with data and that is prone to mistakes, time consuming and boring too. So, in order to rectify this it is better to keep the data in a database and generate the form pre-populated with the static data then worry about adding the additional data only.

Prerequisites:
-pdfbox v.2.0.11
-ICU v.62
-arial.ttf

You can download pdfbox-app-2.0.11.jar which is the latest as of the time I am writing this post from here.

You can download ICU from here

Download arial.ttf from here

Go to netbeans or the IDE you are using and them to your Libraries and create the below desktop program.

package pdftester;

import com.ibm.icu.text.ArabicShaping;
import com.ibm.icu.text.ArabicShapingException;
import java.io.File;
import java.io.IOException;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDTextField;

public class PDFtester {

    public static void main(String[] args) throws IOException, ArabicShapingException {

        PDDocument doc = PDDocument.load(new File("c:\\data\\letters\\letter.pdf"));
        PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
        PDResources formResources = acroForm.getDefaultResources();

        PDType0Font font = PDType0Font.load(doc, new File("C:\\data\\arial.ttf"));

        formResources.put(COSName.getPDFName("F0"), font);
        String s = "نحن معشر الانبياء امرنا ان نخاطب الناس على قدر عقولهم";
        PDTextField formField = (PDTextField) acroForm.getField("15");
        formField.setDefaultAppearance("/F0 0 Tf 0 g");
        formField.setValue(new StringBuilder(new ArabicShaping(ArabicShaping.LETTERS_SHAPE).shape(s)).reverse().toString());

        doc.save("c:\\data\\letters\\filling.pdf");
        doc.close();
    }
}


There is a small glitch in the pdf document which that when you click inside the field letters are getting disconnected and style converts into LTR (Left to Right). I am working on figuring the issue, but the pdf is printable and it will work fine.

Monday, July 30, 2018

Using Java and Pdfbox to create PDF with Arabic text

Hello,

I am writing this post to demonstrate how to create pdf file using pdfbox library, more importantly how to write in Arabic in it which is not very common topic people talk about.

Simply, the below represents the code to do that, and depending on your scenario you can dig more on the rest of the library, it is open source and very rich.

Prerequisites:
-pdfbox v.2.0.11
-ICU v.62
-arial.ttf

You can download pdfbox-app-2.0.11.jar which is the latest as of the time I am writing this post from here.

You can download ICU from here

You can download arial.ttf from here and put it in c:\data\ for the example to work

Go to netbeans or the IDE you are using and them to your Libraries and create the below desktop program.

package pdftester;

import com.ibm.icu.text.ArabicShaping;
import com.ibm.icu.text.ArabicShapingException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;

public class PDFtester {

    public static void main(String[] args) {

        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        PDPageContentStream pageContentStream;
        try {
            pageContentStream = new PDPageContentStream(doc, page);
            pageContentStream.beginText();
            pageContentStream.setFont(PDType0Font.load(doc, new File("c:\\data\\arial.ttf")), 20);
            pageContentStream.newLineAtOffset(250, 750);
            String s = "سامر احمد";
            pageContentStream.showText(new StringBuilder(new ArabicShaping(ArabicShaping.LETTERS_SHAPE).shape(s)).reverse().toString());
            pageContentStream.endText();
            pageContentStream.close();
            doc.save("c:\\data\\test.pdf");
            doc.close();
        } catch (IOException ex) {
            Logger.getLogger(PDFtester.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ArabicShapingException ex) {
            Logger.getLogger(PDFtester.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Monday, April 9, 2018

Rest API using python

In this post I would like to share my experience with Rest APIs using python as a consumer, this will be very useful and innovative in term of operation and automation.

Most of the time system (Storage, UNIX, Windows, Network) admins complain about the amount of work, many repetitive tasks are done in a tedious way, critical mistakes can happen due to doing many tasks at the same time. Apart from all that, recently the self service approach started to rise as a way to offload the tasks to the end user, budget control and reducing interactions. Also not to forget to mention the agility of the environment which will involve the swift creation and removal of environments.

Probably, all of what mentioned above is doable in UNIX and Windows servers, if not most of them. Now, but what about appliances, such as switches, storage, and any embedded systems. Recently, all new well supported systems started to come with enabled Rest APIs, to facilitate integration with other systems, reporting and monitoring.

Using Rest APIs of specific system will have few requirements:
  • Understanding HTTP requests
  • Understanding JSON/XML data
  • Programming language (Python) with request module installed
  • Documentation of how to use the system Rest API
Briefly, the HTTP requests are revolving around GET, POST, PUT, DELETE, UPDATE and some other types which we don't require usually in our Rest API operations. GET is used for list/retrieving objects, POST for creation of objects, PUT for updating attributes, UPDATE for updating the objects and intuitively DELETE for deleting objects.

Object here represents element to be Listed, Created or Deleted..etc. as per the above type of requests.

Security is important element in the Rest APIs that is why there are couple of ways to secure Restful resources. Github for example is using Basic Authentication, OAuth2 token and OAuth2 key/secret check here for more information.

Basic authentication is the usual used Rest API security method, which is basically Username and Password concatenated with ":" in the middle, and prepended by "Basic " passed in a base64 encrypted format.

Here is how you can demonstrate the use of base64 encoding (you don't need to do this in your code as HTTP protocol will do this automatically in the background) and how it will look like in the header parameters:

I am using python version 3.x

#!/usr/bin/python3.6

import base64
import sys

print (base64.b64encode("user:pass".encode()).decode())


The HTTP will have the below parameter in the request header:
KeyValue
AuthorizationBasic dXNlcjpwYXNz

You can use google chrome plugin called Postman to troubleshoot or debug your requests.

Now, starting to make GET requests (without authentication) is easy by following few steps in github..

#!/usr/bin/python3.6

import json
import requests
requests.packages.urllib3.disable_warnings()

response = requests.get('https://api.github.com/users', verify=False)
json_data = json.loads(response.text)
print(json_data)

The above code will get you the list of users in github in json format, you can use online json formatter to view it in a readable format.

Similarly, we can use this to interact with EMC VPLEX:

#!/usr/bin/python3.6

import requests, json

requests.packages.urllib3.disable_warnings()

url = "https://Cluster_IP/vplex/clusters/Cluster_ID/virtual-volumes/*"
payload = (UsernamePassword)
r = requests.get(url, auth = payload, verify = False) #make get request passing the credentials
data = json.loads(r.text) #read response as json and data will be a dictionary variable
print(data) #printing data
print(json.dumps(data)) #printing will be in a nice readable format

Using Rest API I developed interface for deleting VPLEX volumes, which takes less than a minute. This task used to take 15 to 30 minutes using CLI(which was the only available way to delete the volume). Therefore, the productivity significantly increased, and this way can help in automating provisioning and destroying Demo environments, which is the current trend in demonstrating new technologies.