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;
} // 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;
} // 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

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
* 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
* You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org
*****************************************************************************/
package org.compiere.ldap;
import java.io.*;
import java.net.*;
import java.util.logging.*;
import org.compiere.ldap.*;
import org.compiere.util.*;
import com.sun.jndi.ldap.*;
/**
* LDAP Connection Handler
*
import java.io.*;
import java.net.*;
import java.util.Hashtable;
import java.util.logging.*;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.ldap.InitialLdapContext;
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
* @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
* @param socket server socket
*/
public LdapConnectionHandler(Socket socket)
{
try
{
m_socket = socket;
m_socket.setTcpNoDelay(true); // should not be required
* @param model model
*/
public LdapConnectionHandler(Socket socket, MLdapProcessor model)
{
try
{
m_socket = socket;
m_socket.setTcpNoDelay(true); // should not be required
m_model = model;
}
catch (Exception e)
{
@ -49,6 +80,8 @@ public class LdapConnectionHandler extends Thread
/** Socket */
private Socket m_socket = null;
/** Ldap Model */
private MLdapProcessor m_model = null;
/** Logger */
private static CLogger log = CLogger.getCLogger (LdapConnectionHandler.class);
@ -63,6 +96,9 @@ public class LdapConnectionHandler extends Thread
if (m_socket == null || m_socket.isClosed())
return;
LdapMessage msg = new LdapMessage();
MLdapUser ldapUser = new MLdapUser();
LdapResult result = new LdapResult();
boolean activeSession = true;
while (activeSession)
{
@ -72,21 +108,31 @@ public class LdapConnectionHandler extends Thread
byte[] buffer = new byte[512];
int length = in.read(buffer, 0, 512);
LdapMessage msg = new LdapMessage (buffer, length);
if (msg.getOperation() == LdapMessage.UNBIND_REQUEST)
{
activeSession = false;
out.close();
}
else
{
LdapResult result = new LdapResult ();
byte[] bytes = result.bindResponse();
//
out.write(bytes);
out.flush();
}
}
// Decode the input message buffer
result.reset(msg, ldapUser);
msg.reset(result);
msg.decode(buffer, length);
if (msg.getOperation() == LdapMessage.UNBIND_REQUEST)
{
out.close();
break;
}
// Not unbind, so we can create a response
byte[] bytes = result.getResult(m_model);
// 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)
{
@ -115,4 +161,42 @@ public class LdapConnectionHandler extends Thread
return sb.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
* 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
* You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org
*****************************************************************************/
package org.compiere.ldap;
import java.util.logging.*;
import java.util.logging.*;
import org.compiere.util.*;
import com.sun.jndi.ldap.*;
@ -27,138 +28,235 @@ import com.sun.jndi.ldap.*;
*/
public class LdapMessage
{
/**
* Ldap Message
* @param data BER data
* @param length Ber data length
*/
public LdapMessage (byte[] data, int length)
{
try
{
decode(data, length);
}
catch (Exception e)
{
log.log(Level.SEVERE, data.toString(), e);
}
} // LdapMessage
/**
LDAPMessage ::= SEQUENCE {
messageID MessageID,
protocolOp CHOICE {
bindRequest BindRequest,
bindResponse BindResponse,
unbindRequest UnbindRequest,
searchRequest SearchRequest,
searchResEntry SearchResultEntry,
searchResDone SearchResultDone,
searchResRef SearchResultReference,
modifyRequest ModifyRequest,
modifyResponse ModifyResponse,
addRequest AddRequest,
addResponse AddResponse,
delRequest DelRequest,
delResponse DelResponse,
modDNRequest ModifyDNRequest,
modDNResponse ModifyDNResponse,
compareRequest CompareRequest,
compareResponse CompareResponse,
abandonRequest AbandonRequest,
extendedReq ExtendedRequest,
extendedResp ExtendedResponse },
controls [0] Controls OPTIONAL }
**/
static public final int BIND_REQUEST = 0;
static public final int BIND_RESPONSE = 1;
static public final int UNBIND_REQUEST = 2;
static public final int SEARCH_REQUEST = 3;
static public final int SEARCH_RESENTRY = 4;
static public final int SEARCH_RESDONE = 5;
static public final int MODIFY_REQUEST = 6;
static public final int MODIFY_RESPONSE = 7;
static public final int ADD_REQUEST = 8;
static public final int ADD_RESPONSE = 9;
static public final int DEL_REQUEST = 10;
static public final int DEL_RESPONSE = 11;
static public final int MODDN_REQUEST = 12;
static public final int MODDN_RESPONSE = 13;
static public final int COMPARE_REQUEST = 14;
static public final int COMPARE_RESPONSE = 15;
static public final int ABANDON_REQUEST = 16;
static public final int EXTENDED_REQUEST = 17;
static public final int EXTENDED_RESPONSE = 18;
static public final int[] PROTOCOL_OP = {
BIND_REQUEST, BIND_RESPONSE, UNBIND_REQUEST,
SEARCH_REQUEST, SEARCH_RESENTRY, SEARCH_RESDONE,
MODIFY_REQUEST, MODIFY_RESPONSE, ADD_REQUEST, ADD_RESPONSE,
DEL_REQUEST, DEL_RESPONSE, MODDN_REQUEST, MODDN_RESPONSE,
COMPARE_REQUEST, COMPARE_RESPONSE, ABANDON_REQUEST,
EXTENDED_REQUEST, EXTENDED_RESPONSE};
/** Logger */
private static CLogger log = CLogger.getCLogger (LdapMessage.class);
/** Protocol Operation */
private int m_protocolOp = -1;
/**
* Decode Message
* @param data data
* @param length length
* @throws Exception
*/
private void decode (byte[] data, int length) throws Exception
{
BerDecoder decoder = new BerDecoder(data, 0, length);
int left = decoder.bytesLeft();
int pos = decoder.getParsePosition();
//
int seq = decoder.parseSeq(null);
left = decoder.bytesLeft();
pos = decoder.getParsePosition();
//
int messageID = decoder.parseInt();
left = decoder.bytesLeft();
pos = decoder.getParsePosition();
//
int peek = decoder.peekByte();
m_protocolOp = decoder.parseSeq(PROTOCOL_OP);
m_protocolOp -= Ber.ASN_APPLICATION;
if (m_protocolOp - Ber.ASN_CONSTRUCTOR >= 0)
m_protocolOp -= Ber.ASN_CONSTRUCTOR;
left = decoder.bytesLeft();
pos = decoder.getParsePosition();
//
// Payload
if (m_protocolOp == BIND_REQUEST)
{
int version = decoder.parseInt();
left = decoder.bytesLeft();
pos = decoder.getParsePosition();
//
byte[] dn = decoder.parseOctetString(Ber.ASN_OCTET_STR, null);
left = decoder.bytesLeft();
pos = decoder.getParsePosition();
//
byte[] authentification = decoder.parseOctetString(Ber.ASN_CONTEXT, null);
left = decoder.bytesLeft();
pos = decoder.getParsePosition();
//
log.info("#" + messageID + ": bind - version=" + version + ", dn=" + new String(dn)
+ ", auth=" + new String (authentification));
}
else if (m_protocolOp == UNBIND_REQUEST)
log.info("#" + messageID + ": unbind");
else
{
log.warning("#" + messageID + ": Unknown Op + " + m_protocolOp);
}
} // decode
static public final int BIND_REQUEST = 96;
static public final int BIND_RESPONSE = 97;
static public final int UNBIND_REQUEST = 98;
static public final int SEARCH_REQUEST = 99;
static public final int SEARCH_REP_ENTRY = 100;
static public final int SEARCH_RES_RESULT = 101;
static public final int SIMPLE_AUTHENTICATION = 128;
static public final int FILTER_AND = 160;
static public final int FILTER_OR = 161;
static public final int FILTER_NOT = 162;
static public final int FILTER_EQUALITYMATCH = 163;
static public final int SEQUENCE = 48;
/** Decoder */
private BerDecoder decoder = null;
/** Logger */
private static CLogger log = CLogger.getCLogger (LdapMessage.class);
/** Protocol Operation */
private int m_protocolOp = -1;
/** Message Id needed for the reply message */
private int msgId;
/** Distinguished name */
private String dn = null;
/** Organization */
private String org = null;
/** Organization unit */
private String orgUnit = null;
/** User Id */
private String userId = null;
/** Password */
private String passwd = null;
/** base Object */
private String baseObj = null;
/** LdapResult object to hold if there's any error during parsing */
private LdapResult result = null;
/**
* Ldap Message
*/
public LdapMessage()
{
} // LdapMessage
/*
* Reset all the attributes
*/
public void reset(LdapResult result)
{
this.result = result;
decoder = null;
m_protocolOp = -1;
msgId = -1;
dn = null;
org = null;
orgUnit = null;
userId = null;
passwd = null;
baseObj = null;
} // reset()
/**
* Decode Message
* @param data input buffer
* @param length buffer size
*/
public void decode(byte[] data, int length)
{
try
{
// Create the decoder
decoder = new BerDecoder(data, 0, length);
}
catch (Exception e)
{
log.log(Level.SEVERE, data.toString(), e);
return;
}
try
{
// Parse the message envelope
decoder.parseSeq(null);
// Parse message Id
msgId = decoder.parseInt();
// Parse the operation protocol
m_protocolOp = decoder.parseSeq(null);
//
// Payload
if (m_protocolOp == BIND_REQUEST)
handleBind();
else if (m_protocolOp == UNBIND_REQUEST)
log.info("#" + msgId + ": unbind");
else if (m_protocolOp == SEARCH_REQUEST)
handleSearch();
else // Only supoort BIND, UNBIND and SEARCH
{
result.setErrorNo(LdapResult.LDAP_PROTOCOL_ERROR);
result.setErrorString(": Unsupported Request");
log.warning("#" + msgId + ": Unknown Op + " + m_protocolOp);
}
}
catch (Exception ex)
{
result.setErrorNo(LdapResult.LDAP_PROTOCOL_ERROR);
log.log(Level.SEVERE, "", ex);
}
} // decode
/*
* Encode the search request message
*/
private void handleSearch()
{
try
{
// Parse the base Object
baseObj = decoder.parseString(true);
parseDN(baseObj);
decoder.parseEnumeration(); // scope
decoder.parseEnumeration(); // derefAliases
decoder.parseInt(); // sizeLimit
decoder.parseInt(); // timeLimit
decoder.parseBoolean(); // typeOnly
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
@ -169,4 +267,66 @@ public class LdapMessage
return m_protocolOp;
} // 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
* 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
* You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org
*****************************************************************************/
package org.compiere.ldap;
@ -19,9 +19,7 @@ import java.net.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import javax.naming.ldap.*;
import org.compiere.*;
import org.compiere.ldap.*;
import org.compiere.model.*;
import org.compiere.server.*;
import org.compiere.util.*;
@ -38,19 +36,16 @@ public class LdapProcessor extends AdempiereServer
* Ldap Processor (Server)
* @param model Ldap Model
*/
public LdapProcessor (LdapProcessorModel model)
public LdapProcessor (MLdapProcessor model)
{
super (model, 300);
m_model = model;
init();
} // LdapProcessor
/** The Concrete Model */
private LdapProcessorModel m_model = null;
private MLdapProcessor m_model = null;
/** Last Summary */
private StringBuffer m_summary = new StringBuffer();
/** Client info */
private MClient m_client = null;
/** Server Socket */
private ServerSocket m_serverSocket = null;
/** Counter */
@ -87,7 +82,8 @@ public class LdapProcessor extends AdempiereServer
{
Socket socket = m_serverSocket.accept(); // waits for connection
log.log(Level.FINE, "Connection on Port=" + m_model.getLdapPort());
LdapConnectionHandler handler = new LdapConnectionHandler (socket);
LdapConnectionHandler handler =
new LdapConnectionHandler (socket, m_model);
handler.start();
m_counter++;
}
@ -98,24 +94,19 @@ public class LdapProcessor extends AdempiereServer
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
/**
* 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
@ -124,7 +115,8 @@ public class LdapProcessor extends AdempiereServer
public String getServerInfo()
{
return "#" + p_runCount + " - Last=" + m_summary.toString()
+ "; Counter=" + m_counter;
+ "; Counter=" + m_counter
+ "; " + m_model.getInfo();
} // getServerInfo
/**
@ -134,7 +126,7 @@ public class LdapProcessor extends AdempiereServer
public static void main(String[] args)
{
Adempiere.startup(true);
new LdapProcessor(new LdapProcessorModel(new Properties())).doWork();
new LdapProcessor(new MLdapProcessor(new Properties(), 0, null)).doWork();
} // main
} // 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
* 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
* You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org
*****************************************************************************/
package org.compiere.ldap;
import java.io.*;
import java.util.logging.*;
import org.compiere.model.*;
import org.compiere.util.*;
import com.sun.jndi.ldap.*;
import com.sun.jndi.ldap.BerEncoder;
/**
* Ldap Wire Response
@ -28,120 +28,278 @@ import com.sun.jndi.ldap.*;
*/
public class LdapResult
{
public LdapResult()
{
super ();
} // LdapResult
/**
LDAPResult ::= SEQUENCE {
resultCode ENUMERATED {
success (0),
operationsError (1),
protocolError (2),
timeLimitExceeded (3),
sizeLimitExceeded (4),
compareFalse (5),
compareTrue (6),
authMethodNotSupported (7),
strongAuthRequired (8),
-- 9 reserved --
referral (10), -- new
adminLimitExceeded (11), -- new
unavailableCriticalExtension (12), -- new
confidentialityRequired (13), -- new
saslBindInProgress (14), -- new
noSuchAttribute (16),
undefinedAttributeType (17),
inappropriateMatching (18),
constraintViolation (19),
attributeOrValueExists (20),
invalidAttributeSyntax (21),
noSuchObject (32),
aliasProblem (33),
invalidDNSyntax (34),
-- 35 reserved for undefined isLeaf --
aliasDereferencingProblem (36),
-- 37-47 unused --
inappropriateAuthentication (48),
invalidCredentials (49),
insufficientAccessRights (50),
busy (51),
unavailable (52),
unwillingToPerform (53),
loopDetect (54),
-- 55-63 unused --
namingViolation (64),
objectClassViolation (65),
notAllowedOnNonLeaf (66),
notAllowedOnRDN (67),
entryAlreadyExists (68),
objectClassModsProhibited (69),
-- 70 reserved for CLDAP --
affectsMultipleDSAs (71), -- new
-- 72-79 unused --
other (80) },
-- 81-90 reserved for APIs --
matchedDN LDAPDN,
errorMessage LDAPString,
referral [3] Referral OPTIONAL }
**/
/** Encoder */
private BerEncoder m_encoder = new BerEncoder();
/** Logger */
private static CLogger log = CLogger.getCLogger (LdapResult.class);
/**
* Bind Response
* @return reponse
*/
public byte[] bindResponse()
{
try
{
/**
m_encoder.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
for (int i = 0; i < sortKeys.length; i++) {
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
ber.encodeString(sortKeys[i].getAttributeID(), true); // v3
if ((matchingRule = sortKeys[i].getMatchingRuleID()) != null) {
ber.encodeString(matchingRule, (Ber.ASN_CONTEXT | 0), true);
}
if (! sortKeys[i].isAscending()) {
ber.encodeBoolean(true, (Ber.ASN_CONTEXT | 1));
}
ber.endSeq();
}
*/
// payload
m_encoder.beginSeq(Ber.ASN_APPLICATION | LdapMessage.BIND_RESPONSE);
// Response
m_encoder.encodeInt(0); // success
m_encoder.encodeOctetString("cn=testCN".getBytes(), 0); // matched DN
m_encoder.encodeOctetString("".getBytes(), 0); // error mag
// referral
// sasl
//
m_encoder.endSeq();
log.info("Success");
}
catch (Exception e)
{
log.log(Level.SEVERE, "", e);
}
return getResult();
} // bindResponse
/**
* Get BER Result as byte array
* @return byte array
*/
public byte[] getResult()
{
return m_encoder.getTrimmedBuf();
} // getResult
} // LdapResult
/** LdapMesssage */
private LdapMessage ldapMsg = null;
/** Encoder */
private BerEncoder m_encoder = null;
/** Logger */
private static CLogger log = CLogger.getCLogger (LdapResult.class);
/** Error number */
private int errNo = LDAP_SUCCESS;
/** Error String */
private String errStr = "";
/** LdapUser */
private MLdapUser ldapUser = null;
/** disconnect to client */
private boolean disconnect = false;
public LdapResult ()
{
} // LdapResult
/*
* Reset the attributes
*/
public void reset(LdapMessage ldapMsg, MLdapUser ldapUser)
{
this.ldapMsg = ldapMsg;
m_encoder = new BerEncoder();
errNo = LDAP_SUCCESS;
errStr = "";
this.ldapUser = ldapUser;
} // reset()
/**
* Get the response according to the request message
* @param model model
* @return reponse
*/
public byte[] getResult(MLdapProcessor model)
{
if (errNo != LDAP_SUCCESS)
{
generateResult("",
((ldapMsg.getOperation()==LdapMessage.BIND_REQUEST)?
LdapMessage.BIND_RESPONSE:LdapMessage.SEARCH_RES_RESULT),
errNo, ldapErrorMessage[errNo] + errStr);
m_encoder.getTrimmedBuf();
}
try
{
String usrId = ldapMsg.getUserId();
String o = ldapMsg.getOrg();
String ou = ldapMsg.getOrgUnit();
// Adding the Application 1 Sequence
if (ldapMsg.getOperation() == LdapMessage.BIND_REQUEST)
{
String pwd = ldapMsg.getUserPasswd();
if (pwd == null || pwd.length() <= 0)
{
// 1st anonymous bind
generateResult(ldapMsg.getDN(), LdapMessage.BIND_RESPONSE,
LDAP_SUCCESS, null);
log.info("Success");
return m_encoder.getTrimmedBuf();
}
// Authenticate with Compiere data
if (ldapUser.getUserId() == null)
{ // Try to authenticate on the 1st bind, must be java client
ldapUser.reset();
model.authenticate(ldapUser, usrId, o, ou);
if (ldapUser.getErrorMsg() != null)
{ // Failed to authenticated with compiere
errNo = LDAP_NO_SUCH_OBJECT;
generateResult(ldapMsg.getBaseObj(), LdapMessage.SEARCH_RES_RESULT,
LDAP_NO_SUCH_OBJECT,
ldapErrorMessage[LDAP_NO_SUCH_OBJECT] + ldapUser.getErrorMsg());
log.info("Failed");
return m_encoder.getTrimmedBuf();
}
}
// Check to see if the input passwd is match to the one
// in compiere database
if (usrId.compareTo(ldapUser.getUserId()) == 0 &&
pwd.compareTo(ldapUser.getPassword()) == 0)
{ // Successfully authenticated
generateResult("", LdapMessage.BIND_RESPONSE,
LDAP_SUCCESS, null);
// Close the connection to client since most of the client
// application might cache the connection but we can't afford
// to have too many such client connection
disconnect = true;
log.info("Success");
}
else
{ // Unsuccessfully authenticated
errNo = LDAP_INAPPROPRIATE_AUTHENTICATION;
generateResult("", LdapMessage.BIND_RESPONSE,
LDAP_INAPPROPRIATE_AUTHENTICATION,
ldapErrorMessage[LDAP_INAPPROPRIATE_AUTHENTICATION]);
log.info("Failed : " + ldapErrorMessage[LDAP_INAPPROPRIATE_AUTHENTICATION]);
}
}
else if (ldapMsg.getOperation() == LdapMessage.SEARCH_REQUEST)
{
// Authenticate with compiere database
ldapUser.reset();
model.authenticate(ldapUser, usrId, o, ou);
if (ldapUser.getErrorMsg() != null)
{
errNo = LDAP_NO_SUCH_OBJECT;
generateResult(ldapMsg.getBaseObj(), LdapMessage.SEARCH_RES_RESULT,
LDAP_NO_SUCH_OBJECT,
ldapErrorMessage[LDAP_NO_SUCH_OBJECT] + ldapUser.getErrorMsg());
log.info("Failed");
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. *
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.server;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.ldap.*;
import org.compiere.model.*;
import org.compiere.util.*;
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.server;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.ldap.*;
import org.compiere.model.*;
import org.compiere.util.*;
import org.compiere.wf.*;
/**
@ -41,23 +41,23 @@ public abstract class AdempiereServer extends Thread
{
if (model instanceof MRequestProcessor)
return new RequestProcessor ((MRequestProcessor)model);
if (model instanceof MWorkflowProcessor)
return new WorkflowProcessor ((MWorkflowProcessor)model);
if (model instanceof MAcctProcessor)
return new AcctProcessor ((MAcctProcessor)model);
if (model instanceof MAlertProcessor)
if (model instanceof MWorkflowProcessor)
return new WorkflowProcessor ((MWorkflowProcessor)model);
if (model instanceof MAcctProcessor)
return new AcctProcessor ((MAcctProcessor)model);
if (model instanceof MAlertProcessor)
return new AlertProcessor ((MAlertProcessor)model);
if (model instanceof MScheduler)
return new Scheduler ((MScheduler)model);
if (model instanceof LdapProcessorModel)
return new LdapProcessor((LdapProcessorModel)model);
if (model instanceof MLdapProcessor)
return new LdapProcessor((MLdapProcessor)model);
//
throw new IllegalArgumentException("Unknown Processor");
} // create
/**************************************************************************
* Server Base Class
/**************************************************************************
* Server Base Class
* @param model model
* @param initialNap delay time running in sec
*/
@ -67,11 +67,11 @@ public abstract class AdempiereServer extends Thread
p_model = model;
m_ctx = new Properties(model.getCtx());
if (p_system == null)
p_system = MSystem.get(m_ctx);
p_client = MClient.get(m_ctx);
Env.setContext(m_ctx, "#AD_Client_ID", p_client.getAD_Client_ID());
m_initialNap = initialNap;
// log.info(model.getName() + " - " + getThreadGroup());
p_system = MSystem.get(m_ctx);
p_client = MClient.get(m_ctx);
Env.setContext(m_ctx, "#AD_Client_ID", p_client.getAD_Client_ID());
m_initialNap = initialNap;
// log.info(model.getName() + " - " + getThreadGroup());
} // ServerBase
/** The Processor Model */
@ -79,221 +79,221 @@ public abstract class AdempiereServer extends Thread
/** Initial nap is seconds */
private int m_initialNap = 0;
/** Miliseconds to sleep - 10 Min default */
private long m_sleepMS = 600000;
/** Sleeping */
private volatile boolean m_sleeping = false;
/** Server start time */
private long m_start = 0;
/** Number of Work executions */
protected int p_runCount = 0;
/** Tine start of work */
protected long p_startWork = 0;
/** Number MS of last Run */
private long m_runLastMS = 0;
/** Number of MS total */
private long m_runTotalMS = 0;
/** When to run next */
private long m_nextWork = 0;
/** Logger */
protected CLogger log = CLogger.getCLogger(getClass());
/** Context */
private Properties m_ctx = null;
/** System */
protected static MSystem p_system = null;
/** Client */
protected MClient p_client = null;
/**
* Get Server Context
* @return context
*/
public Properties getCtx()
{
return m_ctx;
} // getCtx
/**
* @return Returns the sleepMS.
*/
public long getSleepMS ()
{
return m_sleepMS;
} // getSleepMS
/**
* Sleep for set time
* @return true if not interrupted
*/
public boolean sleep()
{
if (isInterrupted())
{
log.info (getName() + ": interrupted");
return false;
}
log.fine(getName() + ": sleeping " + TimeUtil.formatElapsed(m_sleepMS));
m_sleeping = true;
try
{
sleep (m_sleepMS);
}
catch (InterruptedException e)
{
log.info (getName() + ": interrupted");
m_sleeping = false;
return false;
}
m_sleeping = false;
return true;
} // sleep
/**
* Run Now
*/
public void runNow()
{
log.info(getName());
p_startWork = System.currentTimeMillis();
doWork();
long now = System.currentTimeMillis();
// ---------------
p_runCount++;
m_runLastMS = now - p_startWork;
m_runTotalMS += m_runLastMS;
//
p_model.setDateLastRun(new Timestamp(now));
p_model.save();
//
log.fine(getName() + ": " + getStatistics());
} // runNow
/**************************************************************************
* Run async
*/
public void run ()
{
try
{
log.fine(getName() + ": pre-nap - " + m_initialNap);
sleep (m_initialNap * 1000);
}
catch (InterruptedException e)
{
log.log(Level.SEVERE, getName() + ": pre-nap interrupted", e);
return;
}
m_start = System.currentTimeMillis();
while (true)
{
if (m_nextWork == 0)
{
Timestamp dateNextRun = getDateNextRun(true);
if (dateNextRun != null)
m_nextWork = dateNextRun.getTime();
}
long now = System.currentTimeMillis();
if (m_nextWork > now)
{
m_sleepMS = m_nextWork - now;
if (!sleep ())
break;
}
if (isInterrupted())
{
log.info (getName() + ": interrupted");
break;
}
// ---------------
p_startWork = System.currentTimeMillis();
doWork();
now = System.currentTimeMillis();
// ---------------
p_runCount++;
m_runLastMS = now - p_startWork;
m_runTotalMS += m_runLastMS;
//
m_sleepMS = calculateSleep();
m_nextWork = now + m_sleepMS;
//
p_model.setDateLastRun(new Timestamp(now));
p_model.setDateNextRun(new Timestamp(m_nextWork));
p_model.save();
//
log.fine(getName() + ": " + getStatistics());
if (!sleep())
break;
}
m_start = 0;
} // run
/**
* Get Run Statistics
* @return Statistic info
*/
public String getStatistics()
{
return "Run #" + p_runCount
+ " - Last=" + TimeUtil.formatElapsed(m_runLastMS)
+ " - Total=" + TimeUtil.formatElapsed(m_runTotalMS)
+ " - Next " + TimeUtil.formatElapsed(m_nextWork - System.currentTimeMillis());
} // getStatistics
/**
* Do the actual Work
*/
protected abstract void doWork();
/**
* Get Server Info
* @return info
*/
public abstract String getServerInfo();
/**
* Get Unique ID
* @return Unique ID
*/
public String getServerID()
{
return p_model.getServerID();
} // getServerID
/**
* Get the date Next run
* @param requery requery database
* @return date next run
*/
public Timestamp getDateNextRun (boolean requery)
{
return p_model.getDateNextRun(requery);
} // getDateNextRun
/**
* Get the date Last run
* @return date lext run
*/
public Timestamp getDateLastRun ()
{
return p_model.getDateLastRun();
} // getDateLastRun
/**
* Get Description
* @return Description
*/
public String getDescription()
{
return p_model.getDescription();
} // getDescription
/**
/** Miliseconds to sleep - 10 Min default */
private long m_sleepMS = 600000;
/** Sleeping */
private volatile boolean m_sleeping = false;
/** Server start time */
private long m_start = 0;
/** Number of Work executions */
protected int p_runCount = 0;
/** Tine start of work */
protected long p_startWork = 0;
/** Number MS of last Run */
private long m_runLastMS = 0;
/** Number of MS total */
private long m_runTotalMS = 0;
/** When to run next */
private long m_nextWork = 0;
/** Logger */
protected CLogger log = CLogger.getCLogger(getClass());
/** Context */
private Properties m_ctx = null;
/** System */
protected static MSystem p_system = null;
/** Client */
protected MClient p_client = null;
/**
* Get Server Context
* @return context
*/
public Properties getCtx()
{
return m_ctx;
} // getCtx
/**
* @return Returns the sleepMS.
*/
public long getSleepMS ()
{
return m_sleepMS;
} // getSleepMS
/**
* Sleep for set time
* @return true if not interrupted
*/
public boolean sleep()
{
if (isInterrupted())
{
log.info (getName() + ": interrupted");
return false;
}
log.fine(getName() + ": sleeping " + TimeUtil.formatElapsed(m_sleepMS));
m_sleeping = true;
try
{
sleep (m_sleepMS);
}
catch (InterruptedException e)
{
log.info (getName() + ": interrupted");
m_sleeping = false;
return false;
}
m_sleeping = false;
return true;
} // sleep
/**
* Run Now
*/
public void runNow()
{
log.info(getName());
p_startWork = System.currentTimeMillis();
doWork();
long now = System.currentTimeMillis();
// ---------------
p_runCount++;
m_runLastMS = now - p_startWork;
m_runTotalMS += m_runLastMS;
//
p_model.setDateLastRun(new Timestamp(now));
p_model.save();
//
log.fine(getName() + ": " + getStatistics());
} // runNow
/**************************************************************************
* Run async
*/
public void run ()
{
try
{
log.fine(getName() + ": pre-nap - " + m_initialNap);
sleep (m_initialNap * 1000);
}
catch (InterruptedException e)
{
log.log(Level.SEVERE, getName() + ": pre-nap interrupted", e);
return;
}
m_start = System.currentTimeMillis();
while (true)
{
if (m_nextWork == 0)
{
Timestamp dateNextRun = getDateNextRun(true);
if (dateNextRun != null)
m_nextWork = dateNextRun.getTime();
}
long now = System.currentTimeMillis();
if (m_nextWork > now)
{
m_sleepMS = m_nextWork - now;
if (!sleep ())
break;
}
if (isInterrupted())
{
log.info (getName() + ": interrupted");
break;
}
// ---------------
p_startWork = System.currentTimeMillis();
doWork();
now = System.currentTimeMillis();
// ---------------
p_runCount++;
m_runLastMS = now - p_startWork;
m_runTotalMS += m_runLastMS;
//
m_sleepMS = calculateSleep();
m_nextWork = now + m_sleepMS;
//
p_model.setDateLastRun(new Timestamp(now));
p_model.setDateNextRun(new Timestamp(m_nextWork));
p_model.save();
//
log.fine(getName() + ": " + getStatistics());
if (!sleep())
break;
}
m_start = 0;
} // run
/**
* Get Run Statistics
* @return Statistic info
*/
public String getStatistics()
{
return "Run #" + p_runCount
+ " - Last=" + TimeUtil.formatElapsed(m_runLastMS)
+ " - Total=" + TimeUtil.formatElapsed(m_runTotalMS)
+ " - Next " + TimeUtil.formatElapsed(m_nextWork - System.currentTimeMillis());
} // getStatistics
/**
* Do the actual Work
*/
protected abstract void doWork();
/**
* Get Server Info
* @return info
*/
public abstract String getServerInfo();
/**
* Get Unique ID
* @return Unique ID
*/
public String getServerID()
{
return p_model.getServerID();
} // getServerID
/**
* Get the date Next run
* @param requery requery database
* @return date next run
*/
public Timestamp getDateNextRun (boolean requery)
{
return p_model.getDateNextRun(requery);
} // getDateNextRun
/**
* Get the date Last run
* @return date lext run
*/
public Timestamp getDateLastRun ()
{
return p_model.getDateLastRun();
} // getDateLastRun
/**
* Get Description
* @return Description
*/
public String getDescription()
{
return p_model.getDescription();
} // getDescription
/**
* Get Model
* @return Model
*/
@ -301,82 +301,82 @@ public abstract class AdempiereServer extends Thread
{
return p_model;
} // getModel
/**
* Calculate Sleep ms
* @return miliseconds
*/
private long calculateSleep ()
{
String frequencyType = p_model.getFrequencyType();
int frequency = p_model.getFrequency();
if (frequency < 1)
frequency = 1;
//
long typeSec = 600; // 10 minutes
if (frequencyType == null)
typeSec = 300; // 5 minutes
else if (X_R_RequestProcessor.FREQUENCYTYPE_Minute.equals(frequencyType))
typeSec = 60;
else if (X_R_RequestProcessor.FREQUENCYTYPE_Hour.equals(frequencyType))
typeSec = 3600;
else if (X_R_RequestProcessor.FREQUENCYTYPE_Day.equals(frequencyType))
typeSec = 86400;
//
return typeSec * 1000 * frequency; // ms
} // calculateSleep
/**
* Is Sleeping
* @return sleeping
*/
public boolean isSleeping()
{
return m_sleeping;
} // isSleeping
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer (getName())
.append (",Prio=").append(getPriority())
.append (",").append (getThreadGroup())
.append (",Alive=").append(isAlive())
.append (",Sleeping=").append(m_sleeping)
.append (",Last=").append(getDateLastRun());
if (m_sleeping)
sb.append (",Next=").append(getDateNextRun(false));
return sb.toString ();
} // toString
/**
* Get Seconds Alive
* @return seconds alive
*/
public int getSecondsAlive()
{
if (m_start == 0)
return 0;
long now = System.currentTimeMillis();
long ms = (now-m_start) / 1000;
return (int)ms;
} // getSecondsAlive
/**
* Get Start Time
* @return start time
*/
public Timestamp getStartTime()
{
if (m_start == 0)
return null;
return new Timestamp (m_start);
} // getStartTime
/**
/**
* Calculate Sleep ms
* @return miliseconds
*/
private long calculateSleep ()
{
String frequencyType = p_model.getFrequencyType();
int frequency = p_model.getFrequency();
if (frequency < 1)
frequency = 1;
//
long typeSec = 600; // 10 minutes
if (frequencyType == null)
typeSec = 300; // 5 minutes
else if (X_R_RequestProcessor.FREQUENCYTYPE_Minute.equals(frequencyType))
typeSec = 60;
else if (X_R_RequestProcessor.FREQUENCYTYPE_Hour.equals(frequencyType))
typeSec = 3600;
else if (X_R_RequestProcessor.FREQUENCYTYPE_Day.equals(frequencyType))
typeSec = 86400;
//
return typeSec * 1000 * frequency; // ms
} // calculateSleep
/**
* Is Sleeping
* @return sleeping
*/
public boolean isSleeping()
{
return m_sleeping;
} // isSleeping
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer (getName())
.append (",Prio=").append(getPriority())
.append (",").append (getThreadGroup())
.append (",Alive=").append(isAlive())
.append (",Sleeping=").append(m_sleeping)
.append (",Last=").append(getDateLastRun());
if (m_sleeping)
sb.append (",Next=").append(getDateNextRun(false));
return sb.toString ();
} // toString
/**
* Get Seconds Alive
* @return seconds alive
*/
public int getSecondsAlive()
{
if (m_start == 0)
return 0;
long now = System.currentTimeMillis();
long ms = (now-m_start) / 1000;
return (int)ms;
} // getSecondsAlive
/**
* Get Start Time
* @return start time
*/
public Timestamp getStartTime()
{
if (m_start == 0)
return null;
return new Timestamp (m_start);
} // getStartTime
/**
* Get Processor Logs
* @return logs
*/

View File

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

View File

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