Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

11 October, 2013

OAF : Disable Global Buttons in Page

I write snippet code to disable global buttons in OAF page.
You can add the following code to Controller class of the page that you want to disable global buttons inside it.

    public void processRequest(OAPageContext pageContext, OAWebBean webBean) {
        super.processRequest(pageContext, webBean);

        OAPageLayoutBean pageLayoutBean = 
            (OAPageLayoutBean)pageContext.getPageLayoutBean();
        pageLayoutBean.prepareForRendering(pageContext);

        OAGlobalButtonBarBean globalButtonsBean = 
            (OAGlobalButtonBarBean)pageLayoutBean.getGlobalButtons();
        globalButtonsBean.setRendered(false);
    }

Thanks

09 October, 2013

Route HTTP to HTTPS in HttpClient

I published before an article about JAVA : Get html Page Source through Website URL that HttpClient was used to send Get method and get Response.

Sometime developer want to route Http to Https when invoking Urls.
So You can use WebClientWrapper.wrapClient to do this issue.

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

public class WebClientWrapper {
    public static HttpClient wrapClient(HttpClient base) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {

                public void checkClientTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = base.getConnectionManager();
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", ssf, 443));
            return new DefaultHttpClient(ccm, base.getParams());
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}



Thanks

04 October, 2013

JAVA : Get html Page Source through Website URL


To get source code of website page you can use HttpClient ,I will  send GET method and then get response.
The response has content of website URL.

I used Apache HttpClient package to implement this task.

In this Class I used  getStringFromInputStream method that was I was posted before in Convert InputStream to String.

here you can find Class do this task
Note I use static method WebClientDevWrapper.wrapClient, you can find its code in the article Route HTTP to HTTPS in HttpClient

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

public class WebsiteSource {
    public static String getSource(String url) throws Exception {
        String retValue = "";
        HttpClient httpclient = new DefaultHttpClient();
        WebClientDevWrapper.wrapClient(httpclient);
        try {
            HttpGet httpget = new HttpGet(url);

            // Execute HTTP request
            HttpResponse response = httpclient.execute(httpget);

            //Get status : Response Ok will be HTTP/1.1 200 OK
            System.out.println(response.getStatusLine());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    retValue =
                            WebsiteSource.getStringFromInputStream(instream);

                } catch (RuntimeException ex) {
                    httpget.abort();
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    try {
                        instream.close();
                    } catch (Exception e) {
                    }
                }
            }

        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return retValue;
    }

    private static String getStringFromInputStream(InputStream is) {

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();

        String line;
        try {

            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();

    }

    public static void main(String[] args) {

        try {
            String content =
                WebsiteSource.getSource("http://mahmoudoracle.blogspot.com/");
            System.out.println(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Thanks

30 September, 2013

JAVA : Convert InputStream to String

You can use the following snippet to convert InputStream to String
 
    private static String getStringFromInputStream(InputStream is) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

Thanks

16 September, 2013

Random Numbers in Java

Previously I posted  about Generate Random Passwords in Oracle that was using PLSQL.
Today I will post about java randoms.

Java provides two classes to generate random numbers: Random and SecureRandom.
Random is faster than SecureRandom, but it uses a 48 bits seeds which is not enough for the long type.
Moreover, it is not 'random enough' for cryptography. SecureRandom, is slower than Random, but can be used for cryptography.

The following code example shows how to generate a random number within a range for int, long, float and double.

Note rangeStart , rangeEnd is range period of generated numbers .

        int rangeStart = 50;
        int rangeEnd = 100;

        SecureRandom secRandom = new SecureRandom();
        int inclusive = rangeEnd - rangeStart + 1;
        int exclusive = rangeEnd - rangeStart;


        int randomIntInclusive = secRandom.nextInt(inclusive) + rangeStart;
        int randomIntExclusive = secRandom.nextInt(exclusive) + rangeStart;

        System.out.println("randomIntInclusive : " + randomIntInclusive);
        System.out.println("randomIntExclusive : " + randomIntExclusive);

        long randomLongInclusive =
            (secRandom.nextLong() % inclusive) + rangeStart;
        long randomLongExclusive =
            (secRandom.nextLong() % exclusive) + rangeStart;

        System.out.println("randomLongInclusive : " + randomLongInclusive);
        System.out.println("randomLongExclusive : " + randomLongExclusive);

        float randomFloat = (secRandom.nextFloat() * exclusive) + rangeStart;
        System.out.println("randomFloat : " + randomFloat);

        double randomDouble =
            (secRandom.nextDouble() * exclusive) + rangeStart;
        System.out.println("randomDouble : " + randomDouble);

The output will be
randomIntInclusive : 60
randomIntExclusive : 73
randomLongInclusive : 11
randomLongExclusive : 63
randomFloat : 65.19333
randomDouble : 84.14220368726888



Thanks

12 September, 2013

Close Resources in Java

In java when using any resources like Files, Streams, Database Connection and DataSets etc .... , you must close resources at end of processing at your code.

For Example : Streams 

        File f = new File("myFile.txt");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(f);
            // Do something...
        } catch (FileNotFoundException ex) {
            // Display error message
        } finally {
            // Closing resource
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    //Here , Hide Exception
                }
            }
        }

All previous code in Blue color are used to close resources.
So to save time and make code more readability you can use IOUtils Appache packages  to close resources quietly
      finally{
   IOUtils.closeQuietly(fos);
      }


For Example : Database Statement

 finally{
   DBTransaction txn = this.getDBTransaction();
        String sqlStmt =
            "Begin plsqlCode; END;";
        CallableStatement callStmt =
            txn.createCallableStatement(sqlStmt, DBTransaction.DEFAULT);
        try {
             //Write your code here to work with CallableStatement 
        } catch (SQLException e) {
             //Handle SQL Exception
        }finally {
            // Closing resource
            if (callStmt != null) {
                try {
                    callStmt .close();
                } catch (SQLException ex) {
                    //Here , Hide Exception
                }
            }
        }

All previous code in Blue color are used to close resources.
So to save time and make code more readability you can use DBUtils Appache packages  to close resources quietly

      finally{
   DbUtils.closeQuietly(callStmt );
      }

Thanks

08 September, 2013

Run JavaScript from Native Java

I wrote in previous post Execute Javascript code from Java Code how to execute java script in Oracle ADF.
But in this post I will explain how to call Javascript from native Java.



The following code snippets will illustrate how to evaluate Javascript code and invoke functions and get return value.

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class CallJavaScript {
    public static void callJsCode(String jsCode) throws ScriptException,
                                                        NoSuchMethodException {

        // Retrieving the Javascript engine
        ScriptEngine se =
            new ScriptEngineManager().getEngineByName("javascript");
        try {
            se.eval(jsCode);
        } catch (ScriptException e) {
            e.printStackTrace();
        }

        try {
            Invocable jsinvoke = (Invocable)se;
            System.out.println("myFunction(2) returns: " +
                               jsinvoke.invokeFunction("myFunction", 2, 4));
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }
}

Then You can call this code using for example
       try {
            String jsCode =
                "function myFunction(x,y){return x+y;}";
            CallJavaScript.callJsCode(jsCode);
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }      

The output of previous code will be

myFunction(2) returns: 6.0

Thanks

ADF : Scope Variables

Oracle ADF uses many variables and each variable has a scope. There are five scopes in ADF (Application, Request, Session, View and PageFl...