Pages

Friday, August 15, 2014

Drop all tables, constraints, and sequences within an Oracle schema


Drop all tables, constraints, and sequences within an Oracle schema.
refer link: https://snipt.net/Fotinakis/drop-all-tables-and-constraints-within-an-oracle-schema/
BEGIN

FOR c IN (SELECT table_name FROM user_tables) LOOP
EXECUTE IMMEDIATE ('DROP TABLE ' || c.table_name || ' CASCADE CONSTRAINTS');
END LOOP;

FOR s IN (SELECT sequence_name FROM user_sequences) LOOP
EXECUTE IMMEDIATE ('DROP SEQUENCE ' || s.sequence_name);
END LOOP;

END;

Friday, July 4, 2014

Hibernate Caching

refer to :
 http://www.javabeat.net/introduction-to-hibernate-caching/
http://www.tutorialspoint.com/hibernate/hibernate_caching.htm


Tuesday, June 17, 2014

Getting a list of Security Groups and Accounts for a user through the API

link : https://blogs.oracle.com/kyle/entry/getting_a_list_of_security

eg : 
- Request:   /cs/idcplg?IdcService=GET_USER_PERMISSIONS
- Respone :
{
    "LocalData": {
        "IdcService": "GET_USER_PERMISSIONS",
        "StatusCode": "-1",
        "StatusMessage": "JSON strings must begin with a '",
        "StatusMessageKey": "!csJsonStringMustBeginWithBrace",
        "changedMonikers": "",
        "changedSubjects": "",
        "dName": "manager01",
        "dUser": "manager01",
        "idcToken": "",
        "localizedForResponse": "1",
        "refreshMonikers": "",
        "refreshSubMonikers": "",
        "refreshSubjects": ""
    },
    "ResultSets": {
        "DocumentAccounts": {
            "currentRow": 0,
            "fields": [
                {
                    "name": "dDocAccount"
                },
                {
                    "name": "privilege"
                }
            ],
            "rows": [
                [
                    "#none",
                    "7"
                ],
                [
                    "managerdir",
                    "1"
                ],
                [
                    "manager01",
                    "15"
                ],
                [
                    "managerdirbtc",
                    "15"
                ]
            ]
        },
        "SecurityGroups": {
            "currentRow": 0,
            "fields": [
                {
                    "name": "dGroupName"
                },
                {
                    "name": "privilege"
                }
            ],
            "rows": [
                [
                    "contentEditor",
                    "15"
                ],
                [
                    "BTC",
                    "15"
                ],
                [
                    "contentRepo",
                    "1"
                ],
                [
                    "Public",
                    "1"
                ]
            ]
        },
        "UserAttribInfo": {
            "currentRow": 0,
            "fields": [
                {
                    "name": "dUserName"
                },
                {
                    "name": "AttributeInfo"
                }
            ],
            "rows": [
                [
                    "manager01",
                    "account,#none,7,account,managerdir,1,account,manager01,15,account,managerdirbtc,15,role,QuanTriBTCRole,15,role,authenticated,15"
                ]
            ]
        },
        "UserSecurityFlags": {
            "currentRow": 0,
            "fields": [
                {
                    "name": "flag"
                },
                {
                    "name": "value"
                }
            ],
            "rows": [
                [
                    "IsAdmin",
                    "0"
                ],
                [
                    "AdminAtLeastOneGroup",
                    "1"
                ],
                [
                    "IsSubAdmin",
                    "0"
                ],
                [
                    "IsSysManager",
                    "0"
                ],
                [
                    "IsContributor",
                    "1"
                ],
                [
                    "ActAsAnonymous",
                    "0"
                ]
            ]
        }
    }
}

Friday, May 30, 2014

af:showPopupBehavior with Parameter

http://www.jobinesh.com/2011/03/fails-when-used-with-for-buttons-action.html
eg :
on button using click event  :
 <af:commandMenuItem text="#{language.BUTTON_XOA}"                      
                                      id="cmi4">
               <af:setPropertyListener from="#{row.data}" to="#{pageFlowScope.myBean.currRow}" type="action" />
                     <af:showPopupBehavior popupId=":::deleteConfirmDialog" triggerType="click"/>
                  </af:commandMenuItem>
popup define:

  <af:popup id="deleteConfirmDialog">
      <af:dialog id="d1" title="#{language.THONG_BAO}"
                 dialogListener="#{pageFlowScope.themMoiPhamViKhaiThac.deleteConfirmDialogListener}">
        <af:outputText value="#{language.DELETE_CONFIRM_MESSAGE}" id="ot3"/>
      </af:dialog>
    </af:popup>

popup listener:
    public void deleteConfirmDialogListener(DialogEvent dialogEvent) {
        if(!DialogEvent.Outcome.ok.equals(dialogEvent.getOutcome())) return;
     
        if(currRow != null){
          //
        }
    }

Saturday, April 26, 2014

Delete all .svn folders using Windows Command Prompt



You can use the following command to delete all .svn folders in your subversion directory recursively.
FOR /R . %f IN (.svn) DO RD /s /q %f
refer link : http://www.forouzani.com/delete-all-svn-folders-using-windows-command-prompt.html

Friday, April 25, 2014

How to get all classes names in a package ?

see detail
http://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection?lq=1
http://stackoverflow.com/questions/15519626/how-to-get-all-classes-names-in-a-package


with https://code.google.com/p/reflections/
 Reflections reflections = new Reflections("my.project.prefix");

     Set<Class<? extends SomeType>> subTypes = 
               reflections.getSubTypesOf(SomeType.class);

     Set<Class<?>> annotated = 
               reflections.getTypesAnnotatedWith(SomeAnnotation.class);

native code : http://stackoverflow.com/questions/15519626/how-to-get-all-classes-names-in-a-package

public final class ClassFinder {
   
    private final static char DOT = '.';
    private final static char SLASH = '/';
    private final static String CLASS_SUFFIX = ".class";
    private final static String BAD_PACKAGE_ERROR =
        "Unable to get resources from path '%s'. Are you sure the given '%s' package exists?";

    public final static List<Class<?>> find(final String scannedPackage) {
        final ClassLoader classLoader =
            Thread.currentThread().getContextClassLoader();
        final String scannedPath = scannedPackage.replace(DOT, SLASH);
        final Enumeration<URL> resources;
        try {
            resources = classLoader.getResources(scannedPath);
        } catch (IOException e) {
            throw new IllegalArgumentException(String.format(BAD_PACKAGE_ERROR,
                                                             scannedPath,
                                                             scannedPackage),
                                               e);
        }
        final List<Class<?>> classes = new LinkedList<Class<?>>();
        while (resources.hasMoreElements()) {
            final File file = new File(resources.nextElement().getFile());
            classes.addAll(find(file, scannedPackage));
        }
        return classes;
    }

    private final static List<Class<?>> find(final File file,
                                             final String scannedPackage) {
        final List<Class<?>> classes = new LinkedList<Class<?>>();
        final String resource = scannedPackage + DOT + file.getName();
        if (file.isDirectory()) {
            for (File nestedFile : file.listFiles()) {
                classes.addAll(find(nestedFile, scannedPackage));
            }
        } else if (resource.endsWith(CLASS_SUFFIX)) {
            final int beginIndex = 0;
            final int endIndex = resource.length() - CLASS_SUFFIX.length();
            final String className = resource.substring(beginIndex, endIndex);
            try {
                classes.add(Class.forName(className));
            } catch (ClassNotFoundException ignore) {
                ignore.printStackTrace();
            }
        }
        return classes;
    }

// test
   public static void main(String[] args) {
        List<Class<?>> classes = ClassFinder.find("***.model");
        for(int i = 0; i < classes.size(); i++){
            System.out.println("<class>" + classes.get(i).getName() +"</class>");
        }
    }

}

Sunday, March 23, 2014

JPA - Entity SequenceGenerator




@Entity
@NamedQueries({
@NamedQuery(name = "Departments.findAll", query = "select o from Departments o")
})
public class Departments implements Serializable {
@Id
@Column(name="DEPARTMENT_ID", nullable = false)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "DEPARTMENTS_GEN")
@SequenceGenerator(name="DEPARTMENTS_GEN", sequenceName = "DEPARTMENTS_SEQ")

private Long departmentId;
@Column(name="DEPARTMENT_NAME", nullable = false, length = 30)
private String departmentName;
// setters and getters
}


Thursday, March 6, 2014

Unit testing with Junit in JDeveloper 11G

refer links:
http://www.oracle.com/technetwork/articles/adf/part5-083468.html
http://www.oracle.com/technetwork/articles/server-side-unit-tests-096611.html
http://tamanmohamed.blogspot.com/2011/06/unit-testing-with-junit-4x-in.html
http://biemond.blogspot.com/2009/07/unit-test-your-composite-application.html


..... updating

Thursday, February 27, 2014

Why use @PostConstruct ?

http://docs.oracle.com/javaee/5/api/javax/annotation/PostConstruct.html
http://stackoverflow.com/questions/3406555/why-use-postconstruct

@PostConstruct (or post-construct, if declared in deployment descriptors) was introduced in Java EE 5 to all component types, including all web components (Servlet 2.5).


- The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection. The method annotated with PostConstruct MUST be invoked even if the class does not request any resources to be injected.Only one method can be annotated with this annotation.

*** The method on which the PostConstruct annotation is applied MUST fulfill all of the following criteria 

- The method MUST NOT have any parameters except in the case of EJB interceptors in which case it takes an InvocationC ontext object as defined by the EJB specification. 
- The return type of the method MUST be void.
- The method MUST NOT throw a checked exception.
- The method on which PostConstruct is applied MAY be public, protected, package private or private
- The method MUST NOT be static except for the application client
- The method MAY be final. - If the method throws an unchecked exception the class MUST NOT be put into service except in the case of EJBs where the EJB can handle exceptions and even recover from them.

Why use @PostConstruct ?

  • because when the constructor is called, the bean is not yet initialized - i.e. no dependencies are injected. In the @PostConstruct method the bean is fully initialized and you can use the dependencies.
  • because this is the contract that guarantees that this method will be invoked only once in the bean lifecycle. It may happen (though unlikely) that a bean is instantiated multiple times by the container in its internal working, but it guarantees that @PostConstruct will be invoked only once.

in JSF context : use @PostConstruct for @ManagedBean

http://stackoverflow.com/questions/15773350/initialization-of-list-in-a-jsf-managed-bean?lq=1
    There are implications regarding the scope of the managed bean
  1. @RequestScoped: In a managed bean with this annotation, the method will be called per submit of the JSF view concerned. A @RequestScoped bean is destroyed and recreated with every request, The implication of this is that depending on your setup, the list initialized in the @PostConstructmay be reset to empty or default values during each request. Under certain circumstances, conversion errors may occur as a result of the re-initialization of the list mid-JSF request.
  2. @ViewScoped: In a managed bean with this annotation, you're guaranteed to have the @PostConstruct method run once, if and only if you're dealing with the same instance of the @ViewScoped bean. If the viewscoped bean is destroyed and recreated, the @PostConstructmethod will run again.
  3. @SessionScoped: A bean with this annotation is created once and stays alive until the user's HTTP session ends. In this scenario, the @PostConstruct method is guaranteed to run once and only once until the bean is destroyed

Servlet init method vs PostConstruct method

http://javahowto.blogspot.com/2011/07/servlet-init-method-vs-postconstruct.html
invocation order and relationship of the two methods:
servlet class constructor --> PostConstruct --> init and init(ServletConfig)
So inside PostConstruct method at the second step, ServletConfig has not been initialized, and neither is ServletContext. CallinggetServletConfig() in PostConstruct returns null. Calling getServletContext() results in IllegalStateException in most servers (GlassFish 3, Tomcat 7 and JBoss 6), but returns null in Resin 4.
eg :
public class DpartmentBean {
    // service and resource inject
    @EJB
    HrSessionFacadeLocal hrService;
    // ui comp
    private RichTable departmentTable;
    public DpartmentBean() {
        this.departmentTable = new RichTable();
    }
             /**
                load data for table  when hrService injected
            */
    @PostConstruct
    public void initDepartmentTable() {
        if (hrService != null) {
            try {
                List<Departments> departments = hrService.getDepartmentsFindAll();
                this.departmentTable.setValue(departments);
            } catch (Exception e) {
                // TODO: Add catch code
                e.printStackTrace();
            }
        }
    }
}

Saturday, February 15, 2014

Invoke a method from Managed Bean when JSPX/JSFF (JSF fragment) Page Loads in ADF.


link refer
http://www.techartifact.com/blogs/2012/10/invoke-a-method-from-managed-bean-when-jspx-page-loads-in-adf.html
 implements PagePhaseListener
 public void beforePhase(PagePhaseEvent pagePhaseEvent) {
if (pagePhaseEvent.getPhaseId() == Lifecycle.PREPARE_MODEL_ID) {
onPageLoad();
}
}

public void afterPhase(PagePhaseEvent pagePhaseEvent) {
if (pagePhaseEvent.getPhaseId() == Lifecycle.PREPARE_RENDER_ID) {
// onPagePreRender();
}
}

public void onPageLoad() {
if (!AdfFacesContext.getCurrentInstance().isPostback()) {
// add your onPageLoad event here

// to set the View Criteria on the Iterator
doSomeOperation();  ///your custom method.
}

http://www.techartifact.com/blogs/2013/09/call-method-on-page-load-of-jsff-jsf-fragment-in-oracle-adf.html
 implements RegionController
public boolean refreshRegion(RegionContext regionContext)   // you need to override refresh region method.
{
int refreshFlag= regionContext.getRefreshFlag();
FacesContext fctx = FacesContext.getCurrentInstance();
//check internal request parameter
Map requestMap = fctx.getExternalContext().getRequestMap();
PhaseId currentPhase=(PhaseId)requestMap.get("oracle.adfinternal.view.faces.lifecycle.CURRENT_PHASE_ID");
if(currentPhase.getOrdinal()==PhaseId.RENDER_RESPONSE.getOrdinal())   // write custom logic of correct lifecycle phase.
{
Object showPrintableBehavior =
requestMap.get("oracle.adfinternal.view.faces.el.PrintablePage");
if (showPrintableBehavior != null)
{
if (Boolean.TRUE == showPrintableBehavior)
{
ExtendedRenderKitService erks = null;
erks =
Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
//invoke JavaScript from the server
erks.addScript(fctx, "window.print();");
erks.addScript(fctx, "window.close();");

}
  }
regionContext.getRegionBinding().refresh(refreshFlag);
}
return false;
}
     
    public boolean validateRegion(RegionContext regionContext)
    {
        regionContext.getRegionBinding().validate();
        return false;
    }
     
    public boolean isRegionViewable(RegionContext regionContext)
    {
     return regionContext.getRegionBinding().isViewable();
    }
     
public String getName()
{
return null;


Wednesday, February 12, 2014

UCM - checkin without and hiding primary file

Doing check-ins without files in UCM
https://blogs.oracle.com/kyle/entry/check-ins_without_files_ucm

Hiding the Primary File field in UCM
https://blogs.oracle.com/kyle/entry/hiding_the_primary_file_field

Friday, January 24, 2014

Passing values from Page to Bean in JSF

refer to :
http://gik.firetrot.com/index.php/2013/07/19/passing-values-from-page-to-bean-in-jsf/


There are three ways to pass values from page to JSF ManagedBean:
  1. Passing value with f:param tag – using action attribute
  2. Passing value with f:attribute tag – using actionListener attribute
  3. Passing value with f:setPropertyActionListener tag – no need for additional dealing, value allplies directly to bean property!
example : 
case 1:
<p:commandButton value="Pass Param" action="#{PassParamBean.passParam}">
        <f:param name="someParamHolder" value="THIS is VALUE_OF_PARAM !!!" />    </p:commandButton>

case 2:
<p:commandButton value="Pass Attribute" actionListener="#{PassParamBean.passAttributeListener}"
        ajax="true" update="someAttributeId">
        <f:attribute name="someAttributeHolder" value="THIS is VALUE_OF_ATTRIBUTE !!!" />    </p:commandButton>
case 3: 
 <p:commandButton value="Pass Property"
       ajax="true" update="somePropertyId">
       <f:setPropertyActionListener target="#{PassParamBean.someProperty}" 
           value="THIS is VALUE_OF_PROPERTY !!!" />
</p:commandButton>

in managed  bean:
 package passvalue;

import java.io.Serializable;
import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

public class PassParamBean implements Serializable {
    private static final String DEFAULT_OUTCOME = "pass_value";

    private String someParam;
    private String someAttribute;
    private String someProperty;

    public String passParam() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();

        Map<String, String> params = externalContext.getRequestParameterMap();
        someParam = params.get("someParamHolder");

        return DEFAULT_OUTCOME;
    }

    public void passAttributeListener(ActionEvent event) {
        UIComponent component = event.getComponent();
        Map<String, Object> attrs = component.getAttributes();
        someAttribute = (String) attrs.get("someAttributeHolder");
    }

// setters and getters

}

Thursday, January 16, 2014

Install Prosody from source on Centos 6.

https://prosody.im/downloads/source/
https://prosody.im/doc/installing_from_source
https://prosody.im/doc/configure

1. download & extract
wget --no-check-certificate  https://prosody.im/downloads/source/prosody-0.9.2.tar.gz
tar xvf prosody-0.9.2.tar.gz
cd prosody-0.9.2

2. install dependencies
yum install openssl openssl-* lua5.1 liblua5.1-dev libidn11-dev libssl-dev

3. configure & make install
./configure --ostype=PRESET
make install


note : Prosody's configuration is held in a single file, prosody.cfg.lua. on centos 6 you should find it in /usr/local/etc/prosody/prosody.cfg.lua

Install Maven on Linux

http://stackoverflow.com/questions/12076326/how-to-install-maven2-on-redhat-linux

From the command line; you should be able to simply do:
wget http://mirrors.digipower.vn/apache/maven/maven-3/3.1.1/binaries/apache-maven-3.1.1-bin.tar.gz
  1. Run command above from the dir you want to extract maven to (e.g. /usr/local/apache-maven)
  2. run the following to extract the tar:
    tar xvf apache-maven-3.0.4-bin.tar.gz
  3. Next add the env varibles such as
    export M2_HOME=/usr/local/apache-maven/apache-maven-3.0.4
    export M2=$M2_HOME/bin
    export PATH=$M2:$PATH
  4. Verify
    mvn -version