code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public void remove(Identity oid) { try { jcsCache.remove(oid.toString()); } catch (CacheException e) { throw new RuntimeCacheException(e.getMessage()); } }
removes an Object from the cache. @param oid the Identity of the object to be removed.
@Override public void body() { IMessageEvent msg = (IMessageEvent) getReason(); String content = (String) msg.getParameter("content").getValue(); if (content.equalsIgnoreCase("UnknownLanguageCall")) { this.getBeliefbase().getBelief("operatorTalking").setFact(true); try { String type = (String) msg.getParameter("performative") .getValue(); String agent_name = (String) ((IComponentIdentifier) msg .getParameter(SFipa.SENDER).getValue()).getLocalName(); String answer = (String) ((AgentBehaviour) getBeliefbase() .getBelief("agent_behaviour").getFact()) .processMessage(type, agent_name, content); if (answer == null) answer = "Unknown required action"; IMessageEvent msgResp = getEventbase().createReply(msg, "send_inform"); msgResp.getParameter(SFipa.CONTENT).setValue(answer); sendMessage(msgResp); } catch (Exception e) { // Not important for tutorial purposes. } } }
/* (non-Javadoc) @see jadex.bdi.runtime.Plan#body()
public void writeObject(Object o, GraphicsDocument document, boolean asChild) throws RenderException { document.writeElement("path", asChild); document.writeAttributeStart("d"); MultiLineString ml = (MultiLineString) o; for (int i = 0; i < ml.getNumGeometries(); i++) { document.writePathContent(ml.getGeometryN(i).getCoordinates()); } document.writeAttributeEnd(); }
Writes the body for a <code>MultiLineString</code> object. MultiLineStrings are encoded into SVG path elements. This function writes the different lines in one d-attribute of an SVG path element, separated by an 'M' character. @param o The <code>MultiLineString</code> to be encoded.
public List<GetLocationResult> search(String q, int maxRows, Locale locale) throws Exception { List<GetLocationResult> searchResult = new ArrayList<GetLocationResult>(); String url = URLEncoder.encode(q, "UTF8"); url = "q=select%20*%20from%20geo.placefinder%20where%20text%3D%22" + url + "%22"; if (maxRows > 0) { url = url + "&count=" + maxRows; } url = url + "&flags=GX"; if (null != locale) { url = url + "&locale=" + locale; } if (appId != null) { url = url + "&appid=" + appId; } InputStream inputStream = connect(url); if (null != inputStream) { SAXBuilder parser = new SAXBuilder(); Document doc = parser.build(inputStream); Element root = doc.getRootElement(); // check code for exception String message = root.getChildText("Error"); // Integer errorCode = Integer.parseInt(message); if (message != null && Integer.parseInt(message) != 0) { throw new Exception(root.getChildText("ErrorMessage")); } Element results = root.getChild("results"); for (Object obj : results.getChildren("Result")) { Element toponymElement = (Element) obj; GetLocationResult location = getLocationFromElement(toponymElement); searchResult.add(location); } } return searchResult; }
Call the Yahoo! PlaceFinder service for a result. @param q search string @param maxRows max number of rows in result, or 0 for all @param locale locale for strings @return list of found results @throws Exception oops @see <a href="http://developer.yahoo.com/boss/geo/docs/free_YQL.html#table_pf">Yahoo! Boss Geo PlaceFinder</a>
Object getValue(int fieldNum) { String attributeName = getAttributeName(fieldNum); ClassDescriptor cld = broker.getClassDescriptor(pc.getClass()); // field could be a primitive typed attribute... AttributeDescriptorBase fld = cld.getFieldDescriptorByName(attributeName); // field could be a reference attribute... if (fld == null) { fld = cld.getObjectReferenceDescriptorByName(attributeName); } // or it could be a collection attribute: if (fld == null) { fld = cld.getCollectionDescriptorByName(attributeName); } Object value = fld.getPersistentField().get(pc); return value; }
retrieve the value of attribute[fieldNum] from the object. @return Object the value of attribute[fieldNum]
final String excludeQuoted(final String datePattern) { final Pattern pattern = Pattern.compile("'('{2}|[^'])+'"); final Matcher matcher = pattern.matcher(datePattern); final StringBuffer buffer = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(buffer, ""); } matcher.appendTail(buffer); LogLog.debug("DatePattern reduced to " + buffer.toString() + " for computation of time-based rollover strategy (full pattern" + " will be used for actual roll-file naming)"); return buffer.toString(); }
Strips out quoted sections from a date format pattern to leave us with only characters meant to be interpreted by (or which are reserved by) {@link java.text.SimpleDateFormat}. @param datePattern The full pattern specified by the appender config. @return The datePattern minus quoted sections. @see java.text.SimpleDateFormat
public Object getUniqueValue(FieldDescriptor field) throws SequenceManagerException { return field.getJdbcType().sequenceKeyConversion(new Long(getUniqueLong(field))); // perform a sql to java conversion here, so that clients do // not see any db specific values // abyrne commented out: result = field.getFieldConversion().sqlToJava(result); // abyrne commented out: return result; }
Returns a unique object for the given field attribute. The returned value takes in account the jdbc-type and the FieldConversion.sql2java() conversion defined for <code>field</code>. The returned object is unique accross all tables in the extent of class the field belongs to.
void addExtent(String classname, ClassDescriptor cld) { synchronized (extentTable) { extentTable.put(classname, cld); } }
Add a pair of extent/classdescriptor to the extentTable to gain speed while retrieval of extents. @param classname the name of the extent itself @param cld the class descriptor, where it belongs to
void removeExtent(String classname) { synchronized (extentTable) { // returns the super class for given extent class name ClassDescriptor cld = (ClassDescriptor) extentTable.remove(classname); if(cld != null && m_topLevelClassTable != null) { Class extClass = null; try { extClass = ClassHelper.getClass(classname); } catch (ClassNotFoundException e) { // Should not happen throw new MetadataException("Can't instantiate class object for needed extent remove", e); } // remove extent from super class descriptor cld.removeExtentClass(classname); m_topLevelClassTable.remove(extClass); // clear map with first concrete classes, because the removed // extent could be such a first found concrete class m_firstConcreteClassMap = null; } } }
Remove a pair of extent/classdescriptor from the extentTable. @param classname the name of the extent itself
public Class getTopLevelClass(Class clazz) throws ClassNotPersistenceCapableException { if(m_topLevelClassTable == null) { m_topLevelClassTable = new HashMap(); } // try to find an extent that contains clazz Class retval = (Class) m_topLevelClassTable.get(clazz); if (retval == null) { synchronized (extentTable) { ClassDescriptor cld = (ClassDescriptor) extentTable.get(clazz.getName()); if (cld == null) { // walk the super-references cld = getDescriptorFor(clazz).getSuperClassDescriptor(); } if (cld != null) { // fix by Mark Rowell // Changed to call getExtentClass recursively retval = getTopLevelClass(cld.getClassOfObject()); // if such an extent could not be found just return clazz itself. if (retval == null) { retval = clazz; } } else { // check if class is persistence capable // + // Adam Jenkins: use the class that is associated // with the descriptor instead of the actual class ClassDescriptor temp = getDescriptorFor(clazz); retval = temp.getClassOfObject(); } m_topLevelClassTable.put(clazz, retval); } } return retval; }
Returns the top level (extent) class to which the given class belongs. This may be a (abstract) base-class, an interface or the given class itself if given class is not defined as an extent in other class descriptors. @throws ClassNotPersistenceCapableException if clazz is not persistence capable, i.e. if clazz is not defined in the DescriptorRepository.
public ClassDescriptor findFirstConcreteClass(ClassDescriptor cld) { if(m_firstConcreteClassMap == null) { m_firstConcreteClassMap = new HashMap(); } ClassDescriptor result = (ClassDescriptor) m_firstConcreteClassMap.get(cld.getClassNameOfObject()); if (result == null) { if(cld.isInterface() || cld.isAbstract()) { if(cld.isExtent()) { List extents = cld.getExtentClasses(); for (int i = 0; i < extents.size(); i++) { Class ext = (Class) extents.get(i); result = findFirstConcreteClass(getDescriptorFor(ext)); if(result != null) break; } } else { LoggerFactory.getDefaultLogger().error("["+this.getClass().getName()+"] Found interface/abstract class" + " in metadata declarations without concrete class: "+cld.getClassNameOfObject()); } m_firstConcreteClassMap.put(cld.getClassNameOfObject(), result); } else { result = cld; } } return result; }
Return the first found concrete class {@link ClassDescriptor}. This means a class which is not an interface or an abstract class. If given class descriptor is a concrete class, given class descriptor was returned. If no concrete class can be found <code>null</code> will be returned.
public ClassDescriptor getDescriptorFor(String strClassName) throws ClassNotPersistenceCapableException { ClassDescriptor result = discoverDescriptor(strClassName); if (result == null) { throw new ClassNotPersistenceCapableException(strClassName + " not found in OJB Repository"); } else { return result; } }
lookup a ClassDescriptor in the internal Hashtable @param strClassName a fully qualified class name as it is returned by Class.getName().
public void put(String classname, ClassDescriptor cld) { cld.setRepository(this); // BRJ synchronized (descriptorTable) { descriptorTable.put(classname, cld); List extentClasses = cld.getExtentClasses(); for (int i = 0; i < extentClasses.size(); ++i) { addExtent(((Class) extentClasses.get(i)).getName(), cld); } changeDescriptorEvent(); } }
Add a ClassDescriptor to the internal Hashtable<br> Set the Repository for ClassDescriptor
public String toXML() { String eol = SystemUtils.LINE_SEPARATOR; StringBuffer buf = new StringBuffer(); // write all ClassDescriptors Iterator i = this.iterator(); while (i.hasNext()) { buf.append(((XmlCapable) i.next()).toXML() + eol); } return buf.toString(); }
/* @see XmlCapable#toXML()
protected String getIsolationLevelAsString() { if (defaultIsolationLevel == IL_READ_UNCOMMITTED) { return LITERAL_IL_READ_UNCOMMITTED; } else if (defaultIsolationLevel == IL_READ_COMMITTED) { return LITERAL_IL_READ_COMMITTED; } else if (defaultIsolationLevel == IL_REPEATABLE_READ) { return LITERAL_IL_REPEATABLE_READ; } else if (defaultIsolationLevel == IL_SERIALIZABLE) { return LITERAL_IL_SERIALIZABLE; } else if (defaultIsolationLevel == IL_OPTIMISTIC) { return LITERAL_IL_OPTIMISTIC; } return LITERAL_IL_READ_UNCOMMITTED; }
returns IsolationLevel literal as matching to the corresponding id @return the IsolationLevel literal
protected ClassDescriptor discoverDescriptor(String className) { ClassDescriptor result = (ClassDescriptor) descriptorTable.get(className); if (result == null) { Class clazz; try { clazz = ClassHelper.getClass(className, true); } catch (ClassNotFoundException e) { throw new OJBRuntimeException("Class, " + className + ", could not be found.", e); } result = discoverDescriptor(clazz); } return result; }
Starts by looking to see if the <code>className</code> is already mapped specifically to the descritpor repository. If the <code>className</code> is not specifically mapped we look at the <code>className</code>'s parent class for a mapping. We do this until the parent class is of the type <code>java.lang.Object</code>. If no mapping was found, <code>null</code> is returned. Mappings successfuly discovered through inheritence are added to the internal table of class descriptors to improve performance on subsequent requests for those classes. <br/> author <a href="mailto:[email protected]">Scott T. Weaver</a> @param className name of class whose descriptor we need to find. @return ClassDescriptor for <code>className</code> or <code>null</code> if no ClassDescriptor could be located.
private ClassDescriptor discoverDescriptor(Class clazz) { ClassDescriptor result = (ClassDescriptor) descriptorTable.get(clazz.getName()); if (result == null) { Class superClass = clazz.getSuperclass(); // only recurse if the superClass is not java.lang.Object if (superClass != null) { result = discoverDescriptor(superClass); } if (result == null) { // we're also checking the interfaces as there could be normal // mappings for them in the repository (using factory-class, // factory-method, and the property field accessor) Class[] interfaces = clazz.getInterfaces(); if ((interfaces != null) && (interfaces.length > 0)) { for (int idx = 0; (idx < interfaces.length) && (result == null); idx++) { result = discoverDescriptor(interfaces[idx]); } } } if (result != null) { /** * Kuali Foundation modification -- 6/19/2009 */ synchronized (descriptorTable) { /** * End of Kuali Foundation modification */ descriptorTable.put(clazz.getName(), result); /** * Kuali Foundation modification -- 6/19/2009 */ } /** * End of Kuali Foundation modification */ } } return result; }
Internal method for recursivly searching for a class descriptor that avoids class loading when we already have a class object. @param clazz The class whose descriptor we need to find @return ClassDescriptor for <code>clazz</code> or <code>null</code> if no ClassDescriptor could be located.
protected void registerSuperClassMultipleJoinedTables(ClassDescriptor cld) { /* arminw: Sadly, we can't map to sub class-descriptor, because it's not guaranteed that they exist when this method is called. Thus we map the class instance instead of the class-descriptor. */ if(cld.getBaseClass() != null) { try { Class superClass = ClassHelper.getClass(cld.getBaseClass()); Class currentClass = cld.getClassOfObject(); synchronized(descriptorTable) { List subClasses = (List) superClassMultipleJoinedTablesMap.get(superClass); if(subClasses == null) { subClasses = new ArrayList(); superClassMultipleJoinedTablesMap.put(superClass, subClasses); } if(!subClasses.contains(currentClass)) { if(log.isDebugEnabled()) { log.debug("(MultipleJoinedTables): Register sub-class '" + currentClass + "' for class '" + superClass); } subClasses.add(currentClass); } } } catch(Exception e) { throw new MetadataException("Can't register super class '" + cld.getBaseClass() + "' for class-descriptor: " + cld, e); } } }
Internal used! Register sub-classes of specified class when mapping class to multiple joined tables is used. Normally this method is called by the {@link ClassDescriptor} itself. @param cld The {@link ClassDescriptor} of the class to register.
protected void deregisterSuperClassMultipleJoinedTables(ClassDescriptor cld) { try { Class currentClass = cld.getClassOfObject(); synchronized(descriptorTable) { // first remove registered sub-classes for current class List subClasses = (List) superClassMultipleJoinedTablesMap.remove(currentClass); if(subClasses != null && log.isDebugEnabled()) { log.debug("(MultipleJoinedTables): Deregister class " + currentClass + " with sub classes " + subClasses); } if(cld.getBaseClass() != null) { // then remove sub-class entry of current class for super-class Class superClass = ClassHelper.getClass(cld.getBaseClass()); subClasses = (List) superClassMultipleJoinedTablesMap.get(superClass); if(subClasses != null) { boolean removed = subClasses.remove(currentClass); if(removed && log.isDebugEnabled()) { log.debug("(MultipleJoinedTables): Remove sub-class entry '" + currentClass + "' in mapping for class '" + superClass + "'"); } } } } } catch(Exception e) { throw new MetadataException("Can't deregister super class '" + cld.getBaseClass() + "' for class-descriptor: " + cld, e); } }
Internal used! Deregister sub-classes of specified class when mapping to multiple joined tables is used. Normally this method is called when {@link #remove(Class)} a class. @param cld The {@link ClassDescriptor} of the class to register.
public Class[] getSubClassesMultipleJoinedTables(ClassDescriptor cld, boolean wholeTree) { ArrayList result = new ArrayList(); createResultSubClassesMultipleJoinedTables(result, cld, wholeTree); return (Class[]) result.toArray(new Class[result.size()]); }
Return <em>sub-classes</em> of the specified class using the <em>"super"-Reference</em> concept. @param cld The {@link ClassDescriptor} of the class to search for sub-classes. @param wholeTree If set <em>true</em>, the whole sub-class tree of the specified class will be returned. If <em>false</em> only the direct sub-classes of the specified class will be returned. @return An array of <em>sub-classes</em> for the specified class.
private void createResultSubClassesMultipleJoinedTables(List result, ClassDescriptor cld, boolean wholeTree) { List tmp = (List) superClassMultipleJoinedTablesMap.get(cld.getClassOfObject()); if(tmp != null) { result.addAll(tmp); if(wholeTree) { for(int i = 0; i < tmp.size(); i++) { Class subClass = (Class) tmp.get(i); ClassDescriptor subCld = getDescriptorFor(subClass); createResultSubClassesMultipleJoinedTables(result, subCld, wholeTree); } } } }
Add all sub-classes using multiple joined tables feature for specified class. @param result The list to add results. @param cld The {@link ClassDescriptor} of the class to search for sub-classes. @param wholeTree If set <em>true</em>, the whole sub-class tree of the specified class will be returned. If <em>false</em> only the direct sub-classes of the specified class will be returned.
public List<Feature> getFeaturesByLocation(Coordinate layerCoordinate, double layerScale, int pixelTolerance) throws LayerException { if (!isEnableFeatureInfoSupport()) { return Collections.emptyList(); } List<Feature> features = new ArrayList<Feature>(); Resolution bestResolution = getResolutionForScale(layerScale); RasterGrid grid = getRasterGrid(new Envelope(layerCoordinate), bestResolution.getTileWidth(), bestResolution.getTileHeight()); int x = (int) (((layerCoordinate.x - grid.getLowerLeft().x) * bestResolution.getTileWidthPx()) / grid .getTileWidth()); int y = (int) (bestResolution.getTileHeightPx() - (((layerCoordinate.y - grid.getLowerLeft().y) * bestResolution .getTileHeightPx()) / grid.getTileHeight())); Bbox layerBox = new Bbox(grid.getLowerLeft().x, grid.getLowerLeft().y, grid.getTileWidth(), grid.getTileHeight()); InputStream stream = null; try { String url = formatGetFeatureInfoUrl(bestResolution.getTileWidthPx(), bestResolution.getTileHeightPx(), layerBox, x, y, featureInfoFormat == WmsFeatureInfoFormat.HTML); log.debug("getFeaturesByLocation: {} {} {} {}", new Object[] { layerCoordinate, layerScale, pixelTolerance, url }); stream = httpService.getStream(url, this); switch (featureInfoFormat) { case GML2: features = getGmlFeatures(stream, Version.GML2); break; case GML3: features = getGmlFeatures(stream, Version.GML3); break; case HTML: features = getHtmlFeatures(url); break; case TEXT: features = getTextFeatures(stream); break; case JSON: features = getTextFeatures(stream); break; } } catch (LayerException le) { throw le; // NOSONAR } catch (Exception e) { // NOSONAR throw new LayerException(e, ExceptionCode.UNEXPECTED_PROBLEM); } finally { if (null != stream) { try { stream.close(); } catch (IOException ioe) { // ignore, closing anyway } } } return features; }
{@inheritDoc}.
public List<RasterTile> paint(CoordinateReferenceSystem targetCrs, Envelope bounds, double scale) throws GeomajasException { Envelope layerBounds = bounds; double layerScale = scale; CrsTransform layerToMap = null; boolean needTransform = !crs.equals(targetCrs); try { // We don't necessarily need to split into same CRS and different CRS cases, the latter implementation uses // identity transform if crs's are equal for map and layer but might introduce bugs in rounding and/or // conversions. if (needTransform) { layerToMap = geoService.getCrsTransform(crs, targetCrs); CrsTransform mapToLayer = geoService.getCrsTransform(targetCrs, crs); // Translate the map coordinates to layer coordinates, assumes equal x-y orientation layerBounds = geoService.transform(bounds, mapToLayer); layerScale = bounds.getWidth() * scale / layerBounds.getWidth(); } } catch (MismatchedDimensionException e) { throw new GeomajasException(e, ExceptionCode.RENDER_DIMENSION_MISMATCH); } layerBounds = clipBounds(layerBounds); if (layerBounds.isNull()) { return new ArrayList<RasterTile>(0); } // Grid is in layer coordinate space! Resolution bestResolution = getResolutionForScale(layerScale); RasterGrid grid = getRasterGrid(layerBounds, bestResolution.getTileWidth(), bestResolution.getTileHeight()); // We calculate the first tile's screen box with this assumption List<RasterTile> result = new ArrayList<RasterTile>(); for (int i = grid.getXmin(); i < grid.getXmax(); i++) { for (int j = grid.getYmin(); j < grid.getYmax(); j++) { double x = grid.getLowerLeft().x + (i - grid.getXmin()) * grid.getTileWidth(); double y = grid.getLowerLeft().y + (j - grid.getYmin()) * grid.getTileHeight(); // layer coordinates Bbox worldBox; Bbox layerBox; if (needTransform) { layerBox = new Bbox(x, y, grid.getTileWidth(), grid.getTileHeight()); // Transforming back to map coordinates will only result in a proper grid if the transformation // is nearly affine worldBox = geoService.transform(layerBox, layerToMap); } else { worldBox = new Bbox(x, y, grid.getTileWidth(), grid.getTileHeight()); layerBox = worldBox; } // Rounding to avoid white space between raster tiles lower-left becomes upper-left in inverted y-space Bbox screenBox = new Bbox(Math.round(scale * worldBox.getX()), -Math.round(scale * worldBox.getMaxY()), Math.round(scale * worldBox.getMaxX()) - Math.round(scale * worldBox.getX()), Math.round(scale * worldBox.getMaxY()) - Math.round(scale * worldBox.getY())); RasterTile image = new RasterTile(screenBox, getId() + "." + bestResolution.getLevel() + "." + i + "," + j); image.setCode(new TileCode(bestResolution.getLevel(), i, j)); String url = formatUrl(bestResolution.getTileWidthPx(), bestResolution.getTileHeightPx(), layerBox); image.setUrl(url); result.add(image); } } return result; }
Paints the specified bounds optimized for the specified scale in pixel/unit. @param targetCrs Coordinate reference system used for bounds @param bounds bounds to request images for @param scale scale or zoom level (unit?) @return a list of raster images that covers the bounds @throws GeomajasException oops
private StringBuilder formatBaseUrl(String targetUrl, int width, int height, Bbox box) throws GeomajasException { try { StringBuilder url = new StringBuilder(targetUrl); int pos = url.lastIndexOf("?"); if (pos > 0) { url.append("&SERVICE=WMS"); } else { url.append("?SERVICE=WMS"); } String layers = getId(); if (layerInfo.getDataSourceName() != null) { layers = layerInfo.getDataSourceName(); } url.append("&layers="); url.append(URLEncoder.encode(layers, "UTF8")); url.append("&WIDTH="); url.append(Integer.toString(width)); url.append("&HEIGHT="); url.append(Integer.toString(height)); DecimalFormat decimalFormat = new DecimalFormat(); // create new as this is not thread safe decimalFormat.setDecimalSeparatorAlwaysShown(false); decimalFormat.setGroupingUsed(false); decimalFormat.setMinimumFractionDigits(0); decimalFormat.setMaximumFractionDigits(100); DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator('.'); decimalFormat.setDecimalFormatSymbols(symbols); url.append("&bbox="); url.append(decimalFormat.format(box.getX())); url.append(","); url.append(decimalFormat.format(box.getY())); url.append(","); url.append(decimalFormat.format(box.getMaxX())); url.append(","); url.append(decimalFormat.format(box.getMaxY())); url.append("&format="); url.append(format); url.append("&version="); url.append(version); if ("1.3.0".equals(version)) { url.append("&crs="); } else { url.append("&srs="); } url.append(URLEncoder.encode(layerInfo.getCrs(), "UTF8")); url.append("&styles="); url.append(styles); if (null != parameters) { for (Parameter p : parameters) { url.append("&"); url.append(URLEncoder.encode(p.getName(), "UTF8")); url.append("="); url.append(URLEncoder.encode(p.getValue(), "UTF8")); } } if (useProxy && null != securityContext.getToken()) { url.append("&userToken="); url.append(securityContext.getToken()); } return url; } catch (UnsupportedEncodingException uee) { throw new IllegalStateException("Cannot find UTF8 encoding?", uee); } }
Build the base part of the url (doesn't change for getMap or getFeatureInfo requests). @param targetUrl base url @param width image width @param height image height @param box bounding box @return base WMS url @throws GeomajasException missing parameter
public ProxyAuthentication getProxyAuthentication() { // convert authentication to layerAuthentication so we only use one // TODO Remove when removing deprecated authentication field. if (layerAuthentication == null && authentication != null) { layerAuthentication = new LayerAuthentication(); layerAuthentication.setAuthenticationMethod(LayerAuthenticationMethod.valueOf(authentication .getAuthenticationMethod().name())); layerAuthentication.setPassword(authentication.getPassword()); layerAuthentication.setPasswordKey(authentication.getPasswordKey()); layerAuthentication.setRealm(authentication.getRealm()); layerAuthentication.setUser(authentication.getUser()); layerAuthentication.setUserKey(authentication.getUserKey()); } // TODO Remove when removing deprecated authentication field. return layerAuthentication; }
Get the authentication info for this layer. @return authentication info.
@Api public void setUseCache(boolean useCache) { if (null == cacheManagerService && useCache) { log.warn("The caching plugin needs to be available to cache WMS requests. Not setting useCache."); } else { this.useCache = useCache; } }
Set whether the WMS tiles should be cached for later use. This implies that the WMS tiles will be proxied. @param useCache true when request needs to be cached @since 1.9.0
protected boolean check(String id, List<String> includes, List<String> excludes) { return check(id, includes) && !check(id, excludes); }
Check whether the given id is included in the list of includes and not excluded. @param id id to check @param includes list of include regular expressions @param excludes list of exclude regular expressions @return true when id included and not excluded
protected boolean check(String id, List<String> includes) { if (null != includes) { for (String check : includes) { if (check(id, check)) { return true; } } } return false; }
Check whether the given is is matched by one of the include expressions. @param id id to check @param includes list of include regular expressions @return true when id is included
protected boolean check(String value, String regex) { Pattern pattern = Pattern.compile(regex); return pattern.matcher(value).matches(); }
Check whether the value is matched by a regular expression. @param value value @param regex regular expression @return true when value is matched
protected ClassDescriptor getClassDescriptor() { ClassDescriptor cld = (ClassDescriptor) m_classDescriptor.get(); if(cld == null) { throw new OJBRuntimeException("Requested ClassDescriptor instance was already GC by JVM"); } return cld; }
Returns the classDescriptor. @return ClassDescriptor
protected void appendWhereClause(FieldDescriptor[] fields, StringBuffer stmt) throws PersistenceBrokerException { stmt.append(" WHERE "); for(int i = 0; i < fields.length; i++) { FieldDescriptor fmd = fields[i]; stmt.append(fmd.getColumnName()); stmt.append(" = ? "); if(i < fields.length - 1) { stmt.append(" AND "); } } }
Generate a sql where-clause for the array of fields @param fields array containing all columns used in WHERE clause
protected void appendWhereClause(ClassDescriptor cld, boolean useLocking, StringBuffer stmt) { FieldDescriptor[] pkFields = cld.getPkFields(); FieldDescriptor[] fields; fields = pkFields; if(useLocking) { FieldDescriptor[] lockingFields = cld.getLockingFields(); if(lockingFields.length > 0) { fields = new FieldDescriptor[pkFields.length + lockingFields.length]; System.arraycopy(pkFields, 0, fields, 0, pkFields.length); System.arraycopy(lockingFields, 0, fields, pkFields.length, lockingFields.length); } } appendWhereClause(fields, stmt); }
Generate a where clause for a prepared Statement. Only primary key and locking fields are used in this where clause @param cld the ClassDescriptor @param useLocking true if locking fields should be included @param stmt the StatementBuffer
public Object copy(final Object obj, PersistenceBroker broker) throws ObjectCopyException { ObjectOutputStream oos = null; ObjectInputStream ois = null; try { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); // serialize and pass the object oos.writeObject(obj); oos.flush(); final ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); ois = new ObjectInputStream(bin); // return the new object return ois.readObject(); } catch (Exception e) { throw new ObjectCopyException(e); } finally { try { if (oos != null) { oos.close(); } if (ois != null) { ois.close(); } } catch (IOException ioe) { // ignore } } }
This implementation will probably be slower than the metadata object copy, but this was easier to implement. @see org.apache.ojb.otm.copy.ObjectCopyStrategy#copy(Object)
public void bindDelete(PreparedStatement stmt, Identity oid, ClassDescriptor cld) throws SQLException { Object[] pkValues = oid.getPrimaryKeyValues(); FieldDescriptor[] pkFields = cld.getPkFields(); int i = 0; try { for (; i < pkValues.length; i++) { setObjectForStatement(stmt, i + 1, pkValues[i], pkFields[i].getJdbcType().getType()); } } catch (SQLException e) { m_log.error("bindDelete failed for: " + oid.toString() + ", while set value '" + pkValues[i] + "' for column " + pkFields[i].getColumnName()); throw e; } }
binds the Identities Primary key values to the statement
public void bindDelete(PreparedStatement stmt, ClassDescriptor cld, Object obj) throws SQLException { if (cld.getDeleteProcedure() != null) { this.bindProcedure(stmt, cld, obj, cld.getDeleteProcedure()); } else { int index = 1; ValueContainer[] values, currentLockingValues; currentLockingValues = cld.getCurrentLockingValues(obj); // parameters for WHERE-clause pk values = getKeyValues(m_broker, cld, obj); for (int i = 0; i < values.length; i++) { setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType()); index++; } // parameters for WHERE-clause locking values = currentLockingValues; for (int i = 0; i < values.length; i++) { setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType()); index++; } } }
binds the objects primary key and locking values to the statement, BRJ
private int bindStatementValue(PreparedStatement stmt, int index, Object attributeOrQuery, Object value, ClassDescriptor cld) throws SQLException { FieldDescriptor fld = null; // if value is a subQuery bind it if (value instanceof Query) { Query subQuery = (Query) value; return bindStatement(stmt, subQuery, cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index); } // if attribute is a subQuery bind it if (attributeOrQuery instanceof Query) { Query subQuery = (Query) attributeOrQuery; bindStatement(stmt, subQuery, cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index); } else { fld = cld.getFieldDescriptorForPath((String) attributeOrQuery); } if (fld != null) { // BRJ: use field conversions and platform if (value != null) { m_platform.setObjectForStatement(stmt, index, fld.getFieldConversion().javaToSql(value), fld.getJdbcType().getType()); } else { m_platform.setNullForStatement(stmt, index, fld.getJdbcType().getType()); } } else { if (value != null) { stmt.setObject(index, value); } else { stmt.setNull(index, Types.NULL); } } return ++index; // increment before return }
bind attribute and value @param stmt @param index @param attributeOrQuery @param value @param cld @return @throws SQLException
private int bindStatement(PreparedStatement stmt, int index, SelectionCriteria crit, ClassDescriptor cld) throws SQLException { return bindStatementValue(stmt, index, crit.getAttribute(), crit.getValue(), cld); }
bind SelectionCriteria @param stmt the PreparedStatement @param index the position of the parameter to bind @param crit the Criteria containing the parameter @param cld the ClassDescriptor @return next index for PreparedStatement
private int bindStatement(PreparedStatement stmt, int index, BetweenCriteria crit, ClassDescriptor cld) throws SQLException { index = bindStatementValue(stmt, index, crit.getAttribute(), crit.getValue(), cld); return bindStatementValue(stmt, index, crit.getAttribute(), crit.getValue2(), cld); }
bind BetweenCriteria @param stmt the PreparedStatement @param index the position of the parameter to bind @param crit the Criteria containing the parameter @param cld the ClassDescriptor @return next index for PreparedStatement
private int bindStatement(PreparedStatement stmt, int index, InCriteria crit, ClassDescriptor cld) throws SQLException { if (crit.getValue() instanceof Collection) { Collection values = (Collection) crit.getValue(); Iterator iter = values.iterator(); while (iter.hasNext()) { index = bindStatementValue(stmt, index, crit.getAttribute(), iter.next(), cld); } } else { index = bindStatementValue(stmt, index, crit.getAttribute(), crit.getValue(), cld); } return index; }
bind InCriteria @param stmt the PreparedStatement @param index the position of the parameter to bind @param crit the Criteria containing the parameter @param cld the ClassDescriptor @return next index for PreparedStatement
private int bindStatement(PreparedStatement stmt, int index, ExistsCriteria crit, ClassDescriptor cld) throws SQLException { Query subQuery = (Query) crit.getValue(); // if query has criteria, bind them if (subQuery.getCriteria() != null && !subQuery.getCriteria().isEmpty()) { return bindStatement(stmt, subQuery.getCriteria(), cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index); // otherwise, just ignore it } else { return index; } }
bind ExistsCriteria @param stmt the PreparedStatement @param index the position of the parameter to bind @param crit the Criteria containing the parameter @param cld the ClassDescriptor @return next index for PreparedStatement
public int bindStatement(PreparedStatement stmt, Query query, ClassDescriptor cld, int param) throws SQLException { int result; result = bindStatement(stmt, query.getCriteria(), cld, param); result = bindStatement(stmt, query.getHavingCriteria(), cld, result); return result; }
bind a Query based Select Statement
protected int bindStatement(PreparedStatement stmt, Criteria crit, ClassDescriptor cld, int param) throws SQLException { if (crit != null) { Enumeration e = crit.getElements(); while (e.hasMoreElements()) { Object o = e.nextElement(); if (o instanceof Criteria) { Criteria pc = (Criteria) o; param = bindStatement(stmt, pc, cld, param); } else { SelectionCriteria c = (SelectionCriteria) o; // BRJ : bind once for the criterion's main class param = bindSelectionCriteria(stmt, param, c, cld); // BRJ : and once for each extent for (int i = 0; i < c.getNumberOfExtentsToBind(); i++) { param = bindSelectionCriteria(stmt, param, c, cld); } } } } return param; }
bind a Query based Select Statement
private int bindSelectionCriteria(PreparedStatement stmt, int index, SelectionCriteria crit, ClassDescriptor cld) throws SQLException { if (crit instanceof NullCriteria) index = bindStatement(stmt, index, (NullCriteria) crit); else if (crit instanceof BetweenCriteria) index = bindStatement(stmt, index, (BetweenCriteria) crit, cld); else if (crit instanceof InCriteria) index = bindStatement(stmt, index, (InCriteria) crit, cld); else if (crit instanceof SqlCriteria) index = bindStatement(stmt, index, (SqlCriteria) crit); else if (crit instanceof FieldCriteria) index = bindStatement(stmt, index, (FieldCriteria) crit); else if (crit instanceof ExistsCriteria) index = bindStatement(stmt, index, (ExistsCriteria) crit, cld); else index = bindStatement(stmt, index, crit, cld); return index; }
bind SelectionCriteria @param stmt the PreparedStatement @param index the position of the parameter to bind @param crit the Criteria containing the parameter @param cld the ClassDescriptor @return next index for PreparedStatement
public void bindInsert(PreparedStatement stmt, ClassDescriptor cld, Object obj) throws java.sql.SQLException { ValueContainer[] values; cld.updateLockingValues(obj); // BRJ : provide useful defaults for locking fields if (cld.getInsertProcedure() != null) { this.bindProcedure(stmt, cld, obj, cld.getInsertProcedure()); } else { values = getAllValues(cld, obj); for (int i = 0; i < values.length; i++) { setObjectForStatement(stmt, i + 1, values[i].getValue(), values[i].getJdbcType().getType()); } } }
binds the values of the object obj to the statements parameters
public void bindSelect(PreparedStatement stmt, Identity oid, ClassDescriptor cld, boolean callableStmt) throws SQLException { ValueContainer[] values = null; int i = 0; int j = 0; if (cld == null) { cld = m_broker.getClassDescriptor(oid.getObjectsRealClass()); } try { if(callableStmt) { // First argument is the result set m_platform.registerOutResultSet((CallableStatement) stmt, 1); j++; } values = getKeyValues(m_broker, cld, oid); for (/*void*/; i < values.length; i++, j++) { setObjectForStatement(stmt, j + 1, values[i].getValue(), values[i].getJdbcType().getType()); } } catch (SQLException e) { m_log.error("bindSelect failed for: " + oid.toString() + ", PK: " + i + ", value: " + values[i]); throw e; } }
Binds the Identities Primary key values to the statement.
public void bindUpdate(PreparedStatement stmt, ClassDescriptor cld, Object obj) throws java.sql.SQLException { if (cld.getUpdateProcedure() != null) { this.bindProcedure(stmt, cld, obj, cld.getUpdateProcedure()); } else { int index = 1; ValueContainer[] values, valuesSnapshot; // first take a snapshot of current locking values valuesSnapshot = cld.getCurrentLockingValues(obj); cld.updateLockingValues(obj); // BRJ values = getNonKeyValues(m_broker, cld, obj); // parameters for SET-clause for (int i = 0; i < values.length; i++) { setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType()); index++; } // parameters for WHERE-clause pk values = getKeyValues(m_broker, cld, obj); for (int i = 0; i < values.length; i++) { setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType()); index++; } // parameters for WHERE-clause locking // take old locking values values = valuesSnapshot; for (int i = 0; i < values.length; i++) { setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType()); index++; } } }
binds the values of the object obj to the statements parameters
public int bindValues(PreparedStatement stmt, ValueContainer[] values, int index) throws SQLException { if (values != null) { for (int i = 0; i < values.length; i++) { setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType()); index++; } } return index; }
binds the given array of values (if not null) starting from the given parameter index @return the next parameter index
public PreparedStatement getDeleteStatement(ClassDescriptor cld) throws PersistenceBrokerSQLException, PersistenceBrokerException { try { return cld.getStatementsForClass(m_conMan).getDeleteStmt(m_conMan.getConnection()); } catch (SQLException e) { throw new PersistenceBrokerSQLException("Could not build statement ask for", e); } catch (LookupException e) { throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e); } }
return a prepared DELETE Statement fitting for the given ClassDescriptor
public Statement getGenericStatement(ClassDescriptor cds, boolean scrollable) throws PersistenceBrokerException { try { return cds.getStatementsForClass(m_conMan).getGenericStmt(m_conMan.getConnection(), scrollable); } catch (LookupException e) { throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e); } }
return a generic Statement for the given ClassDescriptor. Never use this method for UPDATE/INSERT/DELETE if you want to use the batch mode.
public PreparedStatement getInsertStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException { try { return cds.getStatementsForClass(m_conMan).getInsertStmt(m_conMan.getConnection()); } catch (SQLException e) { throw new PersistenceBrokerSQLException("Could not build statement ask for", e); } catch (LookupException e) { throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e); } }
return a prepared Insert Statement fitting for the given ClassDescriptor
public PreparedStatement getPreparedStatement(ClassDescriptor cds, String sql, boolean scrollable, int explicitFetchSizeHint, boolean callableStmt) throws PersistenceBrokerException { try { return cds.getStatementsForClass(m_conMan).getPreparedStmt(m_conMan.getConnection(), sql, scrollable, explicitFetchSizeHint, callableStmt); } catch (LookupException e) { throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e); } }
return a generic Statement for the given ClassDescriptor
public PreparedStatement getSelectByPKStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException { try { return cds.getStatementsForClass(m_conMan).getSelectByPKStmt(m_conMan.getConnection()); } catch (SQLException e) { throw new PersistenceBrokerSQLException("Could not build statement ask for", e); } catch (LookupException e) { throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e); } }
return a prepared Select Statement for the given ClassDescriptor
public PreparedStatement getUpdateStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException { try { return cds.getStatementsForClass(m_conMan).getUpdateStmt(m_conMan.getConnection()); } catch (SQLException e) { throw new PersistenceBrokerSQLException("Could not build statement ask for", e); } catch (LookupException e) { throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e); } }
return a prepared Update Statement fitting to the given ClassDescriptor
protected ValueContainer[] getAllValues(ClassDescriptor cld, Object obj) throws PersistenceBrokerException { return m_broker.serviceBrokerHelper().getAllRwValues(cld, obj); }
returns an array containing values for all the Objects attribute @throws PersistenceBrokerException if there is an erros accessing obj field values
protected ValueContainer[] getKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException { return broker.serviceBrokerHelper().getKeyValues(cld, obj); }
returns an Array with an Objects PK VALUES @throws PersistenceBrokerException if there is an erros accessing o field values
protected ValueContainer[] getKeyValues(PersistenceBroker broker, ClassDescriptor cld, Identity oid) throws PersistenceBrokerException { return broker.serviceBrokerHelper().getKeyValues(cld, oid); }
returns an Array with an Identities PK VALUES @throws PersistenceBrokerException if there is an erros accessing o field values
protected ValueContainer[] getNonKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException { return broker.serviceBrokerHelper().getNonKeyRwValues(cld, obj); }
returns an Array with an Objects NON-PK VALUES @throws PersistenceBrokerException if there is an erros accessing o field values
private void bindProcedure(PreparedStatement stmt, ClassDescriptor cld, Object obj, ProcedureDescriptor proc) throws SQLException { int valueSub = 0; // Figure out if we are using a callable statement. If we are, then we // will need to register one or more output parameters. CallableStatement callable = null; try { callable = (CallableStatement) stmt; } catch(Exception e) { m_log.error("Error while bind values for class '" + (cld != null ? cld.getClassNameOfObject() : null) + "', using stored procedure: "+ proc, e); if(e instanceof SQLException) { throw (SQLException) e; } else { throw new PersistenceBrokerException("Unexpected error while bind values for class '" + (cld != null ? cld.getClassNameOfObject() : null) + "', using stored procedure: "+ proc); } } // If we have a return value, then register it. if ((proc.hasReturnValue()) && (callable != null)) { int jdbcType = proc.getReturnValueFieldRef().getJdbcType().getType(); m_platform.setNullForStatement(stmt, valueSub + 1, jdbcType); callable.registerOutParameter(valueSub + 1, jdbcType); valueSub++; } // Process all of the arguments. Iterator iterator = proc.getArguments().iterator(); while (iterator.hasNext()) { ArgumentDescriptor arg = (ArgumentDescriptor) iterator.next(); Object val = arg.getValue(obj); int jdbcType = arg.getJdbcType(); setObjectForStatement(stmt, valueSub + 1, val, jdbcType); if ((arg.getIsReturnedByProcedure()) && (callable != null)) { callable.registerOutParameter(valueSub + 1, jdbcType); } valueSub++; } }
Bind a prepared statment that represents a call to a procedure or user-defined function. @param stmt the statement to bind. @param cld the class descriptor of the object that triggered the invocation of the procedure or user-defined function. @param obj the object that triggered the invocation of the procedure or user-defined function. @param proc the procedure descriptor that provides information about the arguments that shoudl be passed to the procedure or user-defined function
private void setObjectForStatement(PreparedStatement stmt, int index, Object value, int sqlType) throws SQLException { if (value == null) { m_platform.setNullForStatement(stmt, index, sqlType); } else { m_platform.setObjectForStatement(stmt, index, value, sqlType); } }
Sets object for statement at specific index, adhering to platform- and null-rules. @param stmt the statement @param index the current parameter index @param value the value to set @param sqlType the JDBC SQL-type of the value @throws SQLException on platform error
private void pushToApplicationCache(int typeToProcess, int typeAfterProcess) { for(Iterator iter = sessionCache.values().iterator(); iter.hasNext();) { CacheEntry entry = (CacheEntry) iter.next(); // if the cached object was garbage collected, nothing to do Object result = entry.get(); if(result == null) { if(log.isDebugEnabled()) log.debug("Object in session cache was gc, nothing to push to application cache"); } else { // push all objects of the specified type to application cache if(entry.type == typeToProcess) { if(log.isDebugEnabled()) { log.debug("Move obj from session cache --> application cache : " + entry.oid); } /* arminw: only cache non-proxy or real subject of materialized proxy objects */ if(ProxyHelper.isMaterialized(result)) { putToApplicationCache(entry.oid, ProxyHelper.getRealObject(result), false); // set the new type after the object was pushed to application cache entry.type = typeAfterProcess; } } } } }
Push all cached objects of the specified type, e.g. like {@link #TYPE_WRITE} to the application cache and reset type to the specified one.
public void doInternalCache(Identity oid, Object obj, int type) { processQueue(); // pass new materialized objects immediately to application cache if(type == TYPE_NEW_MATERIALIZED) { boolean result = putToApplicationCache(oid, obj, true); CacheEntry entry = new CacheEntry(oid, obj, TYPE_CACHED_READ, queue); if(result) { // as current session says this object is new, put it // in session cache putToSessionCache(oid, entry, false); } else { // object is not new, but if not in session cache // put it in putToSessionCache(oid, entry, true); if(log.isDebugEnabled()) { log.debug("The 'new' materialized object was already in cache," + " will not push it to application cache: " + oid); } } } else { // other types of cached objects will only be put to the session // cache. CacheEntry entry = new CacheEntry(oid, obj, type, queue); putToSessionCache(oid, entry, false); } }
Cache the given object. Creates a {@link org.apache.ojb.broker.cache.ObjectCacheTwoLevelImpl.CacheEntry} and put it to session cache. If the specified object to cache is of type {@link #TYPE_NEW_MATERIALIZED} it will be immediately pushed to the application cache.
public Object lookup(Identity oid) { Object result = null; // 1. lookup an instance in session cache CacheEntry entry = (CacheEntry) sessionCache.get(oid); if(entry != null) { result = entry.get(); } if(result == null) { result = lookupFromApplicationCache(oid); // 4. if we have a match // put object in session cache if(result != null) { doInternalCache(oid, result, TYPE_CACHED_READ); materializeFullObject(result); if(log.isDebugEnabled()) log.debug("Materialized object from second level cache: " + oid); } } if(result != null && log.isDebugEnabled()) { log.debug("Match for: " + oid); } return result; }
Lookup corresponding object from session cache or if not found from the underlying real {@link ObjectCache} - Return <em>null</em> if no object was found.
public void materializeFullObject(Object target) { ClassDescriptor cld = broker.getClassDescriptor(target.getClass()); // don't force, let OJB use the user settings final boolean forced = false; if (forceProxies){ broker.getReferenceBroker().retrieveProxyReferences(target, cld, forced); broker.getReferenceBroker().retrieveProxyCollections(target, cld, forced); }else{ broker.getReferenceBroker().retrieveReferences(target, cld, forced); broker.getReferenceBroker().retrieveCollections(target, cld, forced); } }
This cache implementation cache only "flat" objects (persistent objects without any references), so when {@link #lookup(org.apache.ojb.broker.Identity)} a cache object it needs full materialization (assign all referenced objects) before the cache returns the object. The materialization of the referenced objects based on the auto-XXX settings specified in the metadata mapping. <br/> Override this method if needed in conjunction with a user-defined {@link org.apache.ojb.broker.cache.ObjectCacheTwoLevelImpl.CopyStrategy}. @param target The "flat" object for full materialization
public void remove(Identity oid) { if(log.isDebugEnabled()) log.debug("Remove object " + oid); sessionCache.remove(oid); getApplicationCache().remove(oid); }
Remove the corresponding object from session AND application cache.
private void putToSessionCache(Identity oid, CacheEntry entry, boolean onlyIfNew) { if(onlyIfNew) { // no synchronization needed, because session cache was used per broker instance if(!sessionCache.containsKey(oid)) sessionCache.put(oid, entry); } else { sessionCache.put(oid, entry); } }
Put object to session cache. @param oid The {@link org.apache.ojb.broker.Identity} of the object to cache @param entry The {@link org.apache.ojb.broker.cache.ObjectCacheTwoLevelImpl.CacheEntry} of the object @param onlyIfNew Flag, if set <em>true</em> only new objects (not already in session cache) be cached.
private void processQueue() { CacheEntry sv; while((sv = (CacheEntry) queue.poll()) != null) { sessionCache.remove(sv.oid); } }
Make sure that the Identity objects of garbage collected cached objects are removed too.
public void afterCommit(PBStateEvent event) { if(log.isDebugEnabled()) log.debug("afterCommit() call, push objects to application cache"); if(invokeCounter != 0) { log.error("** Please check method calls of ObjectCacheTwoLevelImpl#enableMaterialization and" + " ObjectCacheTwoLevelImpl#disableMaterialization, number of calls have to be equals **"); } try { // we only push "really modified objects" to the application cache pushToApplicationCache(TYPE_WRITE, TYPE_CACHED_READ); } finally { resetSessionCache(); } }
After committing the transaction push the object from session cache ( 1st level cache) to the application cache (2d level cache). Finally, clear the session cache.
public void beforeClose(PBStateEvent event) { /* arminw: this is a workaround for use in managed environments. When a PB instance is used within a container a PB.close call is done when leave the container method. This close the PB handle (but the real instance is still in use) and the PB listener are notified. But the JTA tx was not committed at this point in time and the session cache should not be cleared, because the updated/new objects will be pushed to the real cache on commit call (if we clear, nothing to push). So we check if the real broker is in a local tx (in this case we are in a JTA tx and the handle is closed), if true we don't reset the session cache. */ if(!broker.isInTransaction()) { if(log.isDebugEnabled()) log.debug("Clearing the session cache"); resetSessionCache(); } }
Before closing the PersistenceBroker ensure that the session cache is cleared
public boolean isUpToDate(final DbArtifact artifact) { final List<String> versions = repoHandler.getArtifactVersions(artifact); final String currentVersion = artifact.getVersion(); final String lastDevVersion = getLastVersion(versions); final String lastReleaseVersion = getLastRelease(versions); if(lastDevVersion == null || lastReleaseVersion == null) { // Plain Text comparison against version "strings" for(final String version: versions){ if(version.compareTo(currentVersion) > 0){ return false; } } return true; } else { return currentVersion.equals(lastDevVersion) || currentVersion.equals(lastReleaseVersion); } }
Check if the current version match the last release or the last snapshot one @param artifact @return boolean
public String getLastRelease(final Collection<String> versions) { final List<Version> sorted = versions.stream() .filter(Version::isValid) // filter invalid input values .map(Version::make) .filter(Optional::isPresent) .map(Optional::get) .filter(Version::isRelease) .sorted((v1, v2) -> { try { return v1.compare(v2); } catch (IncomparableException e) { return 0; } }) .collect(Collectors.toList()); if(sorted.isEmpty()) { if(LOG.isWarnEnabled()) { LOG.warn(String.format("Cannot obtain last release from collection %s", versions.toString())); } return null; } return sorted.get(sorted.size() - 1).toString(); }
Find-out the last release version in a list of version (regarding Axway Conventions) @param versions @return String @throws IncomparableException
public void clearItems() { List<LegendItemComponentImpl> items = new ArrayList<LegendItemComponentImpl>(); for (PrintComponent child : children) { if (child instanceof LegendItemComponentImpl) { items.add((LegendItemComponentImpl) child); } } for (LegendItemComponentImpl item : items) { removeComponent(item); } }
}
private void renderViewPorts(PdfContext context) { for (PrintComponent<?> child : getChildren()) { if (child instanceof ViewPortComponentImpl) { renderViewPort((ViewPortComponentImpl) child, context); } } }
------------------------------------------------------------------------
public Object readObjectFrom(Map row) throws PersistenceBrokerException { // allow to select a specific classdescriptor ClassDescriptor cld = selectClassDescriptor(row); return buildOrRefreshObject(row, cld, null); }
materialize a single object, described by cld, from the first row of the ResultSet rs. There are two possible strategies: 1. The persistent class defines a public constructor with arguments matching the persistent primitive attributes of the class. In this case we build an array args of arguments from rs and call Constructor.newInstance(args) to build an object. 2. The persistent class does not provide such a constructor, but only a public default constructor. In this case we create an empty instance with Class.newInstance(). This empty instance is then filled by calling Field::set(obj,getObject(matchingColumn)) for each attribute. The second strategy needs n calls to Field::set() which are much more expensive than the filling of the args array in the first strategy. client applications should therefore define adequate constructors to benefit from performance gain of the first strategy. MBAIRD: The rowreader is told what type of object to materialize, so we have to trust it is asked for the right type. It is possible someone marked an extent in the repository, but not in java, or vice versa and this could cause problems in what is returned. we *have* to be able to materialize an object from a row that has a objConcreteClass, as we retrieve ALL rows belonging to that table. The objects using the rowReader will make sure they know what they are asking for, so we don't have to make sure a descriptor is assignable from the selectClassDescriptor. This allows us to map both inherited classes and unrelated classes to the same table.
protected Object buildOrRefreshObject(Map row, ClassDescriptor targetClassDescriptor, Object targetObject) { Object result = targetObject; FieldDescriptor fmd; FieldDescriptor[] fields = targetClassDescriptor.getFieldDescriptor(true); if(targetObject == null) { // 1. create new object instance if needed result = ClassHelper.buildNewObjectInstance(targetClassDescriptor); } // 2. fill all scalar attributes of the new object for (int i = 0; i < fields.length; i++) { fmd = fields[i]; fmd.getPersistentField().set(result, row.get(fmd.getColumnName())); } if(targetObject == null) { // 3. for new build objects, invoke the initialization method for the class if one is provided Method initializationMethod = targetClassDescriptor.getInitializationMethod(); if (initializationMethod != null) { try { initializationMethod.invoke(result, NO_ARGS); } catch (Exception ex) { throw new PersistenceBrokerException("Unable to invoke initialization method:" + initializationMethod.getName() + " for class:" + m_cld.getClassOfObject(), ex); } } } return result; }
Creates an object instance according to clb, and fills its fileds width data provided by row. @param row A {@link Map} contain the Object/Row mapping for the object. @param targetClassDescriptor If the "ojbConcreteClass" feature was used, the target {@link org.apache.ojb.broker.metadata.ClassDescriptor} could differ from the descriptor this class was associated - see {@link #selectClassDescriptor}. @param targetObject If 'null' a new object instance is build, else fields of object will be refreshed. @throws PersistenceBrokerException if there ewas an error creating the new object
public void readObjectArrayFrom(ResultSetAndStatement rs_stmt, Map row) { FieldDescriptor[] fields; /* arminw: TODO: this feature doesn't work, so remove this in future */ if (m_cld.getSuperClass() != null) { /** * treeder * append super class fields if exist */ fields = m_cld.getFieldDescriptorsInHeirarchy(); } else { String ojbConcreteClass = extractOjbConcreteClass(m_cld, rs_stmt.m_rs, row); /* arminw: if multiple classes were mapped to the same table, lookup the concrete class and use these fields, attach ojbConcreteClass in row map for later use */ if(ojbConcreteClass != null) { ClassDescriptor cld = m_cld.getRepository().getDescriptorFor(ojbConcreteClass); row.put(OJB_CONCRETE_CLASS_KEY, cld.getClassOfObject()); fields = cld.getFieldDescriptor(true); } else { String ojbClass = SqlHelper.getOjbClassName(rs_stmt.m_rs); if (ojbClass != null) { ClassDescriptor cld = m_cld.getRepository().getDescriptorFor(ojbClass); row.put(OJB_CONCRETE_CLASS_KEY, cld.getClassOfObject()); fields = cld.getFieldDescriptor(true); } else { fields = m_cld.getFieldDescriptor(true); } } } readValuesFrom(rs_stmt, row, fields); }
materialize a single object, described by cld, from the first row of the ResultSet rs. There are two possible strategies: 1. The persistent class defines a public constructor with arguments matching the persistent primitive attributes of the class. In this case we build an array args of arguments from rs and call Constructor.newInstance(args) to build an object. 2. The persistent class does not provide such a constructor, but only a public default constructor. In this case we create an empty instance with Class.newInstance(). This empty instance is then filled by calling Field::set(obj,getObject(matchingColumn)) for each attribute. The second strategy needs n calls to Field::set() which are much more expensive than the filling of the args array in the first strategy. client applications should therefore define adequate constructors to benefit from performance gain of the first strategy. @throws PersistenceBrokerException if there is an error accessing the access layer
public void readPkValuesFrom(ResultSetAndStatement rs_stmt, Map row) { String ojbClass = SqlHelper.getOjbClassName(rs_stmt.m_rs); ClassDescriptor cld; if (ojbClass != null) { cld = m_cld.getRepository().getDescriptorFor(ojbClass); } else { cld = m_cld; } FieldDescriptor[] pkFields = cld.getPkFields(); readValuesFrom(rs_stmt, row, pkFields); }
/* @see RowReader#readPkValuesFrom(ResultSet, ClassDescriptor, Map) @throws PersistenceBrokerException if there is an error accessing the access layer
protected ClassDescriptor selectClassDescriptor(Map row) throws PersistenceBrokerException { ClassDescriptor result = m_cld; Class ojbConcreteClass = (Class) row.get(OJB_CONCRETE_CLASS_KEY); if(ojbConcreteClass != null) { result = m_cld.getRepository().getDescriptorFor(ojbConcreteClass); // if we can't find class-descriptor for concrete class, something wrong with mapping if (result == null) { throw new PersistenceBrokerException("Can't find class-descriptor for ojbConcreteClass '" + ojbConcreteClass + "', the main class was " + m_cld.getClassNameOfObject()); } } return result; }
Check if there is an attribute which tells us which concrete class is to be instantiated.
public String getString(String key, String defaultValue) { String ret = properties.getProperty(key); if (ret == null) { if(defaultValue == null) { logger.info("No value for key '" + key + "'"); } else { logger.debug("No value for key \"" + key + "\", using default \"" + defaultValue + "\"."); properties.put(key, defaultValue); } ret = defaultValue; } return ret; }
Returns the string value for the specified key. If no value for this key is found in the configuration <code>defaultValue</code> is returned. @param key the key @param defaultValue the default value @return the value for the key, or <code>defaultValue</code>
public String[] getStrings(String key, String defaultValue, String seperators) { StringTokenizer st = new StringTokenizer(getString(key, defaultValue), seperators); String[] ret = new String[st.countTokens()]; for (int i = 0; i < ret.length; i++) { ret[i] = st.nextToken(); } return ret; }
Gets an array of Strings from the value of the specified key, seperated by any key from <code>seperators</code>. If no value for this key is found the array contained in <code>defaultValue</code> is returned. @param key the key @param defaultValue the default Value @param seperators the seprators to be used @return the strings for the key, or the strings contained in <code>defaultValue</code> @see StringTokenizer
public int getInteger(String key, int defaultValue) { int ret; try { String tmp = properties.getProperty(key); if (tmp == null) { properties.put(key, String.valueOf(defaultValue)); logger.debug("No value for key \"" + key + "\", using default " + defaultValue + "."); return defaultValue; } ret = Integer.parseInt(tmp); } catch (NumberFormatException e) { Object wrongValue = properties.put(key, String.valueOf(defaultValue)); logger.warn( "Value \"" + wrongValue + "\" is illegal for key \"" + key + "\" (should be an integer, using default value " + defaultValue + ")"); ret = defaultValue; } return ret; }
Returns the integer value for the specified key. If no value for this key is found in the configuration or the value is not an legal integer <code>defaultValue</code> is returned. @param key the key @param defaultValue the default Value @return the value for the key, or <code>defaultValue</code>
public boolean getBoolean(String key, boolean defaultValue) { String tmp = properties.getProperty(key); if (tmp == null) { logger.debug("No value for key \"" + key + "\", using default " + defaultValue + "."); properties.put(key, String.valueOf(defaultValue)); return defaultValue; } for (int i = 0; i < trueValues.length; i++) { if (tmp.equalsIgnoreCase(trueValues[i])) { return true; } } for (int i = 0; i < falseValues.length; i++) { if (tmp.equalsIgnoreCase(falseValues[i])) { return false; } } logger.warn( "Value \"" + tmp + "\" is illegal for key \"" + key + "\" (should be a boolean, using default value " + defaultValue + ")"); return defaultValue; }
Returns the boolean value for the specified key. If no value for this key is found in the configuration or the value is not an legal boolean <code>defaultValue</code> is returned. @see #trueValues @see #falseValues @param key the key @param defaultValue the default Value @return the value for the key, or <code>defaultValue</code>
public Class getClass(String key, Class defaultValue, Class[] assignables) { String className = properties.getProperty(key); if (className == null) { if (defaultValue == null) { logger.info("No value for key '" + key + "'"); return null; } else { className = defaultValue.getName(); properties.put(key, className); logger.debug("No value for key \"" + key + "\", using default " + className + "."); return defaultValue; } } Class clazz = null; try { clazz = ClassHelper.getClass(className); } catch (ClassNotFoundException e) { clazz = defaultValue; logger.warn( "Value \"" + className + "\" is illegal for key \"" + key + "\" (should be a class, using default value " + defaultValue + ")", e); } for (int i = 0; i < assignables.length; i++) { Class assignable = assignables[i]; if (!assignable.isAssignableFrom(clazz)) { String extendsOrImplements; if (assignable.isInterface()) { extendsOrImplements = "implement the interface "; } else { extendsOrImplements = "extend the class "; } logger.error( "The specified class \"" + className + "\" does not " + extendsOrImplements + assignables[i].getName() + ", which is a requirement for the key \"" + key + "\". Using default class " + defaultValue); clazz = defaultValue; } } return clazz; }
Returns the class specified by the value for the specified key. If no value for this key is found in the configuration, no class of this name can be found or the specified class is not assignable to each class/interface in <code>assignables defaultValue</code> is returned. @param key the key @param defaultValue the default Value @param assignables classes and/or interfaces the specified class must extend/implement. @return the value for the key, or <code>defaultValue</code>
public Class getClass(String key, Class defaultValue, Class assignable) { return getClass(key, defaultValue, new Class[]{assignable}); }
Returns the class specified by the value for the specified key. If no value for this key is found in the configuration, no class of this name can be found or the specified class is not assignable <code>assignable defaultValue</code> is returned. @param key the key @param defaultValue the default Value @param assignable a classe and/or interface the specified class must extend/implement. @return the value for the key, or <code>defaultValue</code>
protected void load() { properties = new Properties(); String filename = getFilename(); try { URL url = ClassHelper.getResource(filename); if (url == null) { url = (new File(filename)).toURL(); } logger.info("Loading OJB's properties: " + url); URLConnection conn = url.openConnection(); conn.setUseCaches(false); conn.connect(); InputStream strIn = conn.getInputStream(); properties.load(strIn); strIn.close(); } catch (FileNotFoundException ex) { // [tomdz] If the filename is explicitly reset (null or empty string) then we'll // output an info message because the user did this on purpose // Otherwise, we'll output a warning if ((filename == null) || (filename.length() == 0)) { logger.info("Starting OJB without a properties file. OJB is using default settings instead."); } else { logger.warn("Could not load properties file '"+filename+"'. Using default settings!", ex); } // [tomdz] There seems to be no use of this setting ? //properties.put("valid", "false"); } catch (Exception ex) { throw new MetadataException("An error happend while loading the properties file '"+filename+"'", ex); } }
Loads the Configuration from the properties file. Loads the properties file, or uses defaults on failure. @see org.apache.ojb.broker.util.configuration.impl.ConfigurationAbstractImpl#setFilename(java.lang.String)
public static void init() { reports.clear(); Reflections reflections = new Reflections(REPORTS_PACKAGE); final Set<Class<? extends Report>> reportClasses = reflections.getSubTypesOf(Report.class); for(Class<? extends Report> c : reportClasses) { LOG.info("Report class: " + c.getName()); try { reports.add(c.newInstance()); } catch (IllegalAccessException | InstantiationException e) { LOG.error("Error while loading report implementation classes", e); } } if(LOG.isInfoEnabled()) { LOG.info(String.format("Detected %s reports", reports.size())); } }
Initializes the set of report implementation.
public InternalTile paint(InternalTile tile) throws RenderException { if (tile.getContentType().equals(VectorTileContentType.URL_CONTENT)) { if (urlBuilder != null) { if (paintGeometries) { urlBuilder.paintGeometries(paintGeometries); urlBuilder.paintLabels(false); tile.setFeatureContent(urlBuilder.getImageUrl()); } if (paintLabels) { urlBuilder.paintGeometries(false); urlBuilder.paintLabels(paintLabels); tile.setLabelContent(urlBuilder.getImageUrl()); } return tile; } } return tile; }
Painter the tile, by building a URL where the image can be found. @param tile Must be an instance of {@link InternalTile}, and must have a non-null {@link RasterUrlBuilder}. @return Returns a {@link InternalTile}.
public void addPropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener) { this.propertyChangeDelegate.addPropertyChangeListener(propertyName, listener); }
Add a new PropertyChangeListener to this node for a specific property. This functionality has been borrowed from the java.beans package, though this class has nothing to do with a bean
public void removePropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener) { this.propertyChangeDelegate.removePropertyChangeListener(propertyName, listener); }
Remove a PropertyChangeListener for a specific property from this node. This functionality has. Please note that the listener this does not remove a listener that has been added without specifying the property it is interested in.
public void setAttribute(String strKey, Object value) { this.propertyChangeDelegate.firePropertyChange(strKey, hmAttributes.put(strKey, value), value); }
Set an attribute of this node as Object. This method is backed by a HashMap, so all rules of HashMap apply to this method. Fires a PropertyChangeEvent.
public void setup() { LogActivator.logToFile(logger, this.getName(), Level.ALL); introspector = JadeAgentIntrospector.getMyInstance(this); // introspector.storeBeliefValue(this, Definitions.RECEIVED_MESSAGE_COUNT, 0); MockConfiguration configuration = (MockConfiguration) this.getArguments()[0]; messages = new ArrayList<ACLMessage>(); // Attemps to register the aggent. registered = false; try { AgentRegistration.registerAgent(this, configuration.getDFservice(), this.getLocalName()); registered = true; } catch(FIPAException e) { logger.warning("Exception while registring the ListenerMock"); logger.warning(e.getMessage()); // Will this show anything useful? } // Adds the behavior to store the messages. addBehaviour(new MessageReceiver()); }
Initializes the Agent. @see jade.core.Agent#setup()
private void modifyBeliefCount(int count){ introspector.setBeliefValue(getLocalName(), Definitions.RECEIVED_MESSAGE_COUNT, getBeliefCount()+count, null); }
Modifies the "msgCount" belief @param int - the number to add or remove
private int getBeliefCount() { Integer count = (Integer)introspector.getBeliefBase(ListenerMockAgent.this).get(Definitions.RECEIVED_MESSAGE_COUNT); if (count == null) count = 0; // Just in case, not really sure if this is necessary. return count; }
Returns the "msgCount" belief @return int - the count
@RequestMapping(value = "/reporting/f/{layerId}/{reportName}.{format}", method = RequestMethod.GET) public String reportFeatures(@PathVariable String reportName, @PathVariable String format, @PathVariable String layerId, @RequestParam(defaultValue = "EPSG:4326", required = false) String crs, @RequestParam(required = false) String filter, HttpServletRequest request, Model model) { List<InternalFeature> features; try { Filter filterObject = null; if (null != filter) { filterObject = filterService.parseFilter(filter); } features = vectorLayerService.getFeatures(layerId, geoService.getCrs2(crs), filterObject, null, VectorLayerService.FEATURE_INCLUDE_ALL); model.addAttribute(DATA_SOURCE, new InternalFeatureDataSource(features)); addParameters(model, request); } catch (GeomajasException ge) { log.error(REPORT_DATA_PROBLEM, ge); model.addAttribute(DATA_SOURCE, new InternalFeatureDataSource(new ArrayList<InternalFeature>())); } model.addAttribute(JasperReportsMultiFormatView.DEFAULT_FORMAT_KEY, format); return getView(reportName); }
Report on the features of a layer. @param reportName name of the report @param format format for the report (eg "pdf") @param layerId id of the layer @param crs coordinate reference system @param filter filter to apply on layer @param request request object for report parameters @param model mvc model @return name of the view
@RequestMapping(value = "/reporting/c/{layerId}/{reportName}.{format}", method = RequestMethod.GET) public String reportFromCache(@PathVariable String reportName, @PathVariable String format, @PathVariable String layerId, @RequestParam(required = true) String key, HttpServletRequest request, Model model) { try { VectorLayer layer = configurationService.getVectorLayer(layerId); if (null != layer) { ReportingCacheContainer container = cacheManager.get(layer, CacheCategory.RASTER, key, ReportingCacheContainer.class); addParameters(model, request); if (null != container) { model.addAttribute("map", JRImageRenderer.getInstance(container.getMapImageData())); model.addAttribute("legend", JRImageRenderer.getInstance(container.getLegendImageData())); model.addAttribute(DATA_SOURCE, getDataSource(container)); } else { model.addAttribute(DATA_SOURCE, new InternalFeatureDataSource(new ArrayList<InternalFeature>())); } } } catch (GeomajasException ge) { log.error(REPORT_DATA_PROBLEM, ge); model.addAttribute(DATA_SOURCE, new InternalFeatureDataSource(new ArrayList<InternalFeature>())); } model.addAttribute(JasperReportsMultiFormatView.DEFAULT_FORMAT_KEY, format); return getView(reportName); }
Report on the features of a layer with map image and legend, data coming from the cache. @param reportName name of the report @param format format for the report (eg "pdf") @param layerId id of the layer @param key cache key for data @param request request object for report parameters @param model mvc model @return name of the view
@SuppressWarnings("unchecked") private void addParameters(Model model, HttpServletRequest request) { for (Object objectEntry : request.getParameterMap().entrySet()) { Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) objectEntry; String key = entry.getKey(); String[] values = entry.getValue(); if (null != values && values.length > 0) { String value = values[0]; try { model.addAttribute(key, getParameter(key, value)); } catch (ParseException pe) { log.error("Could not parse parameter value {} for {}, ignoring parameter.", key, value); } catch (NumberFormatException nfe) { log.error("Could not parse parameter value {} for {}, ignoring parameter.", key, value); } } } }
Add the extra parameters which are passed as report parameters. The type of the parameter is "guessed" from the first letter of the parameter name. @param model view model @param request servlet request
private Object getParameter(String name, String value) throws ParseException, NumberFormatException { Object result = null; if (name.length() > 0) { switch (name.charAt(0)) { case 'i': if (null == value || value.length() == 0) { value = "0"; } result = new Integer(value); break; case 'f': if (name.startsWith("form")) { result = value; } else { if (null == value || value.length() == 0) { value = "0.0"; } result = new Double(value); } break; case 'd': if (null == value || value.length() == 0) { result = null; } else { SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd"); result = dateParser.parse(value); } break; case 't': if (null == value || value.length() == 0) { result = null; } else { SimpleDateFormat timeParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); result = timeParser.parse(value); } break; case 'b': result = "true".equalsIgnoreCase(value) ? Boolean.TRUE : Boolean.FALSE; break; default: result = value; } if (log.isDebugEnabled()) { if (result != null) { log.debug( "parameter " + name + " value " + result + " class " + result.getClass().getName()); } else { log.debug("parameter" + name + "is null"); } } } return result; }
Convert a query parameter to the correct object type based on the first letter of the name. @param name parameter name @param value parameter value @return parameter object as @throws ParseException value could not be parsed @throws NumberFormatException value could not be parsed
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(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); lblProductName = new javax.swing.JLabel(); tfProductName = new javax.swing.JTextField(); lblProductVersion = new javax.swing.JLabel(); tfProductVersion = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); lblCatalogTerm = new javax.swing.JLabel(); tfCatalogTerm = new javax.swing.JTextField(); lblCatalogSeparator = new javax.swing.JLabel(); tfCatalogSeparator = new javax.swing.JTextField(); lblSupportsCatalogInIndex = new javax.swing.JLabel(); tfSupportsCatalogInIndex = new javax.swing.JTextField(); lblSupportsCatalogInDML = new javax.swing.JLabel(); tfSupportsCatalogInDML = new javax.swing.JTextField(); lblSupportsCatalogInPrivilegeDefinitions = new javax.swing.JLabel(); tfSupportsCatalogInPrivilegeDefinitions = new javax.swing.JTextField(); lblSupportsCatalogInProcedureCalls = new javax.swing.JLabel(); tfSupportsCatalogInProcedureCalls = new javax.swing.JTextField(); lblSupportsCatalogInTableDefinitions = new javax.swing.JLabel(); tfSupportsCatalogInTableDefinitions = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); lblSchemaTerm = new javax.swing.JLabel(); tfSchemaTerm = 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(19, 2)); lblEnabled.setText("enabled"); lblEnabled.setDisplayedMnemonic('e'); 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); jPanel1.add(jLabel1); jPanel1.add(jLabel2); lblProductName.setText("Database Product Name:"); jPanel1.add(lblProductName); tfProductName.setEditable(false); tfProductName.setText("jTextField1"); tfProductName.setBorder(null); jPanel1.add(tfProductName); lblProductVersion.setText("Database Product Version:"); jPanel1.add(lblProductVersion); tfProductVersion.setEditable(false); tfProductVersion.setText("jTextField2"); tfProductVersion.setBorder(null); jPanel1.add(tfProductVersion); jPanel1.add(jLabel8); jPanel1.add(jLabel7); lblCatalogTerm.setText("Catalog Term:"); lblCatalogTerm.setLabelFor(tfCatalogTerm); jPanel1.add(lblCatalogTerm); tfCatalogTerm.setEditable(false); tfCatalogTerm.setText("jTextField1"); tfCatalogTerm.setBorder(null); jPanel1.add(tfCatalogTerm); lblCatalogSeparator.setText("Catalog Separator:"); lblCatalogSeparator.setLabelFor(tfCatalogSeparator); jPanel1.add(lblCatalogSeparator); tfCatalogSeparator.setEditable(false); tfCatalogSeparator.setText("jTextField1"); tfCatalogSeparator.setBorder(null); jPanel1.add(tfCatalogSeparator); lblSupportsCatalogInIndex.setText("supports Catalog in Index:"); lblSupportsCatalogInIndex.setLabelFor(tfSupportsCatalogInIndex); jPanel1.add(lblSupportsCatalogInIndex); tfSupportsCatalogInIndex.setEditable(false); tfSupportsCatalogInIndex.setText("jTextField1"); tfSupportsCatalogInIndex.setBorder(null); jPanel1.add(tfSupportsCatalogInIndex); lblSupportsCatalogInDML.setText("supports Catalog in DML:"); lblSupportsCatalogInDML.setLabelFor(lblSupportsCatalogInDML); jPanel1.add(lblSupportsCatalogInDML); tfSupportsCatalogInDML.setEditable(false); tfSupportsCatalogInDML.setText("jTextField1"); tfSupportsCatalogInDML.setBorder(null); jPanel1.add(tfSupportsCatalogInDML); lblSupportsCatalogInPrivilegeDefinitions.setText("supports Catalog in Privilege Definitions:"); lblSupportsCatalogInPrivilegeDefinitions.setLabelFor(tfSupportsCatalogInPrivilegeDefinitions); jPanel1.add(lblSupportsCatalogInPrivilegeDefinitions); tfSupportsCatalogInPrivilegeDefinitions.setEditable(false); tfSupportsCatalogInPrivilegeDefinitions.setText("jTextField1"); tfSupportsCatalogInPrivilegeDefinitions.setBorder(null); jPanel1.add(tfSupportsCatalogInPrivilegeDefinitions); lblSupportsCatalogInProcedureCalls.setText("supports Catalog in Procedure Calls:"); lblSupportsCatalogInProcedureCalls.setLabelFor(tfSupportsCatalogInProcedureCalls); jPanel1.add(lblSupportsCatalogInProcedureCalls); tfSupportsCatalogInProcedureCalls.setEditable(false); tfSupportsCatalogInProcedureCalls.setText("jTextField1"); tfSupportsCatalogInProcedureCalls.setBorder(null); jPanel1.add(tfSupportsCatalogInProcedureCalls); lblSupportsCatalogInTableDefinitions.setText("supports Catalog in Table Definitions:"); lblSupportsCatalogInTableDefinitions.setLabelFor(tfSupportsCatalogInTableDefinitions); jPanel1.add(lblSupportsCatalogInTableDefinitions); tfSupportsCatalogInTableDefinitions.setEditable(false); tfSupportsCatalogInTableDefinitions.setText("jTextField1"); tfSupportsCatalogInTableDefinitions.setBorder(null); jPanel1.add(tfSupportsCatalogInTableDefinitions); jPanel1.add(jLabel4); jPanel1.add(jLabel3); lblSchemaTerm.setText("Schema Term:"); lblSchemaTerm.setLabelFor(tfSchemaTerm); jPanel1.add(lblSchemaTerm); tfSchemaTerm.setEditable(false); tfSchemaTerm.setText("jTextField1"); tfSchemaTerm.setBorder(null); jPanel1.add(tfSchemaTerm); 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.
public void setModel (PropertySheetModel pm) { if (pm instanceof org.apache.ojb.tools.mapping.reversedb.DBMeta) { this.aMeta = (org.apache.ojb.tools.mapping.reversedb.DBMeta)pm; this.readValuesFromMeta(); } else throw new IllegalArgumentException(); }
GEN-LAST:event_formComponentShown
public Configuration getInfinispanConfiguration(ConfigurationBuilder baseBuilder) { ConfigurationChildBuilder builder = baseBuilder; if (null == builder) { builder = new ConfigurationBuilder(); } builder = builder.locking().useLockStriping(false); if (EVICTION_NOT_SET != evictionWakeUpInterval) { builder = builder.expiration().wakeUpInterval(evictionWakeUpInterval); } if (null != evictionStrategy) { builder = builder.eviction().strategy(evictionStrategy); } if (null != isolationLevel) { builder = builder.locking().isolationLevel(isolationLevel); } if (null != location) { SingleFileStoreConfigurationBuilder sfBuilder = builder.persistence().addSingleFileStore(); sfBuilder.location(location); if (level2MaxEntries > 0) { sfBuilder.maxEntries(level2MaxEntries); } builder = sfBuilder; } if (maxEntries > 0) { builder.eviction().maxEntries(maxEntries); } if (EXPIRATION_NOT_SET != expiration) { builder = builder.expiration().maxIdle(expiration < 0 ? -1L : expiration * MILLISECONDS_PER_MINUTE); } return builder.build(); }
{@inheritDoc} @since 2.0.0
public void setLevel2CacheLocation(String locationExpr) { if (null != locationExpr) { // property name handling in location String location = propertyReplace(locationExpr); // create caching directory File dir = new File(location); if (!dir.isDirectory()) { if (dir.exists()) { log.error("Location {} for 2nd level cache should be a directory.", location); throw new RuntimeException("Invalid location for setLevel2CacheLocation, " + location + //NOPMD " has to be a directory."); //NOPMD } else { if (!dir.mkdirs()) { log.warn("Directory {} for 2nd level cache could not be created.", location); } } } this.location = location; } }
Set the location for the second level cache. This needs to be a directory which is created if needed. <p/> The location can point to a system property by using the "${propertyName}" notation. If the property does not exist it is replaced by a temporary directory. The property needs to be at the start of the string (so "${cache.dir}/rebuild" is ok but "/tmp/${hostname}" is not. Note that the temporary directory is not automatically removed! @param locationExpr directory location for second level cache of items