Hiển thị các bài đăng có nhãn Ecm Filenet. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn Ecm Filenet. Hiển thị tất cả bài đăng

Thứ Hai, 10 tháng 10, 2016

JAAS - J2C authentication data in websphere


  Map map = new HashMap();
    map.put(Constants.MAPPING_ALIAS,"TEST-ECM-CMNode01/ecm_admin");
    CallbackHandler callbackHandler = WSMappingCallbackHandlerFactory.getInstance().getCallbackHandler(map, null);

    LoginContext loginContext = new LoginContext("DefaultPrincipalMapping", callbackHandler);
    loginContext.login();

    Subject subject_1 = loginContext.getSubject();
    Set credentials = subject_1.getPrivateCredentials();

    PasswordCredential passwordCredential = (PasswordCredential) credentials.iterator().next();

    String username = passwordCredential.getUserName();
    String password = new String(passwordCredential.getPassword());

Chủ Nhật, 9 tháng 10, 2016

Get and Put properties on Document


   ObjectStore objectstore =//Get Object Store
                logger.info("Object Store Name :: "+objectstore.get_DisplayName());
                SearchScope search=new SearchScope(objectstore);
                String value = "abcd"
                String sql1= "Select * from DocumentClass where DocumentTitle = "+value;
                SearchSQL searchSQL=new SearchSQL(sql1);
                DocumentSet documents=(DocumentSet)search.fetchObjects(searchSQL, Integer.getInteger("50"), null, Boolean.valueOf(true));
                Document doc;
                Iterator it=documents.iterator();
                while(it.hasNext())
                {
                    doc=(Document)it.next();
                    doc.getProperties().putValue("Name", abc);
                    doc.getProperties().putValue("number", 123);
                    doc.getProperties().putValue("Salary", 200);
                    doc.save(RefreshMode.REFRESH);

                } 

Searching and Deleting documents API FileNet



  SearchScope search=new SearchScope(objectstore);
                String value = abc;
                String sql1= "Select * from DocClass where DocumentTitle = "+ Value;
                SearchSQL searchSQL=new SearchSQL(sql1);
                DocumentSet documents=(DocumentSet)search.fetchObjects(searchSQL, Integer.getInteger("50"), null, Boolean.valueOf(true));
                Document doc;
                Iterator it=documents.iterator();
                while(it.hasNext())
                {
                    doc=(Document)it.next();
                    logger.info("document name::"+doc.get_Name());
                    logger.info("deleting the document now:::");
                    doc.delete();
                    doc.save(RefreshMode.REFRESH);
                    
                }

Thứ Năm, 6 tháng 10, 2016

Search CE Object using SearchSQL (Content Engine API)



package createdoc_api;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Iterator;

import javax.security.auth.Subject;
import com.filenet.api.collection.ContentElementList;
import com.filenet.api.collection.RepositoryRowSet;
import com.filenet.api.constants.AutoClassify;
import com.filenet.api.constants.AutoUniqueName;
import com.filenet.api.constants.CheckinType;
import com.filenet.api.constants.ClassNames;
import com.filenet.api.constants.DefineSecurityParentage;
import com.filenet.api.constants.RefreshMode;
import com.filenet.api.core.Connection;
import com.filenet.api.core.ContentTransfer;
import com.filenet.api.core.Domain;
import com.filenet.api.core.Document;
import com.filenet.api.core.Factory;
import com.filenet.api.core.Folder;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.core.ReferentialContainmentRelationship;
import com.filenet.api.property.Properties;
import com.filenet.api.query.RepositoryRow;
import com.filenet.api.query.SearchSQL;
import com.filenet.api.query.SearchScope;
import com.filenet.api.util.Id;
import com.filenet.api.util.UserContext;

public class sql_query {

/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub

String uri = "http://ecmdemo1.ecm.ibm.local:9080/wsi/FNCEWS40MTOM/";
    String username = "P8admin";
    String password = "filenet";
    String v_id = null;
    // Make connection.
    Connection conn = Factory.Connection.getConnection(uri);
    Subject subject = UserContext.createSubject(conn, username, password, null);
    UserContext.get().pushSubject(subject);

    try
    {
       // Get default domain.
       Domain domain = Factory.Domain.fetchInstance(conn, null, null);
       System.out.println("Domain: " + domain.get_Name());

       // Get object stores for domain.
      // ObjectStoreSet osSet = domain.get_ObjectStores();
      /// ObjectStore store;
       //Iterator osIter = osSet.iterator();

       //while (osIter.hasNext())
       ///{
        //  store = (ObjectStore) osIter.next();
        //  System.out.println("Object store: " + store.get_Name());
      // }

       System.out.println("Connection to Content Platform Engine successful");
     
    // Create a document instance.
       ObjectStore os = Factory.ObjectStore.getInstance(domain, "CMTOS");
   
       String searchQ = "SELECT ID FROM CmAcmCaseFolder WHERE LP_ID_link = 2";
     
             SearchSQL sqlObject = new SearchSQL(searchQ);
           SearchScope searchScope = new SearchScope(os);

 

       // Execute the fetchRows method using the specified parameters.
       RepositoryRowSet myRows = searchScope.fetchRows(sqlObject, null, null, new Boolean(true));

       // You can then iterate through the collection of rows to access the properties.
       int rowCount = 0;
   
       Iterator iter = myRows.iterator();
       while (iter.hasNext())
       {
           RepositoryRow row = (RepositoryRow) iter.next();
                 
         //  String docTitle = row.getProperties().get("DocumentTitle").getStringValue();
           Id docId = row.getProperties().get("Id").getIdValue();
           v_id=docId.toString();      
           rowCount++;
           System.out.print(" row " + rowCount + ":");
           System.out.print(" Id=" + docId.toString());
           //if (docTitle != null)
           //{
            //   System.out.print(" DocumentTitle=" + docTitle);
           // }
          // System.out.println();                          
        }
     
    }
    finally
    {
       UserContext.get().popSubject();
    }
    System.out.println("a"+ v_id);    
 
}

}

Thứ Ba, 4 tháng 10, 2016

How to Use JNDI in websphere (get connect string database websphere)

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.Servlet;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * @version  1.0
 * @author
 */
public class JuliDataServlet extends HttpServlet implements Servlet 
{

 public void doGet(HttpServletRequest req, HttpServletResponse resp)
  throws ServletException, IOException 
 {
  doPost( req,  resp);
 }
 public void doPost(HttpServletRequest req, HttpServletResponse resp)
  throws ServletException, IOException 
 {
  Connection conn=null;
  PrintWriter out=resp.getWriter();
  try{
   //JNDI
   Context aContext = new InitialContext();
   DataSource aDataSource = (DataSource)aContext.lookup("java:comp/env/ExtDS");
   conn = aDataSource.getConnection();
   //JNDI end

   //raw JDBC for the same SAMPLEsample DB2 database 
   //Class.forName("COM.ibm.db2.jdbc.app.DB2Driver"); //need db2java.zip in the path 
   //conn = DriverManager.getConnection("jdbc:db2:sample"); //DB2
   //raw JDBC end

   String firstname="";
   String sql = "select firstnme, lastname from employee";
   Statement stm = conn.createStatement();
   ResultSet rst = stm.executeQuery(sql);
   for (int i=0; (i<10 && rst.next()); i++)  //only print 10 names
   {
    firstname =  rst.getString("firstnme");
    out.println("Hello "+ firstname+"," );
   }
   if(conn != null)
   {
    conn.close();
    System.out.println("Successfully closed");  
   }
  }
  catch (Exception e)
  {
   System.out.println(e);
  }
 
 }
}


==============================

ExtDS : Alias JNDI in websphere
=================================
Config file : ibm-web-bnd.html

<?xml version="1.0" encoding="UTF-8"?>
<web-bnd 
    xmlns="http://websphere.ibm.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee 
http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd"
    version="1.0">

   <resource-ref>
  <res-ref-name>ExtDS</res-ref-name>
  <jndi-name>ExtDS</jndi-name>
</resource-ref>
</web-bnd>

==================================
Config file : web.xml

<resource-ref>
    <description>
    Datasource connection to db</description>
    <res-ref-name>ExtDS</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>





Thứ Tư, 28 tháng 9, 2016

Dynamic Web Application Development  and deploy webSphere

AGENDA
  •  Web application development and deployment Steps
    – Web application tree structure
    – Write (and compile) the Web component code
    – Create deployment descriptor
– Build & Deploy Web Application
  • Configuring Web application
    – Web application deployment descriptor   (web.xml file)
  • Web Application Archive (*.WAR file)
    – *.WAR directory structure
    – WEB-INF subdirectory

A new project has been created with the standard structure of a Java web application. The WEB-INF/lib directory will later hold all the JAR files that the Java web application requires.



Step 1 : Create a Dynamic Web Project,

To create a Dynamic Web Project, click File menu then select New | Other | Web node | Dynamic Web Project leaf (Eclipse helps you organize your web applications using a type of project called a Dynamic Web Project). In the creation wizard, just type “FirstWebApp” as the project name and click the Finish button.


Step 2: Create file JSP

Right click over the folder “WebContent” and select “New” -> “Other”. Expand “Web” node and select “JSP File” and click Next.



Give the file name as “index.jsp” and click Next. Finally, select the “New JSP File (html)” from Select JSP Templatewindow and click Finish.
Edi the code of your FirstJSP.jsp file, as the modified file shown below. Save your work.
(changes are in bold)
<%@ page language=“java” contentType=“text/html; charset=ISO-8859-1″ pageEncoding=“ISO-8859-1″%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”><html><head>
<meta http-equiv=“Content-Type” content=“text/html; charset=ISO-8859-1″>
<title>Insert title here</title></head>
<body>
        <h1>Web Application Development Demo!</h1>
<form action=“MyFirstServlet” method=“get”>
Choose Course : 
<select name=“course”><option value=“Java SE”>Java SE </option><option value=“Java EE”>Java EE</option><option value=“J2ME”>J2ME</option></select>
<input type=“submit” value=“Submit” /></form>
</body>
</html>

Step 3:  Creating Servlet Code for processing the Client Request:
Create a servlet. Right click on the folder “src” and select New-> Other. Expand “Web” node and select “Servlet” from Select a wizard. Give the class name for the Servlet (e.g MyFirstServlet), click Next and Finish. Maintain the following data.

Now, your Servlet class file ‘MyFirstServlet’ will be opened in the editor window of your IDE.
Editing  your Servlet class  ‘MyFirstServlet
Select the entire code of your Servlet class file from the editor window and delete it & type the following code as shown below. Save your work.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyFirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();
String course=request.getParameter(“course”);
out.print(“You have Selected: “+course);
}}
Create deployment descriptor (web.xml)
The web.xml file provides configuration and deployment information for the Web components that comprise a Web application.
The web.xml file defines each servlet and JSP page within a web application. It also enumerates enterprise beansreferenced in the web application.
Deployment descriptor (web.xml) contains deployment time & runtime instructions to the Web container
Every web application has to have it.
The file must reside in the WEB-INF directory under the document root of a web application.



Configuration informations, such as Servlet deployment, Servlet parameters are specified in web.xml (Web Applications Deployment Descriptor)
Elements of web.xml: Configuring and Mapping a Servlet
First you configure the servlet. This is done using the <servlet> element. Here you give the servlet a name, and writes the class name of the servlet and defines its physical location of servlet class.

servlet:
For each servlet in the web application, there is a <servlet> element.
Second, you map the servlet to a URL or URL pattern. This is done in the <servlet-mapping> element. In the above example, all URL’s ending in .html are sent to the servlet.
Other possible servlet URL mappings are:  /myServlet,   /myServlet.do,  /myServlet*
servlet-mapping:
Each servlet in the web application gets a servlet mapping. The url pattern is used to map URI to servlets.

session-timeout:
<session-timeout>: The timeout for a session in minutes.
Welcome-file-list:
<welcome-file>: Specifies the index or home page of your web application.
   Note: In our application, we used the default index.jsp instead of creating one.
Initialization Parameters of (web.xml)
Initialization parameters can be shared among Web components (Servlet / JSP) in a web application. (will be discussed in Servlets).
Note: Initialization parameters are configured in the below web.xml file.
<servlet>
<servlet-name>greeting</servlet-name>
<servlet-class>GreetingServlet</servlet-class>
 <init-param>
            <param-name>user</param-name>
                <param-value>xyz</param-value>
      </init-param>
</servlet>
<servlet-mapping>
<servlet-name>greeting</servlet-name>
<url-pattern>/greeting</url-pattern>
</servlet-mapping>

Step 4: Test application 
Select project | Run as | Run on server

This result : 



Step 5 : Deploy websphere

1. Export file war 


2. Depoy file war in the websphere

Go to admin websphere :  https://x.xx.xx.x:9043/ibm/console/login.do?action=secure
Go to  New Application 


Sellect file war to deploy, after run install and start

The result after deploy websphere


Good Luck






Dowload Document API Filenet


package createdoc_api;

import com.filenet.api.collection.ContentElementList;
import com.filenet.api.collection.DocumentSet;
import com.filenet.api.core.*;
import com.filenet.api.util.Id;
import java.util.Iterator;
import java.io.*;
public class BulkDownloading {

    public static void main(String []args)
    {
     
        EngineConnection mine=new EngineConnection();
     
        Connection connection= mine.giveConnection();
     
        if(connection !=null)
        {
            Domain domain=Factory.Domain.fetchInstance(connection, null, null);
         
            ObjectStore object_store=Factory.ObjectStore.fetchInstance(domain, "CMTOS", null);
         
            System.out.println(""+object_store.get_DisplayName());
         
            Folder folder=Factory.Folder.fetchInstance(object_store, "/Banking/New Account Opening", null);
         
            System.out.println(""+folder.get_FolderName());
         
            //get all documents from this folder now
         
            DocumentSet document_set=folder.get_ContainedDocuments();
         
            Document current_document=null;
         
            FileOutputStream output_data=null;
         
            InputStream input_data=null;
         
            Document working_document=null;
         
            ContentElementList content_element_list=null;
         
           Iterator<DocumentSet>doc_iterator= document_set.iterator();
         
           while(doc_iterator.hasNext())
           {
             
               current_document=(Document)doc_iterator.next();
             
               //System.out.println(""+current_document.get_Name()+current_document.get_MimeType());
             
               String mime=current_document.get_MimeType();
             
               if(mime.startsWith("applica"))
               {
                   mime="pdf";
               }
             
               try
               {
              System.out.println(" duong dan "+current_document.get_Id());
                 
              output_data = new FileOutputStream("C:\\data_sample\\"+current_document.get_Name());
              System.out.println(" output_data "+ output_data);
              working_document=Factory.Document.fetchInstance(object_store,current_document.get_Id(), null);
                 
                   content_element_list=working_document.get_ContentElements();
                 
                   //iterate through these
                 
                   Iterator ite=content_element_list.iterator();
                 
                   while(ite.hasNext())
                   {
                     
                       ContentTransfer ct=(ContentTransfer)ite.next();
                     
                       input_data=ct.accessContentStream();
                     
                       int data_length=ct.get_ContentSize().intValue();
                     
                       byte buff[]=new byte[data_length];
                     
                       try
                       {
                         
                           input_data.read(buff);
                         
                           output_data.write(buff);
                         
                       }
                       catch(Exception e)
                       {
                           System.out.println(""+e.getLocalizedMessage());
                       }
                   }
                 
                 
               }
               catch(Exception e)
               {
                   System.out.println(""+e.getLocalizedMessage());
               }
           }
         
            System.out.println("Operation completed");
        }
     
    }
 
}

Thứ Tư, 21 tháng 9, 2016

GET LIST FILE IN SERVER AND TRANFER TO DATABASE


import java.io.File;
import java.sql.*;

public class get_file_list 
{
    /**
     * List all the files and folders from a directory
     * @param directoryName to be listed
     */
    public void listFilesAndFolders(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            System.out.println(file.getName());
        }
    }
    /**
     * List all the files under a directory
     * @param directoryName to be listed
     */
    public void listFiles(String directoryName)
      throws SQLException
    {
     int ret_code;
     Connection conn = null;
      conn = DriverManager.getConnection("jdbc:oracle:thin:@(DESCRIPTION=(load_balance=yes)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=e)(failover_mode=(type=select)(method=basic)(retries=32)(delay=4))))", "xx", "xxxxx");
            
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isFile())
            {
                System.out.println(file.getName());
                String sql2 = "INSERT INTO dir_list_ecm VALUES (?)";
                System.out.println(conn);
            //PreparedStatement pstmt1 = conn.prepareStatement(sql1);
              PreparedStatement pstmt2 = conn.prepareStatement(sql2);
          
              pstmt2.setString(1, file.getName());
              pstmt2.executeUpdate();
              System.out.println("finis");
               pstmt2.close();
              
            }
        }
        conn.close();
    }
    /**
     * List all the folder under a directory
     * @param directoryName to be listed
     */
    public void listFolders(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isDirectory()){
                System.out.println(file.getName());
            }
        }
    }
    /**
     * List all files from a directory and its subdirectories
     * @param directoryName to be listed
     */
    public void listFilesAndFilesSubDirectories(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isFile()){
                System.out.println(file.getAbsolutePath());
            } else if (file.isDirectory()){
                listFilesAndFilesSubDirectories(file.getAbsolutePath());
            }
        }
    }
    
   
    public static void main (String[] args)  throws SQLException
    {
     get_file_list listFilesUtil = new get_file_list();
        final String directoryLinuxMac ="/backup/ECM_TTQT";
        //Windows directory example
        final String directoryWindows ="D://Works";
        listFilesUtil.listFiles(directoryLinuxMac);
        
    }

}
================================================
Note :  Grant_permission

declare 
begin 
 dbms_java.grant_permission('SYSTEM','java.util.PropertyPermission','*','read');
 dbms_java.grant_permission('SYSTEM','java.net.SocketPermission','*','connect, resolve');
 dbms_java.grant_permission('SYSTEM','java.io.FilePermission','/backup/ECM_TTQT','read');
end;