code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public static Class getClass(String className, boolean initialize) throws ClassNotFoundException
{
return Class.forName(className, initialize, getClassLoader());
} | Retrieves the class object for the given qualified class name.
@param className The qualified name of the class
@param initialize Whether the class shall be initialized
@return The class object |
public static Object newInstance(Class target, boolean makeAccessible) throws InstantiationException,
IllegalAccessException
{
if (makeAccessible)
{
try
{
return newInstance(target, NO_ARGS_CLASS, NO_ARGS, makeAccessible);
}
catch (InvocationTargetException e)
{
throw new OJBRuntimeException("Unexpected exception while instantiate class '"
+ target + "' with default constructor", e);
}
catch (NoSuchMethodException e)
{
throw new OJBRuntimeException("Unexpected exception while instantiate class '"
+ target + "' with default constructor", e);
}
}
else
{
return target.newInstance();
}
} | Returns a new instance of the given class, using the default or a no-arg constructor.
This method can also use private no-arg constructors if <code>makeAccessible</code>
is set to <code>true</code> (and there are no other security constraints).
@param target The class to instantiate
@param makeAccessible If the constructor shall be made accessible prior to using it
@return The instance |
public static Object newInstance(Class target, Class[] types, Object[] args) throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
NoSuchMethodException,
SecurityException
{
return newInstance(target, types, args, false);
} | Returns a new instance of the given class, using the constructor with the specified parameter types.
@param target The class to instantiate
@param types The parameter types
@param args The arguments
@return The instance |
public static Object newInstance(Class target, Class[] types, Object[] args, boolean makeAccessible) throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
NoSuchMethodException,
SecurityException
{
Constructor con;
if (makeAccessible)
{
con = target.getDeclaredConstructor(types);
if (makeAccessible && !con.isAccessible())
{
con.setAccessible(true);
}
}
else
{
con = target.getConstructor(types);
}
return con.newInstance(args);
} | Returns a new instance of the given class, using the constructor with the specified parameter types.
This method can also use private constructors if <code>makeAccessible</code> is set to
<code>true</code> (and there are no other security constraints).
@param target The class to instantiate
@param types The parameter types
@param args The arguments
@param makeAccessible If the constructor shall be made accessible prior to using it
@return The instance |
public static Method getMethod(Class clazz, String methodName, Class[] params)
{
try
{
return clazz.getMethod(methodName, params);
}
catch (Exception ignored)
{}
return null;
} | Determines the method with the specified signature via reflection look-up.
@param clazz The java class to search in
@param methodName The method's name
@param params The parameter types
@return The method object or <code>null</code> if no matching method was found |
public static Field getField(Class clazz, String fieldName)
{
try
{
return clazz.getField(fieldName);
}
catch (Exception ignored)
{}
return null;
} | Determines the field via reflection look-up.
@param clazz The java class to search in
@param fieldName The field's name
@return The field object or <code>null</code> if no matching field was found |
public static Object newInstance(String className) throws InstantiationException,
IllegalAccessException,
ClassNotFoundException
{
return newInstance(getClass(className));
} | Returns a new instance of the class with the given qualified name using the default or
or a no-arg constructor.
@param className The qualified name of the class to instantiate |
public static Object newInstance(String className, Class[] types, Object[] args) throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
NoSuchMethodException,
SecurityException,
ClassNotFoundException
{
return newInstance(getClass(className), types, args);
} | Returns a new instance of the class with the given qualified name using the constructor with
the specified signature.
@param className The qualified name of the class to instantiate
@param types The parameter types
@param args The arguments
@return The instance |
public static Object newInstance(Class target, Class type, Object arg) throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
NoSuchMethodException,
SecurityException
{
return newInstance(target, new Class[]{ type }, new Object[]{ arg });
} | Returns a new instance of the given class using the constructor with the specified parameter.
@param target The class to instantiate
@param type The types of the single parameter of the constructor
@param arg The argument
@return The instance |
public static Object newInstance(String className, Class type, Object arg) throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
NoSuchMethodException,
SecurityException,
ClassNotFoundException
{
return newInstance(className, new Class[]{type}, new Object[]{arg});
} | Returns a new instance of the class with the given qualified name using the constructor with
the specified parameter.
@param className The qualified name of the class to instantiate
@param type The types of the single parameter of the constructor
@param arg The argument
@return The instance |
public static Method getMethod(Object object, String methodName, Class[] params)
{
return getMethod(object.getClass(), methodName, params);
} | Determines the method with the specified signature via reflection look-up.
@param object The instance whose class is searched for the method
@param methodName The method's name
@param params The parameter types
@return A method object or <code>null</code> if no matching method was found |
public static Method getMethod(String className, String methodName, Class[] params)
{
try
{
return getMethod(getClass(className, false), methodName, params);
}
catch (Exception ignored)
{}
return null;
} | Determines the method with the specified signature via reflection look-up.
@param className The qualified name of the searched class
@param methodName The method's name
@param params The parameter types
@return A method object or <code>null</code> if no matching method was found |
public static Object buildNewObjectInstance(ClassDescriptor cld)
{
Object result = null;
// If either the factory class and/or factory method is null,
// just follow the normal code path and create via constructor
if ((cld.getFactoryClass() == null) || (cld.getFactoryMethod() == null))
{
try
{
// 1. create an empty Object (persistent classes need a public default constructor)
Constructor con = cld.getZeroArgumentConstructor();
if(con == null)
{
throw new ClassNotPersistenceCapableException(
"A zero argument constructor was not provided! Class was '" + cld.getClassNameOfObject() + "'");
}
result = ConstructorHelper.instantiate(con);
}
catch (InstantiationException e)
{
throw new ClassNotPersistenceCapableException(
"Can't instantiate class '" + cld.getClassNameOfObject()+"'");
}
}
else
{
try
{
// 1. create an empty Object by calling the no-parms factory method
Method method = cld.getFactoryMethod();
if (Modifier.isStatic(method.getModifiers()))
{
// method is static so call it directly
result = method.invoke(null, null);
}
else
{
// method is not static, so create an object of the factory first
// note that this requires a public no-parameter (default) constructor
Object factoryInstance = cld.getFactoryClass().newInstance();
result = method.invoke(factoryInstance, null);
}
}
catch (Exception ex)
{
throw new PersistenceBrokerException("Unable to build object instance of class '"
+ cld.getClassNameOfObject() + "' from factory:" + cld.getFactoryClass()
+ "." + cld.getFactoryMethod(), ex);
}
}
return result;
} | Builds a new instance for the class represented by the given class descriptor.
@param cld The class descriptor
@return The instance |
public InternalTile paint(InternalTile tileToPaint) throws RenderException {
if (tileToPaint != null && null != tileToPaint.getFeatures()) {
tile = tileToPaint;
Collections.sort(tile.getFeatures()); // make sure features are sorted by style, needed for grouping
// Create the SVG / VML feature fragment:
if (paintGeometries && featureDocument == null) {
StringWriter writer = new StringWriter();
try {
featureDocument = createFeatureDocument(writer);
featureDocument.setRootId(layer.getId());
featureDocument.writeObject(tile, false);
featureDocument.flush();
} catch (RenderException e) {
log.error("Unable to write this tile's feature fragment", e);
}
tile.setFeatureContent(writer.toString());
}
// Create the SVG / VML label fragment:
if (paintLabels && labelDocument == null) {
StringWriter writer = new StringWriter();
try {
labelDocument = createLabelDocument(writer, style.getLabelStyle());
labelDocument.setRootId(layer.getId());
labelDocument.writeObject(tileToPaint, false);
labelDocument.flush();
} catch (RenderException e) {
log.error("Unable to write this tile's label fragment", e);
}
tile.setLabelContent(writer.toString());
}
return tile;
}
return tileToPaint;
} | Paint the tile! The tile must be an instance of {@link InternalTile}. This function will create 2 DOM documents
for geometries and labels. In case the renderer says "SVG" these documents will be of the type
{@link org.geomajas.internal.rendering.DefaultSvgDocument}, otherwise
{@link org.geomajas.internal.rendering.DefaultVmlDocument}. These documents in turn are built using
{@link org.geomajas.internal.rendering.writer.GraphicsWriter} classes.
@param tileToPaint
The instance of {@link InternalTile}. Using the DOM documents, the tile's "featureFragment" and
"labelFragment" will be created.
@return Returns a fully rendered vector tile. |
private GraphicsDocument createFeatureDocument(StringWriter writer) throws RenderException {
if (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) {
DefaultSvgDocument document = new DefaultSvgDocument(writer, false);
document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);
document.registerWriter(InternalFeatureImpl.class, new SvgFeatureWriter(getTransformer()));
document.registerWriter(InternalTileImpl.class, new SvgTileWriter());
return document;
} else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) {
DefaultVmlDocument document = new DefaultVmlDocument(writer);
int coordWidth = tile.getScreenWidth();
int coordHeight = tile.getScreenHeight();
document.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth,
coordHeight));
document.registerWriter(InternalTileImpl.class, new VmlTileWriter(coordWidth, coordHeight));
document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);
return document;
} else {
throw new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer);
}
} | Create a document that parses the tile's featureFragment, using GraphicsWriter classes.
@param writer
writer
@return document
@throws RenderException
oops |
private GraphicsDocument createLabelDocument(StringWriter writer, LabelStyleInfo labelStyleInfo)
throws RenderException {
if (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) {
DefaultSvgDocument document = new DefaultSvgDocument(writer, false);
document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);
document.registerWriter(InternalTileImpl.class, new SvgLabelTileWriter(getTransformer(), labelStyleInfo,
geoService, textService));
return document;
} else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) {
DefaultVmlDocument document = new DefaultVmlDocument(writer);
int coordWidth = tile.getScreenWidth();
int coordHeight = tile.getScreenHeight();
document.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth,
coordHeight));
document.registerWriter(InternalTileImpl.class, new VmlLabelTileWriter(coordWidth, coordHeight,
getTransformer(), labelStyleInfo, geoService, textService));
document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);
return document;
} else {
throw new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer);
}
} | Create a document that parses the tile's labelFragment, using GraphicsWriter classes.
@param writer
writer
@param labelStyleInfo
label style info
@return graphics document
@throws RenderException
cannot render |
private GeometryCoordinateSequenceTransformer getTransformer() {
if (unitToPixel == null) {
unitToPixel = new GeometryCoordinateSequenceTransformer();
unitToPixel.setMathTransform(ProjectiveTransform.create(new AffineTransform(scale, 0, 0, -scale, -scale
* panOrigin.x, scale * panOrigin.y)));
}
return unitToPixel;
} | Get transformer to use.
@return transformation to apply |
public void execute(Task task, Database dbModel, DescriptorRepository objModel) throws BuildException
{
if (_outputFile == null)
{
throw new BuildException("No output file specified");
}
if (_outputFile.exists() && !_outputFile.canWrite())
{
throw new BuildException("Cannot overwrite output file "+_outputFile.getAbsolutePath());
}
try
{
FileWriter outputWriter = new FileWriter(_outputFile);
DataDtdWriter dtdWriter = new DataDtdWriter();
DdlUtilsDataHandling handling = new DdlUtilsDataHandling();
handling.setModel(dbModel, objModel);
handling.getDataDTD(outputWriter);
outputWriter.close();
task.log("Written DTD to "+_outputFile.getAbsolutePath(), Project.MSG_INFO);
}
catch (Exception ex)
{
throw new BuildException("Failed to write to output file "+_outputFile.getAbsolutePath(), ex);
}
} | {@inheritDoc} |
@Override
public void execute(GeometryAreaRequest request, GeometryAreaResponse response) throws Exception {
List<Double> areas = new ArrayList<Double>(request.getGeometries().size());
for (org.geomajas.geometry.Geometry g : request.getGeometries()) {
Geometry geometry = converter.toInternal(g);
double area = 0;
if (geometry instanceof Polygonal) {
if (request.getCrs() != null) {
if (!EPSG_4326.equals(request.getCrs())) {
geometry = geoService.transform(geometry, request.getCrs(), EPSG_4326);
}
// applying global sinusoidal projection (equal-area)
geometry.apply(new CoordinateFilter() {
public void filter(Coordinate coord) {
double newX = coord.x * Math.PI / 180.0 * Math.cos(coord.y * Math.PI / 180.0);
double newY = coord.y * Math.PI / 180.0;
coord.x = newX;
coord.y = newY;
}
});
area = geometry.getArea() * RADIUS * RADIUS;
} else {
area = geometry.getArea();
}
}
areas.add(area);
}
response.setAreas(areas);
} | Calculate the geographical area for each of the requested geometries. The current algorithm uses the global
sinusoidal projection (a so-called equal-area projection) and assumes a spherical earth. More accurate
projections exist (Albers, Mollweide, ...) but they are more complicated and cause tolerance problems when
directly applied with Geotools transformations.
@param request request parameters
@param response response object
@throws Exception in case of problems |
private void doExecute(Connection conn) throws SQLException
{
PreparedStatement stmt;
int size;
size = _methods.size();
if ( size == 0 )
{
return;
}
stmt = conn.prepareStatement(_sql);
try
{
m_platform.afterStatementCreate(stmt);
}
catch ( PlatformException e )
{
if ( e.getCause() instanceof SQLException )
{
throw (SQLException)e.getCause();
}
else
{
throw new SQLException(e.getMessage());
}
}
try
{
m_platform.beforeBatch(stmt);
}
catch ( PlatformException e )
{
if ( e.getCause() instanceof SQLException )
{
throw (SQLException)e.getCause();
}
else
{
throw new SQLException(e.getMessage());
}
}
try
{
for ( int i = 0; i < size; i++ )
{
Method method = (Method) _methods.get(i);
try
{
if ( method.equals(ADD_BATCH) )
{
/**
* we invoke on the platform and pass the stmt as an arg.
*/
m_platform.addBatch(stmt);
}
else
{
method.invoke(stmt, (Object[]) _params.get(i));
}
}
catch (IllegalArgumentException ex)
{
StringBuffer buffer = generateExceptionMessage(i, stmt, ex);
throw new SQLException(buffer.toString());
}
catch ( IllegalAccessException ex )
{
StringBuffer buffer = generateExceptionMessage(i, stmt, ex);
throw new SQLException(buffer.toString());
}
catch ( InvocationTargetException ex )
{
Throwable th = ex.getTargetException();
if ( th == null )
{
th = ex;
}
if ( th instanceof SQLException )
{
throw ((SQLException) th);
}
else
{
throw new SQLException(th.toString());
}
}
catch (PlatformException e)
{
throw new SQLException(e.toString());
}
}
try
{
/**
* this will call the platform specific call
*/
m_platform.executeBatch(stmt);
}
catch ( PlatformException e )
{
if ( e.getCause() instanceof SQLException )
{
throw (SQLException)e.getCause();
}
else
{
throw new SQLException(e.getMessage());
}
}
}
finally
{
stmt.close();
_methods.clear();
_params.clear();
}
} | This method performs database modification at the very and of transaction. |
public Object getBeliefValue(String agent_name, final String belief_name,
Connector connector) {
((IExternalAccess) connector.getAgentsExternalAccess(agent_name))
.scheduleStep(new IComponentStep<Integer>() {
public IFuture<Integer> execute(IInternalAccess ia) {
IBDIInternalAccess bia = (IBDIInternalAccess) ia;
belief_value = bia.getBeliefbase()
.getBelief(belief_name).getFact();
return null;
}
}).get(new ThreadSuspendable());
return belief_value;
} | This method takes the value of an agent's belief through its external
access
@param agent_name
The name of the agent
@param belief_name
The name of the belief inside agent's adf
@param connector
The connector to get the external access
@return belief_value The value of the requested belief |
public void setBeliefValue(String agent_name, final String belief_name,
final Object new_value, Connector connector) {
((IExternalAccess) connector.getAgentsExternalAccess(agent_name))
.scheduleStep(new IComponentStep<Integer>() {
public IFuture<Integer> execute(IInternalAccess ia) {
IBDIInternalAccess bia = (IBDIInternalAccess) ia;
bia.getBeliefbase().getBelief(belief_name)
.setFact(new_value);
return null;
}
}).get(new ThreadSuspendable());
} | This method changes the value of an agent's belief through its external
access
@param agent_name
The name of the agent to change a belief
@param belief_name
The name of the belief to change
@param new_value
The new value of the belief to be changed
@param connector
The connector to get the external access |
public IPlan[] getAgentPlans(final String agent_name, Connector connector) {
((IExternalAccess) connector.getAgentsExternalAccess(agent_name))
.scheduleStep(new IComponentStep<Plan>() {
public IFuture<Plan> execute(IInternalAccess ia) {
IBDIInternalAccess bia = (IBDIInternalAccess) ia;
plans = bia.getPlanbase().getPlans();
return null;
}
}).get(new ThreadSuspendable());
return plans;
} | This method prints plan information of an agent through its external
access. It can be used to check the correct behaviour of the agent.
@param agent_name
The name of the agent
@param connector
The connector to get the external access
@return plans the IPlan[] with all the information, so the tester can
look for information |
public IGoal[] getAgentGoals(final String agent_name, Connector connector) {
((IExternalAccess) connector.getAgentsExternalAccess(agent_name))
.scheduleStep(new IComponentStep<Plan>() {
public IFuture<Plan> execute(IInternalAccess ia) {
IBDIInternalAccess bia = (IBDIInternalAccess) ia;
goals = bia.getGoalbase().getGoals();
return null;
}
}).get(new ThreadSuspendable());
return goals;
} | This method prints goal information of an agent through its external
access. It can be used to check the correct behaviour of the agent.
@param agent_name
The name of the agent
@param connector
The connector to get the external access
@return goals the IGoal[] with all the information, so the tester can
look for information |
public Connection getConnection() throws LookupException
{
/*
if the connection is not null and we are not in a local tx, we check
the connection state and release "dead" connections.
if connection is in local tx we do nothing, the dead connection will cause
an exception and PB instance have to handle rollback
*/
if(con != null && !isInLocalTransaction() && !isAlive(con))
{
releaseConnection();
}
if (con == null)
{
con = this.connectionFactory.lookupConnection(jcd);
if (con == null) throw new PersistenceBrokerException("Cannot get connection for " + jcd);
if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE)
{
try
{
this.originalAutoCommitState = con.getAutoCommit();
}
catch (SQLException e)
{
throw new PersistenceBrokerException("Cannot request autoCommit state on the connection", e);
}
}
if (log.isDebugEnabled()) log.debug("Request new connection from ConnectionFactory: " + con);
}
if (isBatchMode())
{
if (batchCon == null)
{
batchCon = new BatchConnection(con, broker);
}
return batchCon;
}
else
{
return con;
}
} | Returns the underlying connection, requested from
{@link org.apache.ojb.broker.accesslayer.ConnectionFactory}.
<p>
PB#beginTransaction() opens a single jdbc connection via
PB#serviceConnectionManager().localBegin().
If you call PB#serviceConnectionManager().getConnection() later
it returns the already opened connection.
The PB instance will release the used connection during
PB#commitTransaction() or PB#abortTransaction() or PB#close().
</p>
<p>
NOTE: Never call Connection.close() on the connection requested from the ConnectionManager.
Cleanup of used connection is done by OJB itself. If you need to release a used connection
call {@link #releaseConnection()}.
</p> |
public void localBegin()
{
if (this.isInLocalTransaction)
{
throw new TransactionInProgressException("Connection is already in transaction");
}
Connection connection = null;
try
{
connection = this.getConnection();
}
catch (LookupException e)
{
/**
* must throw to notify user that we couldn't start a connection
*/
throw new PersistenceBrokerException("Can't lookup a connection", e);
}
if (log.isDebugEnabled()) log.debug("localBegin was called for con " + connection);
// change autoCommit state only if we are not in a managed environment
// and it is enabled by user
if(!broker.isManaged())
{
if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE)
{
if (log.isDebugEnabled()) log.debug("Try to change autoCommit state to 'false'");
platform.changeAutoCommitState(jcd, connection, false);
}
}
else
{
if(log.isDebugEnabled()) log.debug(
"Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call");
}
this.isInLocalTransaction = true;
} | Start transaction on the underlying connection. |
public void localCommit()
{
if (log.isDebugEnabled()) log.debug("commit was called");
if (!this.isInLocalTransaction)
{
throw new TransactionNotInProgressException("Not in transaction, call begin() before commit()");
}
try
{
if(!broker.isManaged())
{
if (batchCon != null)
{
batchCon.commit();
}
else if (con != null)
{
con.commit();
}
}
else
{
if(log.isDebugEnabled()) log.debug(
"Found managed environment setting in PB, will skip Connection.commit() call");
}
}
catch (SQLException e)
{
log.error("Commit on underlying connection failed, try to rollback connection", e);
this.localRollback();
throw new TransactionAbortedException("Commit on connection failed", e);
}
finally
{
this.isInLocalTransaction = false;
restoreAutoCommitState();
this.releaseConnection();
}
} | Call commit on the underlying connection. |
public void localRollback()
{
log.info("Rollback was called, do rollback on current connection " + con);
if (!this.isInLocalTransaction)
{
throw new PersistenceBrokerException("Not in transaction, cannot abort");
}
try
{
//truncate the local transaction
this.isInLocalTransaction = false;
if(!broker.isManaged())
{
if (batchCon != null)
{
batchCon.rollback();
}
else if (con != null && !con.isClosed())
{
con.rollback();
}
}
else
{
if(log.isEnabledFor(Logger.INFO)) log.info(
"Found managed environment setting in PB, will ignore rollback call on connection, this should be done by JTA");
}
}
catch (SQLException e)
{
log.error("Rollback on the underlying connection failed", e);
}
finally
{
try
{
restoreAutoCommitState();
}
catch(OJBRuntimeException ignore)
{
// Ignore or log exception
}
releaseConnection();
}
} | Call rollback on the underlying connection. |
protected void restoreAutoCommitState()
{
try
{
if(!broker.isManaged())
{
if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE
&& originalAutoCommitState == true && con != null && !con.isClosed())
{
platform.changeAutoCommitState(jcd, con, true);
}
}
else
{
if(log.isDebugEnabled()) log.debug(
"Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call");
}
}
catch (SQLException e)
{
// should never be reached
throw new OJBRuntimeException("Restore of connection autocommit state failed", e);
}
} | Reset autoCommit state. |
public boolean isAlive(Connection conn)
{
try
{
return con != null ? !con.isClosed() : false;
}
catch (SQLException e)
{
log.error("IsAlive check failed, running connection was invalid!!", e);
return false;
}
} | Check if underlying connection was alive. |
public void releaseConnection()
{
if (this.con == null)
{
return;
}
if(isInLocalTransaction())
{
log.error("Release connection: connection is in local transaction, missing 'localCommit' or" +
" 'localRollback' call - try to rollback the connection");
localRollback();
}
else
{
this.connectionFactory.releaseConnection(this.jcd, this.con);
this.con = null;
this.batchCon = null;
}
} | Release connection to the {@link org.apache.ojb.broker.accesslayer.ConnectionFactory}, make
sure that you call the method in either case, it's the only way to free the connection. |
public void executeBatch() throws OJBBatchUpdateException
{
if (batchCon != null)
{
try
{
batchCon.executeBatch();
}
catch (Throwable th)
{
throw new OJBBatchUpdateException(th);
}
}
} | Execute batch (if the batch mode where used). |
public void executeBatchIfNecessary() throws OJBBatchUpdateException
{
if (batchCon != null)
{
try
{
batchCon.executeBatchIfNecessary();
}
catch (Throwable th)
{
throw new OJBBatchUpdateException(th);
}
}
} | Execute batch if the number of statements in it
exceeded the limit (if the batch mode where used). |
@Override
public void format(final LoggingEvent event, final StringBuffer toAppendTo) {
String loggerName = event.getLoggerName();
if (loggerName.startsWith("audit.")) {
toAppendTo.append("AUDIT-");
}
} | {@inheritDoc} |
private void initComponents() {//GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jToolBar1 = new javax.swing.JToolBar();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jSplitPane1 = new javax.swing.JSplitPane();
jScrollPane1 = new javax.swing.JScrollPane();
jTree1 = new javax.swing.JTree();
jScrollPane2 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
menuBar = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
mnuFileConnect = new javax.swing.JMenuItem();
mnuFileReadSchema = new javax.swing.JMenuItem();
exitMenuItem = new javax.swing.JMenuItem();
getContentPane().setLayout(new java.awt.GridBagLayout());
setTitle("OJB Scheme Generator");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
jButton1.setAction(new DBConnPropertiesAction(this));
jToolBar1.add(jButton1);
jButton2.setText("Read");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jToolBar1.add(jButton2);
jButton3.setText("Save XML");
jButton3.setAction(new SaveXMLAction(this));
jToolBar1.add(jButton3);
jButton4.setAction(new GenerateJavaClassesAction(this));
jToolBar1.add(jButton4);
jButton5.setAction(new SetPackageAction(this));
jToolBar1.add(jButton5);
jButton6.setAction(new DisableClassesWithRegexAction(this));
jToolBar1.add(jButton6);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
getContentPane().add(jToolBar1, gridBagConstraints);
jSplitPane1.setDividerLocation(100);
jTree1.setModel(null);
jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
jTree1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jTree1);
jSplitPane1.setLeftComponent(jScrollPane1);
jScrollPane2.setViewportView(jPanel1);
jSplitPane1.setRightComponent(jScrollPane2);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(jSplitPane1, gridBagConstraints);
fileMenu.setText("File");
fileMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileMenuActionPerformed(evt);
}
});
mnuFileConnect.setAction(new DBConnPropertiesAction(this));
mnuFileConnect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mnuFileConnectActionPerformed(evt);
}
});
fileMenu.add(mnuFileConnect);
mnuFileReadSchema.setText("Read Schema");
mnuFileReadSchema.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mnuFileReadSchemaActionPerformed(evt);
}
});
fileMenu.add(mnuFileReadSchema);
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMenuItemActionPerformed(evt);
}
});
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
pack();
} | This method is called from within the constructor to
initialize the form.
WARNING: Do NOT modify this code. The content of this method is
always regenerated by the Form Editor. |
private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt)//GEN-FIRST:event_jTree1ValueChanged
{//GEN-HEADEREND:event_jTree1ValueChanged
javax.swing.tree.TreePath tp = evt.getPath();
if (tp != null)
{
Object o = tp.getLastPathComponent();
if (o instanceof PropertySheetModel)
{
PropertySheetModel p = (PropertySheetModel) o;
PropertySheetView pv =
(PropertySheetView)hmPropertySheets.get(p.getPropertySheetClass());
if (pv == null)
{
try
{
pv = (PropertySheetView)p.getPropertySheetClass().newInstance();
}
catch (InstantiationException ie)
{
// What to do here?????
ie.printStackTrace();
}
catch (IllegalAccessException iae)
{
iae.printStackTrace();
}
}
pv.setModel(p);
this.jScrollPane2.setViewportView((java.awt.Component)pv);
}
}
} | GEN-END:initComponents |
private void initComponents()//GEN-BEGIN:initComponents
{
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
lblEnabled = new javax.swing.JLabel();
cbEnabled = new javax.swing.JCheckBox();
lblDisabledByParent = new javax.swing.JLabel();
cbDisabledByParent = new javax.swing.JCheckBox();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
lblTableName = new javax.swing.JLabel();
tfTableName = new javax.swing.JTextField();
lblClassName = new javax.swing.JLabel();
tfClassName = new javax.swing.JTextField();
lblPackageName = new javax.swing.JLabel();
tfPackageName = new javax.swing.JTextField();
lblDynamicProxy = new javax.swing.JLabel();
cbDynamicProxy = new javax.swing.JCheckBox();
lblConversionStrategyClass = new javax.swing.JLabel();
tfConversionStrategyClass = new javax.swing.JTextField();
setLayout(new java.awt.GridBagLayout());
addComponentListener(new java.awt.event.ComponentAdapter()
{
public void componentShown(java.awt.event.ComponentEvent evt)
{
formComponentShown(evt);
}
public void componentHidden(java.awt.event.ComponentEvent evt)
{
formComponentHidden(evt);
}
});
addHierarchyListener(new java.awt.event.HierarchyListener()
{
public void hierarchyChanged(java.awt.event.HierarchyEvent evt)
{
formHierarchyChanged(evt);
}
});
jPanel1.setLayout(new java.awt.GridLayout(8, 2));
lblEnabled.setDisplayedMnemonic('e');
lblEnabled.setText("enabled");
jPanel1.add(lblEnabled);
cbEnabled.setMnemonic('e');
cbEnabled.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
cbEnabledActionPerformed(evt);
}
});
jPanel1.add(cbEnabled);
lblDisabledByParent.setText("disabled by Parent:");
jPanel1.add(lblDisabledByParent);
cbDisabledByParent.setEnabled(false);
jPanel1.add(cbDisabledByParent);
jPanel1.add(jLabel3);
jPanel1.add(jLabel4);
lblTableName.setLabelFor(tfTableName);
lblTableName.setText("Table Name:");
jPanel1.add(lblTableName);
tfTableName.setEditable(false);
tfTableName.setText("jTextField1");
tfTableName.setBorder(null);
tfTableName.setDisabledTextColor(new java.awt.Color(0, 51, 51));
tfTableName.setEnabled(false);
jPanel1.add(tfTableName);
lblClassName.setDisplayedMnemonic('c');
lblClassName.setLabelFor(tfClassName);
lblClassName.setText("Class Name:");
jPanel1.add(lblClassName);
tfClassName.setText("jTextField1");
tfClassName.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
tfClassNameActionPerformed(evt);
}
});
tfClassName.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusLost(java.awt.event.FocusEvent evt)
{
tfClassNameFocusLost(evt);
}
});
tfClassName.addKeyListener(new java.awt.event.KeyAdapter()
{
public void keyTyped(java.awt.event.KeyEvent evt)
{
tfClassNameKeyTyped(evt);
}
});
jPanel1.add(tfClassName);
lblPackageName.setDisplayedMnemonic('p');
lblPackageName.setLabelFor(tfPackageName);
lblPackageName.setText("Package:");
jPanel1.add(lblPackageName);
tfPackageName.setText("jTextField2");
tfPackageName.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
tfPackageNameActionPerformed(evt);
}
});
tfPackageName.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusLost(java.awt.event.FocusEvent evt)
{
tfPackageNameFocusLost(evt);
}
});
tfPackageName.addKeyListener(new java.awt.event.KeyAdapter()
{
public void keyTyped(java.awt.event.KeyEvent evt)
{
tfPackageNameKeyTyped(evt);
}
});
jPanel1.add(tfPackageName);
lblDynamicProxy.setDisplayedMnemonic('u');
lblDynamicProxy.setText("Use Dynamic Proxy:");
jPanel1.add(lblDynamicProxy);
cbDynamicProxy.setMnemonic('u');
cbDynamicProxy.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
cbDynamicProxyActionPerformed(evt);
}
});
jPanel1.add(cbDynamicProxy);
lblConversionStrategyClass.setDisplayedMnemonic('s');
lblConversionStrategyClass.setLabelFor(tfConversionStrategyClass);
lblConversionStrategyClass.setText("Conversion Strategy Class:");
jPanel1.add(lblConversionStrategyClass);
tfConversionStrategyClass.setText("jTextField1");
tfConversionStrategyClass.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
tfConversionStrategyClassActionPerformed(evt);
}
});
tfConversionStrategyClass.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusLost(java.awt.event.FocusEvent evt)
{
tfConversionStrategyClassFocusLost(evt);
}
});
tfConversionStrategyClass.addKeyListener(new java.awt.event.KeyAdapter()
{
public void keyTyped(java.awt.event.KeyEvent evt)
{
tfConversionStrategyClassKeyTyped(evt);
}
});
jPanel1.add(tfConversionStrategyClass);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
} | This method is called from within the constructor to
initialize the form.
WARNING: Do NOT modify this code. The content of this method is
always regenerated by the Form Editor. |
private void tfConversionStrategyClassKeyTyped(java.awt.event.KeyEvent evt)//GEN-FIRST:event_tfConversionStrategyClassKeyTyped
{//GEN-HEADEREND:event_tfConversionStrategyClassKeyTyped
// Revert on ESC
if (evt.getKeyChar() == KeyEvent.VK_ESCAPE)
{
this.tfConversionStrategyClass.setText(aTable.getConversionStrategyClass());
}
} | GEN-END:initComponents |
private void tfConversionStrategyClassFocusLost(java.awt.event.FocusEvent evt)//GEN-FIRST:event_tfConversionStrategyClassFocusLost
{//GEN-HEADEREND:event_tfConversionStrategyClassFocusLost
// Commit on lost focus
aTable.setConversionStrategyClass(this.tfConversionStrategyClass.getText());
} | GEN-LAST:event_tfConversionStrategyClassKeyTyped |
private void tfConversionStrategyClassActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_tfConversionStrategyClassActionPerformed
{//GEN-HEADEREND:event_tfConversionStrategyClassActionPerformed
// Commit on ENTER
aTable.setConversionStrategyClass(this.tfConversionStrategyClass.getText());
} | GEN-LAST:event_tfConversionStrategyClassFocusLost |
private void tfPackageNameKeyTyped(java.awt.event.KeyEvent evt)//GEN-FIRST:event_tfPackageNameKeyTyped
{//GEN-HEADEREND:event_tfPackageNameKeyTyped
// Revert on ESC
if (evt.getKeyChar() == KeyEvent.VK_ESCAPE)
{
this.tfPackageName.setText(aTable.getPackageName());
}
} | GEN-LAST:event_tfConversionStrategyClassActionPerformed |
private void tfPackageNameFocusLost(java.awt.event.FocusEvent evt)//GEN-FIRST:event_tfPackageNameFocusLost
{//GEN-HEADEREND:event_tfPackageNameFocusLost
// Commit on lost focus
aTable.setPackageName(tfPackageName.getText());
} | GEN-LAST:event_tfPackageNameKeyTyped |
private void tfPackageNameActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_tfPackageNameActionPerformed
{//GEN-HEADEREND:event_tfPackageNameActionPerformed
// Commit on ENTER
aTable.setPackageName(tfPackageName.getText());
} | GEN-LAST:event_tfPackageNameFocusLost |
private void tfClassNameKeyTyped(java.awt.event.KeyEvent evt)//GEN-FIRST:event_tfClassNameKeyTyped
{//GEN-HEADEREND:event_tfClassNameKeyTyped
// Revert on ESC
if (evt.getKeyChar() == KeyEvent.VK_ESCAPE)
{
this.tfClassName.setText(aTable.getClassName());
}
} | GEN-LAST:event_tfPackageNameActionPerformed |
private void tfClassNameFocusLost(java.awt.event.FocusEvent evt)//GEN-FIRST:event_tfClassNameFocusLost
{//GEN-HEADEREND:event_tfClassNameFocusLost
// Commit on lost focus
aTable.setClassName(tfClassName.getText());
} | GEN-LAST:event_tfClassNameKeyTyped |
private void tfClassNameActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_tfClassNameActionPerformed
{//GEN-HEADEREND:event_tfClassNameActionPerformed
// Commit on ENTER
aTable.setClassName(tfClassName.getText());
} | GEN-LAST:event_tfClassNameFocusLost |
private void cbDynamicProxyActionPerformed (java.awt.event.ActionEvent evt)//GEN-FIRST:event_cbDynamicProxyActionPerformed
{//GEN-HEADEREND:event_cbDynamicProxyActionPerformed
// Add your handling code here:
aTable.setDynamicProxy(this.cbDynamicProxy.isSelected());
} | GEN-LAST:event_tfClassNameActionPerformed |
private void cbEnabledActionPerformed (java.awt.event.ActionEvent evt)//GEN-FIRST:event_cbEnabledActionPerformed
{//GEN-HEADEREND:event_cbEnabledActionPerformed
// Add your handling code here:
this.aTable.setEnabled(this.cbEnabled.isSelected());
} | GEN-LAST:event_cbDynamicProxyActionPerformed |
public void setModel (PropertySheetModel pm)
{
if (pm instanceof org.apache.ojb.tools.mapping.reversedb.DBTable)
{
this.aTable = (org.apache.ojb.tools.mapping.reversedb.DBTable)pm;
this.readValuesFromTable();
}
else
throw new IllegalArgumentException();
} | GEN-LAST:event_formComponentShown |
public static void registerAgent(Agent agent, String serviceName, String serviceType) throws FIPAException{
DFAgentDescription dfd = new DFAgentDescription();
ServiceDescription sd = new ServiceDescription();
sd.setType(serviceType);
sd.setName(serviceName);
//NOTE El serviceType es un string que define el tipo de servicio publicado en el DF por el Agente X.
// He escogido crear nombres en clave en jade.common.Definitions para este campo.
//NOTE El serviceName es el nombre efectivo del servicio.
// Esto es lo que el usuario va a definir en MockConfiguration.DFNameService y no el tipo como estaba puesto.
// sd.setType(agentType);
// sd.setName(agent.getLocalName());
//Add services??
// Sets the agent description
dfd.setName(agent.getAID());
dfd.addServices(sd);
// Register the agent
DFService.register(agent, dfd);
} | Register the agent in the platform
@param agent_name
The name of the agent to be registered
@param agent
The agent to register.
@throws FIPAException |
File appendSheet(final List<WorksheetContent> worksheetContents) throws IOException {
final ImmutableSet<String> worksheetNames = FluentIterable.from(worksheetContents)
.transform(new Function<WorksheetContent, String>() {
@Nullable @Override public String apply(@Nullable final WorksheetContent worksheetContent) {
return worksheetContent.getSpec().getSheetName();
}
}).toSet();
if(worksheetNames.size() < worksheetContents.size()) {
throw new IllegalArgumentException("Sheet names must have distinct names");
}
for (final String worksheetName : worksheetNames) {
if(worksheetName.length() > 30) {
throw new IllegalArgumentException(
String.format("Sheet name cannot exceed 30 characters (invalid name: '%s')",
worksheetName));
}
}
final XSSFWorkbook workbook = new XSSFWorkbook();
final File tempFile =
File.createTempFile(ExcelConverter.class.getName(), UUID.randomUUID().toString() + XLSX_SUFFIX);
final FileOutputStream fos = new FileOutputStream(tempFile);
for (WorksheetContent worksheetContent : worksheetContents) {
final WorksheetSpec spec = worksheetContent.getSpec();
appendSheet(workbook, worksheetContent.getDomainObjects(), spec.getFactory(), spec.getSheetName());
}
workbook.write(fos);
fos.close();
return tempFile;
} | ////////////////////////////////////// |
protected CellMarshaller newCellMarshaller(final Workbook wb) {
final CellStyle dateCellStyle = createDateFormatCellStyle(wb);
final CellMarshaller cellMarshaller = new CellMarshaller(bookmarkService, dateCellStyle);
return cellMarshaller;
} | ////////////////////////////////////// |
public static InterceptorFactory getInstance()
{
if (instance == null)
{
instance = new InterceptorFactory();
OjbConfigurator.getInstance().configure(instance);
}
return instance;
} | Returns the instance.
@return InterceptorFactory |
@Programmatic
public ExcelModuleDemoToDoItem findByDescription(final String description) {
return container.firstMatch(
new QueryDefault<>(ExcelModuleDemoToDoItem.class,
"findByDescription",
"description", description,
"ownedBy", currentUserName()));
} | ////////////////////////////////////// |
public void registerDropPasteWorker(DropPasteWorkerInterface worker)
{
this.dropPasteWorkerSet.add(worker);
defaultDropTarget.setDefaultActions(
defaultDropTarget.getDefaultActions()
| worker.getAcceptableActions(defaultDropTarget.getComponent())
);
} | Register a new DropPasteWorkerInterface.
@param worker The new worker |
public void removeDropPasteWorker(DropPasteWorkerInterface worker)
{
this.dropPasteWorkerSet.remove(worker);
java.util.Iterator it = this.dropPasteWorkerSet.iterator();
int newDefaultActions = 0;
while (it.hasNext())
newDefaultActions |= ((DropPasteWorkerInterface)it.next()).getAcceptableActions(defaultDropTarget.getComponent());
defaultDropTarget.setDefaultActions(newDefaultActions);
} | Remove a DropPasteWorker from the helper.
@param worker the worker that should be removed |
public static String serialize(final Object obj) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
return mapper.writeValueAsString(obj);
} | Serialize an object with Json
@param obj Object
@return String
@throws IOException |
public static Organization unserializeOrganization(final String organization) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
return mapper.readValue(organization, Organization.class);
} | Un-serialize a Json into Organization
@param organization String
@return Organization
@throws IOException |
public static Module unserializeModule(final String module) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
return mapper.readValue(module, Module.class);
} | Un-serialize a Json into Module
@param module String
@return Module
@throws IOException |
public static Map<String,String> unserializeBuildInfo(final String buildInfo) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
return mapper.readValue(buildInfo, new TypeReference<Map<String, Object>>(){});
} | Un-serialize a Json into BuildInfo
@param buildInfo String
@return Map<String,String>
@throws IOException |
public static Artifact unserializeArtifact(final String artifact) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
return mapper.readValue(artifact, Artifact.class);
} | Un-serialize a report with Json
@param artifact String
@return Artifact
@throws IOException |
public static License unserializeLicense(final String license) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
return mapper.readValue(license, License.class);
} | Un-serialize a report with Json
@param license String
@return License
@throws IOException |
public Object get(String name, ObjectFactory<?> factory) {
ThreadScopeContext context = ThreadScopeContextHolder.getContext();
Object result = context.getBean(name);
if (null == result) {
result = factory.getObject();
context.setBean(name, result);
}
return result;
} | Get bean for given name in the "thread" scope.
@param name name of bean
@param factory factory for new instances
@return bean for this scope |
public Object remove(String name) {
ThreadScopeContext context = ThreadScopeContextHolder.getContext();
return context.remove(name);
} | Removes bean from scope.
@param name bean name
@return previous value |
public static void addItemsHandled(String handledItemsType, int handledItemsNumber) {
JobLogger jobLogger = (JobLogger) getInstance();
if (jobLogger == null) {
return;
}
jobLogger.addItemsHandledInstance(handledItemsType, handledItemsNumber);
} | Number of failed actions in scheduler |
public void releaseAllResources()
{
super.releaseAllResources();
synchronized (poolSynch)
{
if (!poolMap.isEmpty())
{
Collection pools = poolMap.values();
Iterator iterator = pools.iterator();
ObjectPool op = null;
while (iterator.hasNext())
{
try
{
op = (ObjectPool) iterator.next();
op.close();
}
catch (Exception e)
{
log.error("Exception occured while closing ObjectPool " + op, e);
}
}
poolMap.clear();
}
dsMap.clear();
}
} | Closes all managed pools. |
protected DataSource getDataSource(JdbcConnectionDescriptor jcd)
throws LookupException
{
final PBKey key = jcd.getPBKey();
DataSource ds = (DataSource) dsMap.get(key);
if (ds == null)
{
// Found no pool for PBKey
try
{
synchronized (poolSynch)
{
// Setup new object pool
ObjectPool pool = setupPool(jcd);
poolMap.put(key, pool);
// Wrap the underlying object pool as DataSource
ds = wrapAsDataSource(jcd, pool);
dsMap.put(key, ds);
}
}
catch (Exception e)
{
log.error("Could not setup DBCP DataSource for " + jcd, e);
throw new LookupException(e);
}
}
return ds;
} | Returns the DBCP DataSource for the specified connection descriptor,
after creating a new DataSource if needed.
@param jcd the descriptor for which to return a DataSource
@return a DataSource, after creating a new pool if needed.
Guaranteed to never be null.
@throws LookupException if pool is not in cache and cannot be created |
protected ObjectPool setupPool(JdbcConnectionDescriptor jcd)
{
log.info("Create new ObjectPool for DBCP connections:" + jcd);
try
{
ClassHelper.newInstance(jcd.getDriver());
}
catch (InstantiationException e)
{
log.fatal("Unable to instantiate the driver class: " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e);
}
catch (IllegalAccessException e)
{
log.fatal("IllegalAccessException while instantiating the driver class: " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e);
}
catch (ClassNotFoundException e)
{
log.fatal("Could not find the driver class : " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e);
}
// Get the configuration for the connection pool
GenericObjectPool.Config conf = jcd.getConnectionPoolDescriptor().getObjectPoolConfig();
// Get the additional abandoned configuration
AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig();
// Create the ObjectPool that serves as the actual pool of connections.
final ObjectPool connectionPool = createConnectionPool(conf, ac);
// Create a DriverManager-based ConnectionFactory that
// the connectionPool will use to create Connection instances
final org.apache.commons.dbcp.ConnectionFactory connectionFactory;
connectionFactory = createConnectionFactory(jcd);
// Create PreparedStatement object pool (if any)
KeyedObjectPoolFactory statementPoolFactory = createStatementPoolFactory(jcd);
// Set validation query and auto-commit mode
final String validationQuery;
final boolean defaultAutoCommit;
final boolean defaultReadOnly = false;
validationQuery = jcd.getConnectionPoolDescriptor().getValidationQuery();
defaultAutoCommit = (jcd.getUseAutoCommit() != JdbcConnectionDescriptor.AUTO_COMMIT_SET_FALSE);
//
// Now we'll create the PoolableConnectionFactory, which wraps
// the "real" Connections created by the ConnectionFactory with
// the classes that implement the pooling functionality.
//
final PoolableConnectionFactory poolableConnectionFactory;
poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
connectionPool,
statementPoolFactory,
validationQuery,
defaultReadOnly,
defaultAutoCommit,
ac);
return poolableConnectionFactory.getPool();
} | Returns a new ObjectPool for the specified connection descriptor.
Override this method to setup your own pool.
@param jcd the connection descriptor for which to set up the pool
@return a newly created object pool |
protected DataSource wrapAsDataSource(JdbcConnectionDescriptor jcd,
ObjectPool connectionPool)
{
final boolean allowConnectionUnwrap;
if (jcd == null)
{
allowConnectionUnwrap = false;
}
else
{
final Properties properties = jcd.getConnectionPoolDescriptor().getDbcpProperties();
final String allowConnectionUnwrapParam;
allowConnectionUnwrapParam = properties.getProperty(PARAM_NAME_UNWRAP_ALLOWED);
allowConnectionUnwrap = allowConnectionUnwrapParam != null &&
Boolean.valueOf(allowConnectionUnwrapParam).booleanValue();
}
final PoolingDataSource dataSource;
dataSource = new PoolingDataSource(connectionPool);
dataSource.setAccessToUnderlyingConnectionAllowed(allowConnectionUnwrap);
if(jcd != null)
{
final AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig();
if (ac.getRemoveAbandoned() && ac.getLogAbandoned()) {
final LoggerWrapperPrintWriter loggerPiggyBack;
loggerPiggyBack = new LoggerWrapperPrintWriter(log, Logger.ERROR);
dataSource.setLogWriter(loggerPiggyBack);
}
}
return dataSource;
} | Wraps the specified object pool for connections as a DataSource.
@param jcd the OJB connection descriptor for the pool to be wrapped
@param connectionPool the connection pool to be wrapped
@return a DataSource attached to the connection pool.
Connections will be wrapped using DBCP PoolGuard, that will not allow
unwrapping unless the "accessToUnderlyingConnectionAllowed=true" configuration
is specified. |
protected org.apache.commons.dbcp.ConnectionFactory createConnectionFactory(JdbcConnectionDescriptor jcd)
{
final ConPoolFactory result;
final Properties properties = getJdbcProperties(jcd);
result = new ConPoolFactory(jcd, properties);
return result;
} | Creates a DriverManager-based ConnectionFactory for creating the Connection
instances to feed into the object pool of the specified jcd-alias.
<p>
<b>NB!</b> If you override this method to specify your own ConnectionFactory
you <em>must</em> make sure that you follow OJB's lifecycle contract defined in the
{@link org.apache.ojb.broker.platforms.Platform} API - ie that you call
initializeJdbcConnection when a new Connection is created. For convenience, use
{@link ConnectionFactoryAbstractImpl#initializeJdbcConnection} instead of Platform call.
<p>
The above is automatically true if you re-use the inner class {@link ConPoolFactory}
below and just override this method for additional user-defined "tweaks".
@param jcd the jdbc-connection-alias for which we are creating a ConnectionFactory
@return a DriverManager-based ConnectionFactory that creates Connection instances
using DriverManager, and that follows the lifecycle contract defined in OJB
{@link org.apache.ojb.broker.platforms.Platform} API. |
public static Platform getPlatformFor(JdbcConnectionDescriptor jcd)
{
String dbms = jcd.getDbms();
Platform result = null;
String platformName = null;
result = (Platform) getPlatforms().get(dbms);
if (result == null)
{
try
{
platformName = getClassnameFor(dbms);
Class platformClass = ClassHelper.getClass(platformName);
result = (Platform) platformClass.newInstance();
}
catch (Throwable t)
{
LoggerFactory.getDefaultLogger().warn(
"[PlatformFactory] problems with platform " + platformName, t);
LoggerFactory.getDefaultLogger().warn(
"[PlatformFactory] OJB will use PlatformDefaultImpl instead");
result = new PlatformDefaultImpl();
}
getPlatforms().put(dbms, result); // cache the Platform
}
return result;
} | returns the Platform matching to the JdbcConnectionDescriptor jcd.
The method jcd.getDbms(...) is used to determine the Name of the
platform.
BRJ : cache platforms
@param jcd the JdbcConnectionDescriptor defining the platform |
private static String getClassnameFor(String platform)
{
String pf = "Default";
if (platform != null)
{
pf = platform;
}
return "org.apache.ojb.broker.platforms.Platform" + pf.substring(0, 1).toUpperCase() + pf.substring(1) + "Impl";
} | compute the name of the concrete Class representing the Platform
specified by <code>platform</code>
@param platform the name of the platform as specified in the repository |
public void setAlias(String alias)
{
m_alias = alias;
String attributePath = (String)getAttribute();
boolean allPathsAliased = true;
m_userAlias = new UserAlias(alias, attributePath, allPathsAliased);
} | Sets the alias. By default the entire attribute path participates in the alias
@param alias The name of the alias to set |
public void setAlias(String alias, String aliasPath)
{
m_alias = alias;
m_userAlias = new UserAlias(alias, (String)getAttribute(), aliasPath);
} | Sets the alias.
@param alias The alias to set |
public Table getTable(){
final Table table = new Table("Name", "Long Name", "URL", "Comment");
// Create row(s) per dependency
for(final License license: licenses){
table.addRow(license.getName(), license.getLongName(), license.getUrl(), license.getComments());
}
return table;
} | Generate a table that contains the dependencies information with the column that match the configured filters
@return Table |
final void begin() {
if (this.properties.isDateRollEnforced()) {
final Thread thread = new Thread(this,
"Log4J Time-based File-roll Enforcer");
thread.setDaemon(true);
thread.start();
this.threadRef = thread;
}
} | Starts the enforcer. |
public Map<String, ClientWidgetInfo> securityClone(Map<String, ClientWidgetInfo> widgetInfo) {
Map<String, ClientWidgetInfo> res = new HashMap<String, ClientWidgetInfo>();
for (Map.Entry<String, ClientWidgetInfo> entry : widgetInfo.entrySet()) {
ClientWidgetInfo value = entry.getValue();
if (!(value instanceof ServerSideOnlyInfo)) {
res.put(entry.getKey(), value);
}
}
return res;
} | Clone a widget info map considering what may be copied to the client.
@param widgetInfo widget info map
@return cloned copy including only records which are not {@link ServerSideOnlyInfo} |
public Map<String, LayerExtraInfo> securityCloneLayerExtraInfo(Map<String, LayerExtraInfo> extraInfoMap) {
Map<String, LayerExtraInfo> res = new HashMap<String, LayerExtraInfo>();
for (Map.Entry<String, LayerExtraInfo> entry : extraInfoMap.entrySet()) {
LayerExtraInfo value = entry.getValue();
if (!(value instanceof ServerSideOnlyInfo)) {
res.put(entry.getKey(), value);
}
}
return res;
} | Clone a {@link org.geomajas.configuration.LayerInfo#extraInfo} considering what may be copied to the client.
@param extraInfoMap map of extra info
@return cloned copy including only records which are not {@link ServerSideOnlyInfo} |
public ClientLayerInfo securityClone(ClientLayerInfo original) {
// the data is explicitly copied as this assures the security is considered when copying.
if (null == original) {
return null;
}
ClientLayerInfo client = null;
String layerId = original.getServerLayerId();
if (securityContext.isLayerVisible(layerId)) {
client = (ClientLayerInfo) SerializationUtils.clone(original);
client.setWidgetInfo(securityClone(original.getWidgetInfo()));
client.getLayerInfo().setExtraInfo(securityCloneLayerExtraInfo(original.getLayerInfo().getExtraInfo()));
if (client instanceof ClientVectorLayerInfo) {
ClientVectorLayerInfo vectorLayer = (ClientVectorLayerInfo) client;
// set statuses
vectorLayer.setCreatable(securityContext.isLayerCreateAuthorized(layerId));
vectorLayer.setUpdatable(securityContext.isLayerUpdateAuthorized(layerId));
vectorLayer.setDeletable(securityContext.isLayerDeleteAuthorized(layerId));
// filter feature info
FeatureInfo featureInfo = vectorLayer.getFeatureInfo();
List<AttributeInfo> originalAttr = featureInfo.getAttributes();
List<AttributeInfo> filteredAttr = new ArrayList<AttributeInfo>();
featureInfo.setAttributes(filteredAttr);
for (AttributeInfo ai : originalAttr) {
if (securityContext.isAttributeReadable(layerId, null, ai.getName())) {
filteredAttr.add(ai);
}
}
}
}
return client;
} | Clone layer information considering what may be copied to the client.
@param original layer info
@return cloned copy including only allowed information |
public String getKeyValue(String key){
String keyName = keysMap.get(key);
if (keyName != null){
return keyName;
}
return ""; //key wasn't defined in keys properties file
} | get the key name to use in log from the logging keys map |
public static void start(final Logger logger, final Logger auditor, final HttpServletRequest request) {
start(logger, auditor, request, null);
} | ********* Public methods ********* |
protected void startInstance(final HttpServletRequest request, final String requestBody) {
try {
addPropertiesStart(request, requestBody);
writePropertiesToLog(this.logger, Level.DEBUG);
} catch (Exception e) {
logger.error("Failed logging HTTP transaction start: " + e.getMessage(), e);
}
} | ********* Private methods ********* |
public static void serialize(final File folder, final String content, final String fileName) throws IOException {
if (!folder.exists()) {
folder.mkdirs();
}
final File output = new File(folder, fileName);
try (
final FileWriter writer = new FileWriter(output);
) {
writer.write(content);
writer.flush();
} catch (Exception e) {
throw new IOException("Failed to serialize the notification in folder " + folder.getPath(), e);
}
} | Serialize a content into a targeted file, checking that the parent directory exists.
@param folder File
@param content String
@param fileName String |
public static String read(final File file) throws IOException {
final StringBuilder sb = new StringBuilder();
try (
final FileReader fr = new FileReader(file);
final BufferedReader br = new BufferedReader(fr);
) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
}
return sb.toString();
} | Reads a file and returns the result in a String
@param file File
@return String
@throws IOException |
public static Long getSize(final File file){
if ( file!=null && file.exists() ){
return file.length();
}
return null;
} | Get file size
@return Long |
public static void touch(final File folder , final String fileName) throws IOException {
if(!folder.exists()){
folder.mkdirs();
}
final File touchedFile = new File(folder, fileName);
// The JVM will only 'touch' the file if you instantiate a
// FileOutputStream instance for the file in question.
// You don't actually write any data to the file through
// the FileOutputStream. Just instantiate it and close it.
try (
FileOutputStream doneFOS = new FileOutputStream(touchedFile);
) {
// Touching the file
}
catch (FileNotFoundException e) {
throw new FileNotFoundException("Failed to the find file." + e);
}
} | Creates a file
@param folder File
@param fileName String
@throws IOException |
@Override
public Attribute getAttribute(Object feature, String name) throws LayerException {
return convertAttribute(asFeature(feature).getAttribute(name), name);
} | FeatureModel implementation: |
private void init(final List<DbLicense> licenses) {
licensesRegexp.clear();
for (final DbLicense license : licenses) {
if (license.getRegexp() == null ||
license.getRegexp().isEmpty()) {
licensesRegexp.put(license.getName(), license);
} else {
licensesRegexp.put(license.getRegexp(), license);
}
}
} | Init the licenses cache
@param licenses |
public DbLicense getLicense(final String name) {
final DbLicense license = repoHandler.getLicense(name);
if (license == null) {
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.entity("License " + name + " does not exist.").build());
}
return license;
} | Return a html view that contains the targeted license
@param name String
@return DbLicense |
public void deleteLicense(final String licName) {
final DbLicense dbLicense = getLicense(licName);
repoHandler.deleteLicense(dbLicense.getName());
final FiltersHolder filters = new FiltersHolder();
final LicenseIdFilter licenseIdFilter = new LicenseIdFilter(licName);
filters.addFilter(licenseIdFilter);
for (final DbArtifact artifact : repoHandler.getArtifacts(filters)) {
repoHandler.removeLicenseFromArtifact(artifact, licName, this);
}
} | Delete a license from the repository
@param licName The name of the license to remove |
public void approveLicense(final String name, final Boolean approved) {
final DbLicense license = getLicense(name);
repoHandler.approveLicense(license, approved);
} | Approve or reject a license
@param name String
@param approved Boolean |
public DbLicense resolve(final String licenseId) {
for (final Entry<String, DbLicense> regexp : licensesRegexp.entrySet()) {
try {
if (licenseId.matches(regexp.getKey())) {
return regexp.getValue();
}
} catch (PatternSyntaxException e) {
LOG.error("Wrong pattern for the following license " + regexp.getValue().getName(), e);
continue;
}
}
if(LOG.isWarnEnabled()) {
LOG.warn(String.format("No matching pattern for license %s", licenseId));
}
return null;
} | Resolve the targeted license thanks to the license ID
Return null if no license is matching the licenseId
@param licenseId
@return DbLicense |
public List<License> getLicenses() {
final ModelMapper modelMapper = new ModelMapper(repoHandler);
final List<License> licenses = new ArrayList<>();
for (final DbLicense dbLicense : licensesRegexp.values()) {
licenses.add(modelMapper.getLicense(dbLicense));
}
return licenses;
} | Returns all the available license in client/server data model
@return List<License> |
public Set<DbLicense> resolveLicenses(List<String> licStrings) {
Set<DbLicense> result = new HashSet<>();
licStrings
.stream()
.map(this::getMatchingLicenses)
.forEach(result::addAll);
return result;
} | Turns a series of strings into their corresponding license entities
by using regular expressions
@param licStrings The list of license strings
@return A set of license entities |
private void verityLicenseIsConflictFree(final DbLicense newComer) {
if(newComer.getRegexp() == null || newComer.getRegexp().isEmpty()) {
return;
}
final DbLicense existing = repoHandler.getLicense(newComer.getName());
final List<DbLicense> licenses = repoHandler.getAllLicenses();
if(null == existing) {
licenses.add(newComer);
} else {
existing.setRegexp(newComer.getRegexp());
}
final Optional<Report> reportOp = ReportsRegistry.findById(MULTIPLE_LICENSE_MATCHING_STRINGS);
if (reportOp.isPresent()) {
final Report reportDef = reportOp.get();
ReportRequest reportRequest = new ReportRequest();
reportRequest.setReportId(reportDef.getId());
Map<String, String> params = new HashMap<>();
//
// TODO: Make the organization come as an external parameter from the client side.
// This may have impact on the UI, as when the user will update a license he will
// have to specify which organization he's editing the license for (in case there
// are more organizations defined in the collection).
//
params.put("organization", "Axway");
reportRequest.setParamValues(params);
final RepositoryHandler wrapped = wrapperBuilder
.start(repoHandler)
.replaceGetMethod("getAllLicenses", licenses)
.build();
final ReportExecution execution = reportDef.execute(wrapped, reportRequest);
List<String[]> data = execution.getData();
final Optional<String[]> first = data
.stream()
.filter(strings -> strings[2].contains(newComer.getName()))
.findFirst();
if(first.isPresent()) {
final String[] strings = first.get();
final String message = String.format(
"Pattern conflict for string entry %s matching multiple licenses: %s",
strings[1], strings[2]);
LOG.info(message);
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity(message)
.build());
} else {
if(!data.isEmpty() && !data.get(0)[2].isEmpty()) {
LOG.info("There are remote conflicts between existing licenses and artifact strings");
}
}
} else {
if(LOG.isWarnEnabled()) {
LOG.warn(String.format("Cannot find report by id %s", MULTIPLE_LICENSE_MATCHING_STRINGS));
}
}
} | Check if new license pattern is valid and doesn't match any existing one
@param newComer License being added or edited
@throws WebApplicationException if conflicts involving the newComer are detected |
public List<Dependency> getModuleDependencies(final String moduleId, final FiltersHolder filters){
final DbModule module = moduleHandler.getModule(moduleId);
final DbOrganization organization = moduleHandler.getOrganization(module);
filters.setCorporateFilter(new CorporateFilter(organization));
return getModuleDependencies(module, filters, 1, new ArrayList<String>());
} | Returns the list of module dependencies regarding the provided filters
@param moduleId String
@param filters FiltersHolder
@return List<Dependency> |
public DependencyReport getDependencyReport(final String moduleId, final FiltersHolder filters) {
final DbModule module = moduleHandler.getModule(moduleId);
final DbOrganization organization = moduleHandler.getOrganization(module);
filters.setCorporateFilter(new CorporateFilter(organization));
final DependencyReport report = new DependencyReport(moduleId);
final List<String> done = new ArrayList<String>();
for(final DbModule submodule: DataUtils.getAllSubmodules(module)){
done.add(submodule.getId());
}
addModuleToReport(report, module, filters, done, 1);
return report;
} | Generate a report about the targeted module dependencies
@param moduleId String
@param filters FiltersHolder
@return DependencyReport |
public final boolean roll(final LoggingEvent loggingEvent) {
for (int i = 0; i < this.fileRollables.length; i++) {
if (this.fileRollables[i].roll(loggingEvent)) {
return true;
}
}
return false;
} | Delegates file rolling to composed objects.
@see FileRollable#roll(org.apache.log4j.spi.LoggingEvent) |
public String getCacheId() {
return "GetVectorTileRequest{" +
"code=" + code +
", layerId=" + getLayerId() +
", crs=" + getCrs() +
", scale=" + scale +
", panOrigin=" + panOrigin +
", filter='" + filter + '\'' +
", crs='" + crs + '\'' +
", renderer='" + renderer + '\'' +
", styleInfo=" + styleInfo +
", paintGeometries=" + paintGeometries +
", paintLabels=" + paintLabels +
'}';
} | String identifier which is guaranteed to include sufficient information to assure to be different for two
instances which could produce different result. It is typically used as basis for calculation of hash
codes (like MD5, SHA1, SHA2 etc) of (collections of) objects.
@return cacheId
@since 1.8.0 |
public boolean isPartOf(GetVectorTileRequest request) {
if (Math.abs(request.scale - scale) > EQUALS_DELTA) { return false; }
if (code != null ? !code.equals(request.code) : request.code != null) { return false; }
if (crs != null ? !crs.equals(request.crs) : request.crs != null) { return false; }
if (filter != null ? !filter.equals(request.filter) : request.filter != null) { return false; }
if (panOrigin != null ? !panOrigin.equals(request.panOrigin) : request.panOrigin != null) { return false; }
if (renderer != null ? !renderer.equals(request.renderer) : request.renderer != null) { return false; }
if (styleInfo != null ? !styleInfo.equals(request.styleInfo) : request.styleInfo != null) { return false; }
if (paintGeometries && !request.paintGeometries) { return false; }
if (paintLabels && !request.paintLabels) { return false; }
return true;
} | Check if this request is part of the specified request. This is the case if both requests have equal properties
and the specified request is asking for the same or more paint operations than this one.
@param request another request
@return true if the current request is contained in the specified request
@since 1.10.0 |
Subsets and Splits