Adempiere 3.1.2

This commit is contained in:
vpj-cd 2006-12-07 03:25:49 +00:00
parent 110f14a7f5
commit 64eca30fca
13 changed files with 3453 additions and 3138 deletions

View File

@ -2135,6 +2135,22 @@ public abstract class Doc
} }
return 0; return 0;
} // getUser2_ID } // getUser2_ID
/**
* Get User Defined value
* @return User defined
*/
public int getValue (String ColumnName)
{
int index = p_po.get_ColumnIndex(ColumnName);
if (index != -1)
{
Integer ii = (Integer)p_po.get_Value(index);
if (ii != null)
return ii.intValue();
}
return 0;
} // getValue
/*************************************************************************/ /*************************************************************************/

View File

@ -994,6 +994,23 @@ public class DocLine
} }
return 0; return 0;
} // getUser2_ID } // getUser2_ID
/**
* Get User Defined Column
* @param ColumnName column name
* @return user defined column value
*/
public int getValue(String ColumnName)
{
int index = p_po.get_ColumnIndex(ColumnName);
if (index != -1)
{
Integer ii = (Integer)p_po.get_Value(index);
if (ii != null)
return ii.intValue();
}
return 0;
} // getValue
/** /**
* String representation * String representation

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -10,21 +10,50 @@
* You should have received a copy of the GNU General Public License along * You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., * with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
* You may reach us at: ComPiere, Inc. - http://www.adempiere.org/license.html * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@adempiere.org * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org
*****************************************************************************/ *****************************************************************************/
package org.compiere.ldap; package org.compiere.ldap;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.util.logging.*; import java.util.Hashtable;
import org.compiere.ldap.*; import java.util.logging.*;
import org.compiere.util.*;
import com.sun.jndi.ldap.*; import javax.naming.AuthenticationException;
import javax.naming.Context;
/** import javax.naming.ldap.InitialLdapContext;
* LDAP Connection Handler
* import org.compiere.model.*;
import org.compiere.util.*;
/**
* LDAP Connection Handler
*
* Only "simple" authentication and the following protocol are supported:
* bind
* unbind
* search
* The following distinguished name are supported:
* o - organization
* ou - organization unit
* cn - common name
* Due to some of the ldap client might not unbind and close the connection,
* whenever error occurs and authenticate done, we will close the connection.
*
* Basically, tested with two type of ldap authentication, java client and
* apache ldap support.
* For the apache support, here's the tested definition:
* AuthType Basic
* AuthLDAPAuthoritative on
* AuthLDAPEnabled on
* AuthLDAPURL ldap://<ip address>:<port no>/o=<organization>,ou=<organization unit>?uid?sub
* The protocol for the apache ldap:
* - bind to server
* - search for the object name with user input userid
* - bind again with returned object name and password
* The protocol for the java client, please refer to the sample code in main().
*
* @author Jorg Janke * @author Jorg Janke
* @version $Id: LdapConnectionHandler.java,v 1.1 2006/10/09 00:23:16 jjanke Exp $ * @version $Id: LdapConnectionHandler.java,v 1.1 2006/10/09 00:23:16 jjanke Exp $
*/ */
@ -33,13 +62,15 @@ public class LdapConnectionHandler extends Thread
/** /**
* Ldap Connection Handler * Ldap Connection Handler
* @param socket server socket * @param socket server socket
*/ * @param model model
public LdapConnectionHandler(Socket socket) */
{ public LdapConnectionHandler(Socket socket, MLdapProcessor model)
try {
{ try
m_socket = socket; {
m_socket.setTcpNoDelay(true); // should not be required m_socket = socket;
m_socket.setTcpNoDelay(true); // should not be required
m_model = model;
} }
catch (Exception e) catch (Exception e)
{ {
@ -49,6 +80,8 @@ public class LdapConnectionHandler extends Thread
/** Socket */ /** Socket */
private Socket m_socket = null; private Socket m_socket = null;
/** Ldap Model */
private MLdapProcessor m_model = null;
/** Logger */ /** Logger */
private static CLogger log = CLogger.getCLogger (LdapConnectionHandler.class); private static CLogger log = CLogger.getCLogger (LdapConnectionHandler.class);
@ -63,6 +96,9 @@ public class LdapConnectionHandler extends Thread
if (m_socket == null || m_socket.isClosed()) if (m_socket == null || m_socket.isClosed())
return; return;
LdapMessage msg = new LdapMessage();
MLdapUser ldapUser = new MLdapUser();
LdapResult result = new LdapResult();
boolean activeSession = true; boolean activeSession = true;
while (activeSession) while (activeSession)
{ {
@ -72,21 +108,31 @@ public class LdapConnectionHandler extends Thread
byte[] buffer = new byte[512]; byte[] buffer = new byte[512];
int length = in.read(buffer, 0, 512); int length = in.read(buffer, 0, 512);
LdapMessage msg = new LdapMessage (buffer, length); // Decode the input message buffer
if (msg.getOperation() == LdapMessage.UNBIND_REQUEST) result.reset(msg, ldapUser);
{ msg.reset(result);
activeSession = false; msg.decode(buffer, length);
out.close(); if (msg.getOperation() == LdapMessage.UNBIND_REQUEST)
} {
else out.close();
{ break;
LdapResult result = new LdapResult (); }
byte[] bytes = result.bindResponse();
// // Not unbind, so we can create a response
out.write(bytes); byte[] bytes = result.getResult(m_model);
out.flush();
} // Send the response back
} out.write(bytes);
out.flush();
// If there's error or successfully authenticated the user,
// close the connection to avoid too many open connection
if (result.getDone())
{
out.close();
break;
}
} // while(activeSession)
} }
catch (IOException e) catch (IOException e)
{ {
@ -115,4 +161,42 @@ public class LdapConnectionHandler extends Thread
return sb.toString (); return sb.toString ();
} // toString } // toString
} // LdapConnectionHandler /**
* Test using the java client.
* Ldap v3 won't need to do any bind, search, bind anymore.
* When new InitialLdapContext() is called, it will bind with the
* dn and password, the ldap server should be authenticate with it.
*
* @param args
*/
public static void main(String[] args)
{
Hashtable<String,String> env = new Hashtable<String,String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
// ldap://dc.compiere.org
env.put(Context.PROVIDER_URL, "ldap://10.104.139.160:389");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
// Compiere server only support cn/o/ou, and cn should be the user id.
// Only one entry for cn.
env.put(Context.SECURITY_PRINCIPAL, "cn=cboss@compiere.org,o=GardenWorld,ou=LawnCare");
env.put(Context.SECURITY_CREDENTIALS, "carlboss");
try
{
// Create the initial context
new InitialLdapContext(env, null);
// If not successfully authenticated, exception should be thrown
System.out.println("Successfully authenticated ...");
}
catch (AuthenticationException e)
{
e.printStackTrace();
return;
}
catch (Exception e)
{
e.printStackTrace();
return;
}
} // main()
} // LdapConnectionHandler

View File

@ -10,12 +10,13 @@
* You should have received a copy of the GNU General Public License along * You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., * with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
* You may reach us at: ComPiere, Inc. - http://www.adempiere.org/license.html * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@adempiere.org * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org
*****************************************************************************/ *****************************************************************************/
package org.compiere.ldap; package org.compiere.ldap;
import java.util.logging.*; import java.util.logging.*;
import org.compiere.util.*; import org.compiere.util.*;
import com.sun.jndi.ldap.*; import com.sun.jndi.ldap.*;
@ -27,138 +28,235 @@ import com.sun.jndi.ldap.*;
*/ */
public class LdapMessage public class LdapMessage
{ {
/** static public final int BIND_REQUEST = 96;
* Ldap Message static public final int BIND_RESPONSE = 97;
* @param data BER data static public final int UNBIND_REQUEST = 98;
* @param length Ber data length static public final int SEARCH_REQUEST = 99;
*/ static public final int SEARCH_REP_ENTRY = 100;
public LdapMessage (byte[] data, int length) static public final int SEARCH_RES_RESULT = 101;
{
try static public final int SIMPLE_AUTHENTICATION = 128;
{
decode(data, length); static public final int FILTER_AND = 160;
} static public final int FILTER_OR = 161;
catch (Exception e) static public final int FILTER_NOT = 162;
{ static public final int FILTER_EQUALITYMATCH = 163;
log.log(Level.SEVERE, data.toString(), e);
} static public final int SEQUENCE = 48;
} // LdapMessage
/** Decoder */
/** private BerDecoder decoder = null;
LDAPMessage ::= SEQUENCE { /** Logger */
messageID MessageID, private static CLogger log = CLogger.getCLogger (LdapMessage.class);
protocolOp CHOICE { /** Protocol Operation */
bindRequest BindRequest, private int m_protocolOp = -1;
bindResponse BindResponse, /** Message Id needed for the reply message */
unbindRequest UnbindRequest, private int msgId;
searchRequest SearchRequest, /** Distinguished name */
searchResEntry SearchResultEntry, private String dn = null;
searchResDone SearchResultDone, /** Organization */
searchResRef SearchResultReference, private String org = null;
modifyRequest ModifyRequest, /** Organization unit */
modifyResponse ModifyResponse, private String orgUnit = null;
addRequest AddRequest, /** User Id */
addResponse AddResponse, private String userId = null;
delRequest DelRequest, /** Password */
delResponse DelResponse, private String passwd = null;
modDNRequest ModifyDNRequest, /** base Object */
modDNResponse ModifyDNResponse, private String baseObj = null;
compareRequest CompareRequest, /** LdapResult object to hold if there's any error during parsing */
compareResponse CompareResponse, private LdapResult result = null;
abandonRequest AbandonRequest,
extendedReq ExtendedRequest, /**
extendedResp ExtendedResponse }, * Ldap Message
controls [0] Controls OPTIONAL } */
**/ public LdapMessage()
{
static public final int BIND_REQUEST = 0; } // LdapMessage
static public final int BIND_RESPONSE = 1;
static public final int UNBIND_REQUEST = 2; /*
static public final int SEARCH_REQUEST = 3; * Reset all the attributes
static public final int SEARCH_RESENTRY = 4; */
static public final int SEARCH_RESDONE = 5; public void reset(LdapResult result)
static public final int MODIFY_REQUEST = 6; {
static public final int MODIFY_RESPONSE = 7; this.result = result;
static public final int ADD_REQUEST = 8; decoder = null;
static public final int ADD_RESPONSE = 9; m_protocolOp = -1;
static public final int DEL_REQUEST = 10; msgId = -1;
static public final int DEL_RESPONSE = 11; dn = null;
static public final int MODDN_REQUEST = 12; org = null;
static public final int MODDN_RESPONSE = 13; orgUnit = null;
static public final int COMPARE_REQUEST = 14; userId = null;
static public final int COMPARE_RESPONSE = 15; passwd = null;
static public final int ABANDON_REQUEST = 16; baseObj = null;
static public final int EXTENDED_REQUEST = 17;
static public final int EXTENDED_RESPONSE = 18; } // reset()
static public final int[] PROTOCOL_OP = { /**
BIND_REQUEST, BIND_RESPONSE, UNBIND_REQUEST, * Decode Message
SEARCH_REQUEST, SEARCH_RESENTRY, SEARCH_RESDONE, * @param data input buffer
MODIFY_REQUEST, MODIFY_RESPONSE, ADD_REQUEST, ADD_RESPONSE, * @param length buffer size
DEL_REQUEST, DEL_RESPONSE, MODDN_REQUEST, MODDN_RESPONSE, */
COMPARE_REQUEST, COMPARE_RESPONSE, ABANDON_REQUEST, public void decode(byte[] data, int length)
EXTENDED_REQUEST, EXTENDED_RESPONSE}; {
try
{
/** Logger */ // Create the decoder
private static CLogger log = CLogger.getCLogger (LdapMessage.class); decoder = new BerDecoder(data, 0, length);
/** Protocol Operation */ }
private int m_protocolOp = -1; catch (Exception e)
{
log.log(Level.SEVERE, data.toString(), e);
/** return;
* Decode Message }
* @param data data
* @param length length try
* @throws Exception {
*/ // Parse the message envelope
private void decode (byte[] data, int length) throws Exception decoder.parseSeq(null);
{
BerDecoder decoder = new BerDecoder(data, 0, length); // Parse message Id
int left = decoder.bytesLeft(); msgId = decoder.parseInt();
int pos = decoder.getParsePosition();
// // Parse the operation protocol
int seq = decoder.parseSeq(null); m_protocolOp = decoder.parseSeq(null);
left = decoder.bytesLeft();
pos = decoder.getParsePosition(); //
// // Payload
int messageID = decoder.parseInt(); if (m_protocolOp == BIND_REQUEST)
left = decoder.bytesLeft(); handleBind();
pos = decoder.getParsePosition(); else if (m_protocolOp == UNBIND_REQUEST)
// log.info("#" + msgId + ": unbind");
int peek = decoder.peekByte(); else if (m_protocolOp == SEARCH_REQUEST)
m_protocolOp = decoder.parseSeq(PROTOCOL_OP); handleSearch();
m_protocolOp -= Ber.ASN_APPLICATION; else // Only supoort BIND, UNBIND and SEARCH
if (m_protocolOp - Ber.ASN_CONSTRUCTOR >= 0) {
m_protocolOp -= Ber.ASN_CONSTRUCTOR; result.setErrorNo(LdapResult.LDAP_PROTOCOL_ERROR);
left = decoder.bytesLeft(); result.setErrorString(": Unsupported Request");
pos = decoder.getParsePosition(); log.warning("#" + msgId + ": Unknown Op + " + m_protocolOp);
// }
// Payload }
if (m_protocolOp == BIND_REQUEST) catch (Exception ex)
{ {
int version = decoder.parseInt(); result.setErrorNo(LdapResult.LDAP_PROTOCOL_ERROR);
left = decoder.bytesLeft(); log.log(Level.SEVERE, "", ex);
pos = decoder.getParsePosition(); }
// } // decode
byte[] dn = decoder.parseOctetString(Ber.ASN_OCTET_STR, null);
left = decoder.bytesLeft(); /*
pos = decoder.getParsePosition(); * Encode the search request message
// */
byte[] authentification = decoder.parseOctetString(Ber.ASN_CONTEXT, null); private void handleSearch()
left = decoder.bytesLeft(); {
pos = decoder.getParsePosition(); try
// {
log.info("#" + messageID + ": bind - version=" + version + ", dn=" + new String(dn) // Parse the base Object
+ ", auth=" + new String (authentification)); baseObj = decoder.parseString(true);
} parseDN(baseObj);
else if (m_protocolOp == UNBIND_REQUEST)
log.info("#" + messageID + ": unbind"); decoder.parseEnumeration(); // scope
else decoder.parseEnumeration(); // derefAliases
{ decoder.parseInt(); // sizeLimit
log.warning("#" + messageID + ": Unknown Op + " + m_protocolOp); decoder.parseInt(); // timeLimit
} decoder.parseBoolean(); // typeOnly
} // decode
boolean equalityFilter = false;
while (true)
{
int filter = decoder.parseSeq(null); //Filter
if (filter == FILTER_EQUALITYMATCH)
{
decoder.parseString(true);
userId = decoder.parseString(true);
equalityFilter = true;
break;
}
else if (filter == FILTER_AND)
decoder.parseStringWithTag(135, true, null);
else if (filter == SEQUENCE)
break;
} // while true
if (!equalityFilter) // Didn't find the it
{
result.setErrorNo(LdapResult.LDAP_PROTOCOL_ERROR);
result.setErrorString("Can't can't Filter - EqualityMatch");
}
}
catch (Exception ex)
{
log.log(Level.SEVERE, "", ex);
}
} // handleSearch()
/*
* Encode the bind request message
*/
private void handleBind()
{
try
{
// Parse LDAP version; only support v3
int version = decoder.parseInt();
if (version != 3)
{
result.setErrorNo(LdapResult.LDAP_PROTOCOL_ERROR);
result.setErrorString("Unsupported LDAP version");
log.info("#" + msgId + ": unsupported LDAP version - " + version);
return;
}
// Parse DN
dn = decoder.parseString(true);
// Peek on AuthenticationChoice; only support simple authentication
int auth = decoder.peekByte();
if (auth != SIMPLE_AUTHENTICATION) // 0x80 - simple authentication
{
result.setErrorNo(LdapResult.LDAP_AUTH_METHOD_NOT_SUPPORTED);
log.info("#" + msgId + ": unsupported authentication method - " + auth);
return;
}
// It is simple authentication, get the authentication string
passwd = decoder.parseStringWithTag(SIMPLE_AUTHENTICATION, true, null);
if (passwd != null && passwd.length() > 0)
{
parseDN(dn);
if (userId == null || userId.length() <= 0)
{
result.setErrorNo(LdapResult.LDAP_NO_SUCH_OBJECT);
result.setErrorString(": \"cn\" not defined");
log.info("#" + msgId + ": \"cn\" not defined");
return;
}
}
// Log the information
log.info("#" + msgId + ": bind - version=" + version + ", userId=" + userId);
}
catch (Exception ex)
{
log.log(Level.SEVERE, "", ex);
}
} // handleBind()
/*
* Parse the DN to find user id, organization and organization unit
*/
private void parseDN(String dName)
{
String[] dnArray = dName.split(",");
for (int i = 0; i < dnArray.length; i++)
{
if (dnArray[i].startsWith("cn="))
userId = dnArray[i].split("=")[1];
else if (dnArray[i].startsWith("o="))
org = dnArray[i].split("=")[1];
else if (dnArray[i].startsWith("ou="))
orgUnit = dnArray[i].split("=")[1];
}
} // parseDN()
/** /**
* Get Operation Code * Get Operation Code
@ -169,4 +267,66 @@ public class LdapMessage
return m_protocolOp; return m_protocolOp;
} // getOperation } // getOperation
} // LdapMessage /**
* Get message id
* @return msgId
*/
public int getMsgId()
{
return msgId;
} // getMsgId()
/**
* Get DN
* @return dn
*/
public String getDN()
{
return dn;
} // getDN()
/**
* Get User Id
* @return userId
*/
public String getUserId()
{
return userId;
} // getUserId()
/**
* Get User passwod
* @return passwd
*/
public String getUserPasswd()
{
return passwd;
} // getUserPasswd()
/**
* Get base object
* @return baseObj
*/
public String getBaseObj()
{
return baseObj;
} // getBaseObj()
/**
* Get organization
* @return org
*/
public String getOrg()
{
return org;
} // getOrg()
/**
* Get organization unit
* @return orgUnit
*/
public String getOrgUnit()
{
return orgUnit;
} // getOrgUnit()
} // LdapMessage

View File

@ -10,8 +10,8 @@
* You should have received a copy of the GNU General Public License along * You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., * with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
* You may reach us at: ComPiere, Inc. - http://www.adempiere.org/license.html * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@adempiere.org * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org
*****************************************************************************/ *****************************************************************************/
package org.compiere.ldap; package org.compiere.ldap;
@ -19,9 +19,7 @@ import java.net.*;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import javax.naming.ldap.*;
import org.compiere.*; import org.compiere.*;
import org.compiere.ldap.*;
import org.compiere.model.*; import org.compiere.model.*;
import org.compiere.server.*; import org.compiere.server.*;
import org.compiere.util.*; import org.compiere.util.*;
@ -38,19 +36,16 @@ public class LdapProcessor extends AdempiereServer
* Ldap Processor (Server) * Ldap Processor (Server)
* @param model Ldap Model * @param model Ldap Model
*/ */
public LdapProcessor (LdapProcessorModel model) public LdapProcessor (MLdapProcessor model)
{ {
super (model, 300); super (model, 300);
m_model = model; m_model = model;
init();
} // LdapProcessor } // LdapProcessor
/** The Concrete Model */ /** The Concrete Model */
private LdapProcessorModel m_model = null; private MLdapProcessor m_model = null;
/** Last Summary */ /** Last Summary */
private StringBuffer m_summary = new StringBuffer(); private StringBuffer m_summary = new StringBuffer();
/** Client info */
private MClient m_client = null;
/** Server Socket */ /** Server Socket */
private ServerSocket m_serverSocket = null; private ServerSocket m_serverSocket = null;
/** Counter */ /** Counter */
@ -87,7 +82,8 @@ public class LdapProcessor extends AdempiereServer
{ {
Socket socket = m_serverSocket.accept(); // waits for connection Socket socket = m_serverSocket.accept(); // waits for connection
log.log(Level.FINE, "Connection on Port=" + m_model.getLdapPort()); log.log(Level.FINE, "Connection on Port=" + m_model.getLdapPort());
LdapConnectionHandler handler = new LdapConnectionHandler (socket); LdapConnectionHandler handler =
new LdapConnectionHandler (socket, m_model);
handler.start(); handler.start();
m_counter++; m_counter++;
} }
@ -98,24 +94,19 @@ public class LdapProcessor extends AdempiereServer
m_summary.append(e.toString()); m_summary.append(e.toString());
} }
m_summary.append ("; ")
.append (m_model.getInfo());
int no = m_model.deleteLog();
m_summary.append("; Logs deleted=").append(no);
//
MLdapProcessorLog pLog = new MLdapProcessorLog(m_model, m_summary.toString());
pLog.setReference("#" + String.valueOf(p_runCount)
+ " - " + TimeUtil.formatElapsed(new Timestamp(p_startWork)));
pLog.save();
} // doWork } // doWork
/**
* Initialize
*/
private void init()
{
try
{
InitialLdapContext lctx = new InitialLdapContext();
// lctx.setRequestControls(critModCtls);
// lctx.modifyAttributes(name, mods);
Control[] respCtls = lctx.getResponseControls();
}
catch (Exception e)
{
}
} //
/** /**
* Get Server Info * Get Server Info
@ -124,7 +115,8 @@ public class LdapProcessor extends AdempiereServer
public String getServerInfo() public String getServerInfo()
{ {
return "#" + p_runCount + " - Last=" + m_summary.toString() return "#" + p_runCount + " - Last=" + m_summary.toString()
+ "; Counter=" + m_counter; + "; Counter=" + m_counter
+ "; " + m_model.getInfo();
} // getServerInfo } // getServerInfo
/** /**
@ -134,7 +126,7 @@ public class LdapProcessor extends AdempiereServer
public static void main(String[] args) public static void main(String[] args)
{ {
Adempiere.startup(true); Adempiere.startup(true);
new LdapProcessor(new LdapProcessorModel(new Properties())).doWork(); new LdapProcessor(new MLdapProcessor(new Properties(), 0, null)).doWork();
} // main } // main
} // LdapProcessor } // LdapProcessor

View File

@ -1,158 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved.
* This program is free software; you can redistribute it and/or modify it
* under the terms version 2 of the GNU General Public License as published
* by the Free Software Foundation. This program is distributed in the hope
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
* You may reach us at: ComPiere, Inc. - http://www.adempiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@adempiere.org
*****************************************************************************/
package org.compiere.ldap;
import java.sql.*;
import java.util.*;
import org.compiere.model.*;
/**
* Interim LDAP Server Model
*
* @author Jorg Janke
* @version $Id: LdapProcessorModel.java,v 1.1 2006/10/09 00:23:16 jjanke Exp $
*/
public class LdapProcessorModel implements AdempiereProcessor
{
/**
* Ldap Processor Model
* @param ctx context
*/
public LdapProcessorModel (Properties ctx)
{
m_ctx = ctx;
}
// Properties
private Properties m_ctx = null;
private Timestamp m_dateNextRun;
private Timestamp m_dateLastRun;
public int getLdapPort()
{
return 389;
}
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer (getName());
sb.append (";Port=").append (getLdapPort());
return sb.toString ();
} // toString
/**************************************************************************
* getAD_Client_ID
* @see org.compiere.model.AdempiereProcessor#getAD_Client_ID()
* @return 0
*/
public int getAD_Client_ID()
{
return 0;
}
/**
* getName
* @see org.compiere.model.AdempiereProcessor#getName()
* @return name
*/
public String getName()
{
return "Adempiere LDAP Server";
}
/**
* getDescription
* @see org.compiere.model.AdempiereProcessor#getDescription()
* @return -
*/
public String getDescription()
{
return "-";
}
/**
* Get Ctx
* @return context
*/
public Properties getCtx()
{
return m_ctx;
}
/**
* GetFrequencyType
* @see org.compiere.model.AdempiereProcessor#getFrequencyType()
* @return min
*/
public String getFrequencyType()
{
return MRequestProcessor.FREQUENCYTYPE_Minute;
}
/**
* getFrequency
* @see org.compiere.model.AdempiereProcessor#getFrequency()
* @return 1
*/
public int getFrequency()
{
return 1;
}
/**
* Get Unique Server ID
* @return id
*/
public String getServerID()
{
return "Ldap";
}
public Timestamp getDateNextRun(boolean requery)
{
return m_dateNextRun;
}
public void setDateNextRun(Timestamp dateNextWork)
{
m_dateNextRun = dateNextWork;
}
public Timestamp getDateLastRun()
{
return m_dateLastRun;
}
public void setDateLastRun(Timestamp dateLastRun)
{
m_dateLastRun = dateLastRun;
}
public boolean save()
{
return true;
}
public AdempiereProcessorLog[] getLogs()
{
return new AdempiereProcessorLog[0];
}
}

View File

@ -10,15 +10,15 @@
* You should have received a copy of the GNU General Public License along * You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., * with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
* You may reach us at: ComPiere, Inc. - http://www.adempiere.org/license.html * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@adempiere.org * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org
*****************************************************************************/ *****************************************************************************/
package org.compiere.ldap; package org.compiere.ldap;
import java.io.*;
import java.util.logging.*; import java.util.logging.*;
import org.compiere.model.*;
import org.compiere.util.*; import org.compiere.util.*;
import com.sun.jndi.ldap.*; import com.sun.jndi.ldap.BerEncoder;
/** /**
* Ldap Wire Response * Ldap Wire Response
@ -28,120 +28,278 @@ import com.sun.jndi.ldap.*;
*/ */
public class LdapResult public class LdapResult
{ {
/** LdapMesssage */
public LdapResult() private LdapMessage ldapMsg = null;
{ /** Encoder */
super (); private BerEncoder m_encoder = null;
} // LdapResult /** Logger */
private static CLogger log = CLogger.getCLogger (LdapResult.class);
/** /** Error number */
LDAPResult ::= SEQUENCE { private int errNo = LDAP_SUCCESS;
resultCode ENUMERATED { /** Error String */
success (0), private String errStr = "";
operationsError (1), /** LdapUser */
protocolError (2), private MLdapUser ldapUser = null;
timeLimitExceeded (3), /** disconnect to client */
sizeLimitExceeded (4), private boolean disconnect = false;
compareFalse (5),
compareTrue (6), public LdapResult ()
{
authMethodNotSupported (7), } // LdapResult
strongAuthRequired (8),
-- 9 reserved -- /*
referral (10), -- new * Reset the attributes
adminLimitExceeded (11), -- new */
unavailableCriticalExtension (12), -- new public void reset(LdapMessage ldapMsg, MLdapUser ldapUser)
confidentialityRequired (13), -- new {
saslBindInProgress (14), -- new this.ldapMsg = ldapMsg;
noSuchAttribute (16), m_encoder = new BerEncoder();
undefinedAttributeType (17), errNo = LDAP_SUCCESS;
inappropriateMatching (18), errStr = "";
constraintViolation (19), this.ldapUser = ldapUser;
attributeOrValueExists (20), } // reset()
invalidAttributeSyntax (21),
noSuchObject (32), /**
aliasProblem (33), * Get the response according to the request message
invalidDNSyntax (34), * @param model model
-- 35 reserved for undefined isLeaf -- * @return reponse
aliasDereferencingProblem (36), */
-- 37-47 unused -- public byte[] getResult(MLdapProcessor model)
inappropriateAuthentication (48), {
invalidCredentials (49), if (errNo != LDAP_SUCCESS)
insufficientAccessRights (50), {
busy (51), generateResult("",
unavailable (52), ((ldapMsg.getOperation()==LdapMessage.BIND_REQUEST)?
unwillingToPerform (53), LdapMessage.BIND_RESPONSE:LdapMessage.SEARCH_RES_RESULT),
loopDetect (54), errNo, ldapErrorMessage[errNo] + errStr);
-- 55-63 unused -- m_encoder.getTrimmedBuf();
namingViolation (64), }
objectClassViolation (65),
notAllowedOnNonLeaf (66), try
notAllowedOnRDN (67), {
entryAlreadyExists (68), String usrId = ldapMsg.getUserId();
objectClassModsProhibited (69), String o = ldapMsg.getOrg();
-- 70 reserved for CLDAP -- String ou = ldapMsg.getOrgUnit();
affectsMultipleDSAs (71), -- new
-- 72-79 unused -- // Adding the Application 1 Sequence
other (80) }, if (ldapMsg.getOperation() == LdapMessage.BIND_REQUEST)
-- 81-90 reserved for APIs -- {
matchedDN LDAPDN, String pwd = ldapMsg.getUserPasswd();
errorMessage LDAPString, if (pwd == null || pwd.length() <= 0)
referral [3] Referral OPTIONAL } {
**/ // 1st anonymous bind
generateResult(ldapMsg.getDN(), LdapMessage.BIND_RESPONSE,
/** Encoder */ LDAP_SUCCESS, null);
private BerEncoder m_encoder = new BerEncoder(); log.info("Success");
/** Logger */ return m_encoder.getTrimmedBuf();
private static CLogger log = CLogger.getCLogger (LdapResult.class); }
/** // Authenticate with Compiere data
* Bind Response if (ldapUser.getUserId() == null)
* @return reponse { // Try to authenticate on the 1st bind, must be java client
*/ ldapUser.reset();
public byte[] bindResponse() model.authenticate(ldapUser, usrId, o, ou);
{ if (ldapUser.getErrorMsg() != null)
try { // Failed to authenticated with compiere
{ errNo = LDAP_NO_SUCH_OBJECT;
/** generateResult(ldapMsg.getBaseObj(), LdapMessage.SEARCH_RES_RESULT,
m_encoder.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); LDAP_NO_SUCH_OBJECT,
for (int i = 0; i < sortKeys.length; i++) { ldapErrorMessage[LDAP_NO_SUCH_OBJECT] + ldapUser.getErrorMsg());
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); log.info("Failed");
ber.encodeString(sortKeys[i].getAttributeID(), true); // v3 return m_encoder.getTrimmedBuf();
if ((matchingRule = sortKeys[i].getMatchingRuleID()) != null) { }
ber.encodeString(matchingRule, (Ber.ASN_CONTEXT | 0), true); }
}
if (! sortKeys[i].isAscending()) { // Check to see if the input passwd is match to the one
ber.encodeBoolean(true, (Ber.ASN_CONTEXT | 1)); // in compiere database
} if (usrId.compareTo(ldapUser.getUserId()) == 0 &&
ber.endSeq(); pwd.compareTo(ldapUser.getPassword()) == 0)
} { // Successfully authenticated
*/ generateResult("", LdapMessage.BIND_RESPONSE,
// payload LDAP_SUCCESS, null);
m_encoder.beginSeq(Ber.ASN_APPLICATION | LdapMessage.BIND_RESPONSE); // Close the connection to client since most of the client
// Response // application might cache the connection but we can't afford
m_encoder.encodeInt(0); // success // to have too many such client connection
m_encoder.encodeOctetString("cn=testCN".getBytes(), 0); // matched DN disconnect = true;
m_encoder.encodeOctetString("".getBytes(), 0); // error mag log.info("Success");
// referral }
// sasl else
// { // Unsuccessfully authenticated
m_encoder.endSeq(); errNo = LDAP_INAPPROPRIATE_AUTHENTICATION;
log.info("Success"); generateResult("", LdapMessage.BIND_RESPONSE,
} LDAP_INAPPROPRIATE_AUTHENTICATION,
catch (Exception e) ldapErrorMessage[LDAP_INAPPROPRIATE_AUTHENTICATION]);
{ log.info("Failed : " + ldapErrorMessage[LDAP_INAPPROPRIATE_AUTHENTICATION]);
log.log(Level.SEVERE, "", e); }
} }
return getResult(); else if (ldapMsg.getOperation() == LdapMessage.SEARCH_REQUEST)
} // bindResponse {
// Authenticate with compiere database
/** ldapUser.reset();
* Get BER Result as byte array model.authenticate(ldapUser, usrId, o, ou);
* @return byte array if (ldapUser.getErrorMsg() != null)
*/ {
public byte[] getResult() errNo = LDAP_NO_SUCH_OBJECT;
{ generateResult(ldapMsg.getBaseObj(), LdapMessage.SEARCH_RES_RESULT,
return m_encoder.getTrimmedBuf(); LDAP_NO_SUCH_OBJECT,
} // getResult ldapErrorMessage[LDAP_NO_SUCH_OBJECT] + ldapUser.getErrorMsg());
log.info("Failed");
} // LdapResult return m_encoder.getTrimmedBuf();
}
m_encoder.beginSeq(48); // Hard coded here for Envelope header
m_encoder.encodeInt(ldapMsg.getMsgId());
m_encoder.beginSeq(LdapMessage.SEARCH_REP_ENTRY); // Application 4
m_encoder.encodeString("cn="+ldapMsg.getUserId(), true); // this should be object name
// not going to put in any attributes for this
m_encoder.beginSeq(48);
m_encoder.endSeq();
m_encoder.endSeq();
m_encoder.endSeq();
// SearchResultDone Application 5 for bind
// Result 0 = success
// No error message
generateResult(ldapMsg.getBaseObj(), LdapMessage.SEARCH_RES_RESULT,
LDAP_SUCCESS, null);
log.info("Success");
}
return m_encoder.getTrimmedBuf();
}
catch (Exception e)
{
log.log(Level.SEVERE, "", e);
}
return m_encoder.getTrimmedBuf();
} // bindResponse
/**
* Generate LDAPResult
* @param dn Distinguished Name
* @param resultProtocol Result protocol/operation code
* @param resultCode Result code
* @param errMsg Error Message
* @return reponse
*/
private void generateResult(String dn, int resultProtocol,
int resultCode, String errMsg)
{
try
{
m_encoder.beginSeq(48); // Hard coded here for Envelope header
m_encoder.encodeInt(ldapMsg.getMsgId());
m_encoder.beginSeq(resultProtocol);
m_encoder.encodeInt(resultCode, 10); // Enumeration - 10
// Adding LDAPDN
m_encoder.encodeString(dn, true);
// Adding error message
m_encoder.encodeString((errMsg == null)?"":errMsg, true);
m_encoder.endSeq();
m_encoder.endSeq();
}
catch (Exception ex)
{
log.log(Level.SEVERE, "", ex);
}
} // generateResult()
/*
* Should it be close the connection with client
*/
public boolean getDone()
{
if (errNo != LDAP_SUCCESS)
return true;
return disconnect;
} // getDone()
/**
* Set the error No
* @param errNo Error Number
*/
public void setErrorNo(int errNo)
{
this.errNo = errNo;
} // setErrorNo()
/**
* Get the error No
* @return errNo Error Number
*/
public int getErrorNo()
{
return errNo;
} // getErrorNo()
/**
* Set the error String
* @param errStr Error String
*/
public void setErrorString(String errStr)
{
this.errStr = errStr;
} // setErrorStr()
static final int LDAP_SUCCESS = 0;
static final int LDAP_OPERATIONS_ERROR = 1;
static final int LDAP_PROTOCOL_ERROR = 2;
static final int LDAP_TIME_LIMIT_EXCEEDED = 3;
static final int LDAP_SIZE_LIMIT_EXCEEDED = 4;
static final int LDAP_COMPARE_FALSE = 5;
static final int LDAP_COMPARE_TRUE = 6;
static final int LDAP_AUTH_METHOD_NOT_SUPPORTED = 7;
static final int LDAP_STRONG_AUTH_REQUIRED = 8;
static final int LDAP_PARTIAL_RESULTS = 9;
static final int LDAP_REFERRAL = 10;
static final int LDAP_ADMIN_LIMIT_EXCEEDED = 11;
static final int LDAP_UNAVAILABLE_CRITICAL_EXTENSION = 12;
static final int LDAP_CONFIDENTIALITY_REQUIRED = 13;
static final int LDAP_SASL_BIND_IN_PROGRESS = 14;
static final int LDAP_NO_SUCH_ATTRIBUTE = 16;
static final int LDAP_UNDEFINED_ATTRIBUTE_TYPE = 17;
static final int LDAP_INAPPROPRIATE_MATCHING = 18;
static final int LDAP_CONSTRAINT_VIOLATION = 19;
static final int LDAP_ATTRIBUTE_OR_VALUE_EXISTS = 20;
static final int LDAP_INVALID_ATTRIBUTE_SYNTAX = 21;
static final int LDAP_NO_SUCH_OBJECT = 32;
static final int LDAP_ALIAS_PROBLEM = 33;
static final int LDAP_INVALID_DN_SYNTAX = 34;
static final int LDAP_IS_LEAF = 35;
static final int LDAP_ALIAS_DEREFERENCING_PROBLEM = 36;
static final int LDAP_INAPPROPRIATE_AUTHENTICATION = 48;
static final int LDAP_INVALID_CREDENTIALS = 49;
static final int LDAP_INSUFFICIENT_ACCESS_RIGHTS = 50;
static final int LDAP_BUSY = 51;
static final int LDAP_UNAVAILABLE = 52;
static final int LDAP_UNWILLING_TO_PERFORM = 53;
static final int LDAP_LOOP_DETECT = 54;
static final int LDAP_NAMING_VIOLATION = 64;
static final int LDAP_OBJECT_CLASS_VIOLATION = 65;
static final int LDAP_NOT_ALLOWED_ON_NON_LEAF = 66;
static final int LDAP_NOT_ALLOWED_ON_RDN = 67;
static final int LDAP_ENTRY_ALREADY_EXISTS = 68;
static final int LDAP_OBJECT_CLASS_MODS_PROHIBITED = 69;
static final int LDAP_AFFECTS_MULTIPLE_DSAS = 71;
static final int LDAP_OTHER = 80;
static final String ldapErrorMessage[] = {
"Success", "Operations Error", "Protocol Error", "Timelimit Exceeded",
"Sizelimit Exceeded", "Compare False", "Compare True",
"Authentication Method Not Supported", "Strong Authentication Required", null,
"Referral", "Administrative Limit Exceeded", "Unavailable Critical Extension",
"Confidentiality Required", "SASL Bind In Progress", null, "No Such Attribute",
"Undefined Attribute Type", "Inappropriate Matching", "Constraint Violation",
"Attribute Or Value Exists", "Invalid Attribute Syntax", null, null, null,
null, null, null, null, null,null, null, "No Such Object", "Alias Problem",
"Invalid DN Syntax", null, "Alias Dereferencing Problem", null, null, null,
null, null, null, null, null, null, null, null, "Inappropriate Authentication",
"Invalid Credentials", "Insufficient Access Rights", "Busy", "Unavailable",
"Unwilling To Perform", "Loop Detect", null, null, null, null, null,
null, null, null, null, "Naming Violation", "Object Class Violation",
"Not Allowed On Non-leaf", "Not Allowed On RDN", "Entry Already Exists",
"Object Class Modifications Prohibited", null, "Affects Multiple DSAs", null,
null, null, null, null, null, null, null,"Other", null, null, null, null,
null, null, null, null, null,null
};
} // LdapResult

View File

@ -3,25 +3,25 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.server; package org.compiere.server;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import org.compiere.ldap.*; import org.compiere.ldap.*;
import org.compiere.model.*; import org.compiere.model.*;
import org.compiere.util.*; import org.compiere.util.*;
import org.compiere.wf.*; import org.compiere.wf.*;
/** /**
@ -41,23 +41,23 @@ public abstract class AdempiereServer extends Thread
{ {
if (model instanceof MRequestProcessor) if (model instanceof MRequestProcessor)
return new RequestProcessor ((MRequestProcessor)model); return new RequestProcessor ((MRequestProcessor)model);
if (model instanceof MWorkflowProcessor) if (model instanceof MWorkflowProcessor)
return new WorkflowProcessor ((MWorkflowProcessor)model); return new WorkflowProcessor ((MWorkflowProcessor)model);
if (model instanceof MAcctProcessor) if (model instanceof MAcctProcessor)
return new AcctProcessor ((MAcctProcessor)model); return new AcctProcessor ((MAcctProcessor)model);
if (model instanceof MAlertProcessor) if (model instanceof MAlertProcessor)
return new AlertProcessor ((MAlertProcessor)model); return new AlertProcessor ((MAlertProcessor)model);
if (model instanceof MScheduler) if (model instanceof MScheduler)
return new Scheduler ((MScheduler)model); return new Scheduler ((MScheduler)model);
if (model instanceof LdapProcessorModel) if (model instanceof MLdapProcessor)
return new LdapProcessor((LdapProcessorModel)model); return new LdapProcessor((MLdapProcessor)model);
// //
throw new IllegalArgumentException("Unknown Processor"); throw new IllegalArgumentException("Unknown Processor");
} // create } // create
/************************************************************************** /**************************************************************************
* Server Base Class * Server Base Class
* @param model model * @param model model
* @param initialNap delay time running in sec * @param initialNap delay time running in sec
*/ */
@ -67,11 +67,11 @@ public abstract class AdempiereServer extends Thread
p_model = model; p_model = model;
m_ctx = new Properties(model.getCtx()); m_ctx = new Properties(model.getCtx());
if (p_system == null) if (p_system == null)
p_system = MSystem.get(m_ctx); p_system = MSystem.get(m_ctx);
p_client = MClient.get(m_ctx); p_client = MClient.get(m_ctx);
Env.setContext(m_ctx, "#AD_Client_ID", p_client.getAD_Client_ID()); Env.setContext(m_ctx, "#AD_Client_ID", p_client.getAD_Client_ID());
m_initialNap = initialNap; m_initialNap = initialNap;
// log.info(model.getName() + " - " + getThreadGroup()); // log.info(model.getName() + " - " + getThreadGroup());
} // ServerBase } // ServerBase
/** The Processor Model */ /** The Processor Model */
@ -79,221 +79,221 @@ public abstract class AdempiereServer extends Thread
/** Initial nap is seconds */ /** Initial nap is seconds */
private int m_initialNap = 0; private int m_initialNap = 0;
/** Miliseconds to sleep - 10 Min default */ /** Miliseconds to sleep - 10 Min default */
private long m_sleepMS = 600000; private long m_sleepMS = 600000;
/** Sleeping */ /** Sleeping */
private volatile boolean m_sleeping = false; private volatile boolean m_sleeping = false;
/** Server start time */ /** Server start time */
private long m_start = 0; private long m_start = 0;
/** Number of Work executions */ /** Number of Work executions */
protected int p_runCount = 0; protected int p_runCount = 0;
/** Tine start of work */ /** Tine start of work */
protected long p_startWork = 0; protected long p_startWork = 0;
/** Number MS of last Run */ /** Number MS of last Run */
private long m_runLastMS = 0; private long m_runLastMS = 0;
/** Number of MS total */ /** Number of MS total */
private long m_runTotalMS = 0; private long m_runTotalMS = 0;
/** When to run next */ /** When to run next */
private long m_nextWork = 0; private long m_nextWork = 0;
/** Logger */ /** Logger */
protected CLogger log = CLogger.getCLogger(getClass()); protected CLogger log = CLogger.getCLogger(getClass());
/** Context */ /** Context */
private Properties m_ctx = null; private Properties m_ctx = null;
/** System */ /** System */
protected static MSystem p_system = null; protected static MSystem p_system = null;
/** Client */ /** Client */
protected MClient p_client = null; protected MClient p_client = null;
/** /**
* Get Server Context * Get Server Context
* @return context * @return context
*/ */
public Properties getCtx() public Properties getCtx()
{ {
return m_ctx; return m_ctx;
} // getCtx } // getCtx
/** /**
* @return Returns the sleepMS. * @return Returns the sleepMS.
*/ */
public long getSleepMS () public long getSleepMS ()
{ {
return m_sleepMS; return m_sleepMS;
} // getSleepMS } // getSleepMS
/** /**
* Sleep for set time * Sleep for set time
* @return true if not interrupted * @return true if not interrupted
*/ */
public boolean sleep() public boolean sleep()
{ {
if (isInterrupted()) if (isInterrupted())
{ {
log.info (getName() + ": interrupted"); log.info (getName() + ": interrupted");
return false; return false;
} }
log.fine(getName() + ": sleeping " + TimeUtil.formatElapsed(m_sleepMS)); log.fine(getName() + ": sleeping " + TimeUtil.formatElapsed(m_sleepMS));
m_sleeping = true; m_sleeping = true;
try try
{ {
sleep (m_sleepMS); sleep (m_sleepMS);
} }
catch (InterruptedException e) catch (InterruptedException e)
{ {
log.info (getName() + ": interrupted"); log.info (getName() + ": interrupted");
m_sleeping = false; m_sleeping = false;
return false; return false;
} }
m_sleeping = false; m_sleeping = false;
return true; return true;
} // sleep } // sleep
/** /**
* Run Now * Run Now
*/ */
public void runNow() public void runNow()
{ {
log.info(getName()); log.info(getName());
p_startWork = System.currentTimeMillis(); p_startWork = System.currentTimeMillis();
doWork(); doWork();
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
// --------------- // ---------------
p_runCount++; p_runCount++;
m_runLastMS = now - p_startWork; m_runLastMS = now - p_startWork;
m_runTotalMS += m_runLastMS; m_runTotalMS += m_runLastMS;
// //
p_model.setDateLastRun(new Timestamp(now)); p_model.setDateLastRun(new Timestamp(now));
p_model.save(); p_model.save();
// //
log.fine(getName() + ": " + getStatistics()); log.fine(getName() + ": " + getStatistics());
} // runNow } // runNow
/************************************************************************** /**************************************************************************
* Run async * Run async
*/ */
public void run () public void run ()
{ {
try try
{ {
log.fine(getName() + ": pre-nap - " + m_initialNap); log.fine(getName() + ": pre-nap - " + m_initialNap);
sleep (m_initialNap * 1000); sleep (m_initialNap * 1000);
} }
catch (InterruptedException e) catch (InterruptedException e)
{ {
log.log(Level.SEVERE, getName() + ": pre-nap interrupted", e); log.log(Level.SEVERE, getName() + ": pre-nap interrupted", e);
return; return;
} }
m_start = System.currentTimeMillis(); m_start = System.currentTimeMillis();
while (true) while (true)
{ {
if (m_nextWork == 0) if (m_nextWork == 0)
{ {
Timestamp dateNextRun = getDateNextRun(true); Timestamp dateNextRun = getDateNextRun(true);
if (dateNextRun != null) if (dateNextRun != null)
m_nextWork = dateNextRun.getTime(); m_nextWork = dateNextRun.getTime();
} }
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
if (m_nextWork > now) if (m_nextWork > now)
{ {
m_sleepMS = m_nextWork - now; m_sleepMS = m_nextWork - now;
if (!sleep ()) if (!sleep ())
break; break;
} }
if (isInterrupted()) if (isInterrupted())
{ {
log.info (getName() + ": interrupted"); log.info (getName() + ": interrupted");
break; break;
} }
// --------------- // ---------------
p_startWork = System.currentTimeMillis(); p_startWork = System.currentTimeMillis();
doWork(); doWork();
now = System.currentTimeMillis(); now = System.currentTimeMillis();
// --------------- // ---------------
p_runCount++; p_runCount++;
m_runLastMS = now - p_startWork; m_runLastMS = now - p_startWork;
m_runTotalMS += m_runLastMS; m_runTotalMS += m_runLastMS;
// //
m_sleepMS = calculateSleep(); m_sleepMS = calculateSleep();
m_nextWork = now + m_sleepMS; m_nextWork = now + m_sleepMS;
// //
p_model.setDateLastRun(new Timestamp(now)); p_model.setDateLastRun(new Timestamp(now));
p_model.setDateNextRun(new Timestamp(m_nextWork)); p_model.setDateNextRun(new Timestamp(m_nextWork));
p_model.save(); p_model.save();
// //
log.fine(getName() + ": " + getStatistics()); log.fine(getName() + ": " + getStatistics());
if (!sleep()) if (!sleep())
break; break;
} }
m_start = 0; m_start = 0;
} // run } // run
/** /**
* Get Run Statistics * Get Run Statistics
* @return Statistic info * @return Statistic info
*/ */
public String getStatistics() public String getStatistics()
{ {
return "Run #" + p_runCount return "Run #" + p_runCount
+ " - Last=" + TimeUtil.formatElapsed(m_runLastMS) + " - Last=" + TimeUtil.formatElapsed(m_runLastMS)
+ " - Total=" + TimeUtil.formatElapsed(m_runTotalMS) + " - Total=" + TimeUtil.formatElapsed(m_runTotalMS)
+ " - Next " + TimeUtil.formatElapsed(m_nextWork - System.currentTimeMillis()); + " - Next " + TimeUtil.formatElapsed(m_nextWork - System.currentTimeMillis());
} // getStatistics } // getStatistics
/** /**
* Do the actual Work * Do the actual Work
*/ */
protected abstract void doWork(); protected abstract void doWork();
/** /**
* Get Server Info * Get Server Info
* @return info * @return info
*/ */
public abstract String getServerInfo(); public abstract String getServerInfo();
/** /**
* Get Unique ID * Get Unique ID
* @return Unique ID * @return Unique ID
*/ */
public String getServerID() public String getServerID()
{ {
return p_model.getServerID(); return p_model.getServerID();
} // getServerID } // getServerID
/** /**
* Get the date Next run * Get the date Next run
* @param requery requery database * @param requery requery database
* @return date next run * @return date next run
*/ */
public Timestamp getDateNextRun (boolean requery) public Timestamp getDateNextRun (boolean requery)
{ {
return p_model.getDateNextRun(requery); return p_model.getDateNextRun(requery);
} // getDateNextRun } // getDateNextRun
/** /**
* Get the date Last run * Get the date Last run
* @return date lext run * @return date lext run
*/ */
public Timestamp getDateLastRun () public Timestamp getDateLastRun ()
{ {
return p_model.getDateLastRun(); return p_model.getDateLastRun();
} // getDateLastRun } // getDateLastRun
/** /**
* Get Description * Get Description
* @return Description * @return Description
*/ */
public String getDescription() public String getDescription()
{ {
return p_model.getDescription(); return p_model.getDescription();
} // getDescription } // getDescription
/** /**
* Get Model * Get Model
* @return Model * @return Model
*/ */
@ -301,82 +301,82 @@ public abstract class AdempiereServer extends Thread
{ {
return p_model; return p_model;
} // getModel } // getModel
/** /**
* Calculate Sleep ms * Calculate Sleep ms
* @return miliseconds * @return miliseconds
*/ */
private long calculateSleep () private long calculateSleep ()
{ {
String frequencyType = p_model.getFrequencyType(); String frequencyType = p_model.getFrequencyType();
int frequency = p_model.getFrequency(); int frequency = p_model.getFrequency();
if (frequency < 1) if (frequency < 1)
frequency = 1; frequency = 1;
// //
long typeSec = 600; // 10 minutes long typeSec = 600; // 10 minutes
if (frequencyType == null) if (frequencyType == null)
typeSec = 300; // 5 minutes typeSec = 300; // 5 minutes
else if (X_R_RequestProcessor.FREQUENCYTYPE_Minute.equals(frequencyType)) else if (X_R_RequestProcessor.FREQUENCYTYPE_Minute.equals(frequencyType))
typeSec = 60; typeSec = 60;
else if (X_R_RequestProcessor.FREQUENCYTYPE_Hour.equals(frequencyType)) else if (X_R_RequestProcessor.FREQUENCYTYPE_Hour.equals(frequencyType))
typeSec = 3600; typeSec = 3600;
else if (X_R_RequestProcessor.FREQUENCYTYPE_Day.equals(frequencyType)) else if (X_R_RequestProcessor.FREQUENCYTYPE_Day.equals(frequencyType))
typeSec = 86400; typeSec = 86400;
// //
return typeSec * 1000 * frequency; // ms return typeSec * 1000 * frequency; // ms
} // calculateSleep } // calculateSleep
/** /**
* Is Sleeping * Is Sleeping
* @return sleeping * @return sleeping
*/ */
public boolean isSleeping() public boolean isSleeping()
{ {
return m_sleeping; return m_sleeping;
} // isSleeping } // isSleeping
/** /**
* String Representation * String Representation
* @return info * @return info
*/ */
public String toString () public String toString ()
{ {
StringBuffer sb = new StringBuffer (getName()) StringBuffer sb = new StringBuffer (getName())
.append (",Prio=").append(getPriority()) .append (",Prio=").append(getPriority())
.append (",").append (getThreadGroup()) .append (",").append (getThreadGroup())
.append (",Alive=").append(isAlive()) .append (",Alive=").append(isAlive())
.append (",Sleeping=").append(m_sleeping) .append (",Sleeping=").append(m_sleeping)
.append (",Last=").append(getDateLastRun()); .append (",Last=").append(getDateLastRun());
if (m_sleeping) if (m_sleeping)
sb.append (",Next=").append(getDateNextRun(false)); sb.append (",Next=").append(getDateNextRun(false));
return sb.toString (); return sb.toString ();
} // toString } // toString
/** /**
* Get Seconds Alive * Get Seconds Alive
* @return seconds alive * @return seconds alive
*/ */
public int getSecondsAlive() public int getSecondsAlive()
{ {
if (m_start == 0) if (m_start == 0)
return 0; return 0;
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
long ms = (now-m_start) / 1000; long ms = (now-m_start) / 1000;
return (int)ms; return (int)ms;
} // getSecondsAlive } // getSecondsAlive
/** /**
* Get Start Time * Get Start Time
* @return start time * @return start time
*/ */
public Timestamp getStartTime() public Timestamp getStartTime()
{ {
if (m_start == 0) if (m_start == 0)
return null; return null;
return new Timestamp (m_start); return new Timestamp (m_start);
} // getStartTime } // getStartTime
/** /**
* Get Processor Logs * Get Processor Logs
* @return logs * @return logs
*/ */

View File

@ -20,7 +20,6 @@ import java.sql.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import org.compiere.*; import org.compiere.*;
import org.compiere.ldap.*;
import org.compiere.model.*; import org.compiere.model.*;
import org.compiere.util.*; import org.compiere.util.*;
import org.compiere.wf.*; import org.compiere.wf.*;
@ -148,12 +147,15 @@ public class AdempiereServerMgr
m_servers.add(server); m_servers.add(server);
} }
// LDAP // LDAP
LdapProcessorModel lp = new LdapProcessorModel(m_ctx); MLdapProcessor[] ldapModels = MLdapProcessor.getActive(m_ctx);
AdempiereServer server = AdempiereServer.create(lp); for (int i = 0; i < ldapModels.length; i++)
server.start(); {
server.setPriority(Thread.NORM_PRIORITY-2); MLdapProcessor lp = ldapModels[i];
m_servers.add(server); AdempiereServer server = AdempiereServer.create(lp);
server.start();
server.setPriority(Thread.NORM_PRIORITY-1);
m_servers.add(server);
}
log.fine("#" + noServers); log.fine("#" + noServers);
return startAll(); return startAll();

View File

@ -3,7 +3,7 @@
codebase = "$$context/adempiereHome" codebase = "$$context/adempiereHome"
href = "$$context/adempiere.jnlp"> href = "$$context/adempiere.jnlp">
<information> <information>
<title>Adempiere Client 3.1.1 $$context</title> <title>Adempiere Client 3.1.2 $$context</title>
<vendor>ComPiere, Inc.</vendor> <vendor>ComPiere, Inc.</vendor>
<homepage href = "http://www.adempiere.org"/> <homepage href = "http://www.adempiere.org"/>
<offline-allowed/> <offline-allowed/>