code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public static PersistenceBrokerSQLException generateException(String message, SQLException ex, String sql, Logger logger) { return generateException(message, ex, sql, null, null, logger, null); }
Method which support the conversion of {@link java.sql.SQLException} to OJB's runtime exception (with additional message details). @param message The error message to use, if <em>null</em> a standard message is used. @param ex The exception to convert (mandatory). @param sql The used sql-statement or <em>null</em>. @param logger The {@link org.apache.ojb.broker.util.logging.Logger} to log an detailed message to the specified {@link org.apache.ojb.broker.util.logging.Logger} or <em>null</em> to skip logging message. @return A new created {@link org.apache.ojb.broker.PersistenceBrokerSQLException} based on the specified arguments.
public static PersistenceBrokerSQLException generateException(SQLException ex, String sql, ClassDescriptor cld, Logger logger, Object obj) { return generateException(ex, sql, cld, null, logger, obj); }
Method which support the conversion of {@link java.sql.SQLException} to OJB's runtime exception (with additional message details). @param ex The exception to convert (mandatory). @param sql The used sql-statement or <em>null</em>. @param cld The {@link org.apache.ojb.broker.metadata.ClassDescriptor} of the target object or <em>null</em>. @param logger The {@link org.apache.ojb.broker.util.logging.Logger} to log an detailed message to the specified {@link org.apache.ojb.broker.util.logging.Logger} or <em>null</em> to skip logging message. @param obj The target object or <em>null</em>. @return A new created {@link org.apache.ojb.broker.PersistenceBrokerSQLException} based on the specified arguments.
public static PersistenceBrokerSQLException generateException(String message, SQLException ex, String sql, ClassDescriptor cld, ValueContainer[] values, Logger logger, Object obj) { /* X/OPEN codes within class 23: 23000 INTEGRITY CONSTRAINT VIOLATION 23001 RESTRICT VIOLATION 23502 NOT NULL VIOLATION 23503 FOREIGN KEY VIOLATION 23505 UNIQUE VIOLATION 23514 CHECK VIOLATION */ String eol = SystemUtils.LINE_SEPARATOR; StringBuffer msg = new StringBuffer(eol); eol += "* "; if(ex instanceof BatchUpdateException) { BatchUpdateException tmp = (BatchUpdateException) ex; if(message != null) { msg.append("* ").append(message); } else { msg.append("* BatchUpdateException during execution of sql-statement:"); } msg.append(eol).append("Batch update count is '").append(tmp.getUpdateCounts()).append("'"); } else if(ex instanceof SQLWarning) { if(message != null) { msg.append("* ").append(message); } else { msg.append("* SQLWarning during execution of sql-statement:"); } } else { if(message != null) { msg.append("* ").append(message); } else { msg.append("* SQLException during execution of sql-statement:"); } } if(sql != null) { msg.append(eol).append("sql statement was '").append(sql).append("'"); } String stateCode = null; if(ex != null) { msg.append(eol).append("Exception message is [").append(ex.getMessage()).append("]"); msg.append(eol).append("Vendor error code [").append(ex.getErrorCode()).append("]"); msg.append(eol).append("SQL state code ["); stateCode = ex.getSQLState(); if("23000".equalsIgnoreCase(stateCode)) msg.append(stateCode).append("=INTEGRITY CONSTRAINT VIOLATION"); else if("23001".equalsIgnoreCase(stateCode)) msg.append(stateCode).append("=RESTRICT VIOLATION"); else if("23502".equalsIgnoreCase(stateCode)) msg.append(stateCode).append("=NOT NULL VIOLATION"); else if("23503".equalsIgnoreCase(stateCode)) msg.append(stateCode).append("=FOREIGN KEY VIOLATION"); else if("23505".equalsIgnoreCase(stateCode)) msg.append(stateCode).append("=UNIQUE VIOLATION"); else if("23514".equalsIgnoreCase(stateCode)) msg.append(stateCode).append("=CHECK VIOLATION"); else msg.append(stateCode); msg.append("]"); } if(cld != null) { msg.append(eol).append("Target class is '") .append(cld.getClassNameOfObject()) .append("'"); FieldDescriptor[] fields = cld.getPkFields(); msg.append(eol).append("PK of the target object is ["); for(int i = 0; i < fields.length; i++) { try { if(i > 0) msg.append(", "); msg.append(fields[i].getPersistentField().getName()); if(obj != null) { msg.append("="); msg.append(fields[i].getPersistentField().get(obj)); } } catch(Exception ignore) { msg.append(" PK field build FAILED! "); } } msg.append("]"); } if(values != null) { msg.append(eol).append(values.length).append(" values performed in statement: ").append(eol); for(int i = 0; i < values.length; i++) { ValueContainer value = values[i]; msg.append("["); msg.append("jdbcType=").append(JdbcTypesHelper.getSqlTypeAsString(value.getJdbcType().getType())); msg.append(", value=").append(value.getValue()); msg.append("]"); } } if(obj != null) { msg.append(eol).append("Source object: "); try { msg.append(obj.toString()); } catch(Exception e) { msg.append(obj.getClass()); } } // message string for PB exception String shortMsg = msg.toString(); if(ex != null) { // add causing stack trace Throwable rootCause = ExceptionUtils.getRootCause(ex); if(rootCause == null) rootCause = ex; msg.append(eol).append("The root stack trace is --> "); String rootStack = ExceptionUtils.getStackTrace(rootCause); msg.append(eol).append(rootStack); } msg.append(SystemUtils.LINE_SEPARATOR).append("**"); // log error message if(logger != null) logger.error(msg.toString()); // throw a specific type of runtime exception for a key constraint. if("23000".equals(stateCode) || "23505".equals(stateCode)) { throw new KeyConstraintViolatedException(shortMsg, ex); } else { throw new PersistenceBrokerSQLException(shortMsg, ex); } }
Method which support the conversion of {@link java.sql.SQLException} to OJB's runtime exception (with additional message details). @param message The error message to use, if <em>null</em> a standard message is used. @param ex The exception to convert (mandatory). @param sql The used sql-statement or <em>null</em>. @param cld The {@link org.apache.ojb.broker.metadata.ClassDescriptor} of the target object or <em>null</em>. @param values The values set in prepared statement or <em>null</em>. @param logger The {@link org.apache.ojb.broker.util.logging.Logger} to log an detailed message to the specified {@link org.apache.ojb.broker.util.logging.Logger} or <em>null</em> to skip logging message. @param obj The target object or <em>null</em>. @return A new created {@link org.apache.ojb.broker.PersistenceBrokerSQLException} based on the specified arguments.
@Override public void sendMessageToAgents(String[] agent_name, String msgtype, Object message_content, Connector connector) { Agent messenger = (Agent) connector.getMessageService(); JadeAgentIntrospector introspector = (JadeAgentIntrospector) PlatformSelector.getAgentIntrospector("jade"); ACLMessage msg = null; if(message_content instanceof ACLMessage) { msg = (ACLMessage) message_content; } else if (message_content instanceof String) { msg = new ACLMessage(ACLMessage.getInteger(msgtype)); msg.setContent( (String) message_content); } else { connector.getLogger().warning("Incorrect message_content value. It should be a ACLMessage or a String."); } for (String name : agent_name) { Agent agent = introspector.getAgent(name); AID aid = agent.getAID(); msg.addReceiver(aid); connector.getLogger().finer("Receiver added to the message..."); } messenger.send(msg); connector.getLogger().finer("Message sent..."); }
/* (non-Javadoc) @see es.upm.dit.gsi.beast.platform.Messenger#sendMessageToAgents(java.lang.String[], java.lang.String, java.lang.Object, es.upm.dit.gsi.beast.platform.Connector)
@Override public void sendMessageToAgentsWithExtraProperties(String[] agent_name, String msgtype, Object message_content, ArrayList<Object> properties, Connector connector) { connector.getLogger().warning("Non suported method for Jade Platform. There is no extra properties."); throw new java.lang.UnsupportedOperationException("Non suported method for Jade Platform. There is no extra properties."); }
/* (non-Javadoc) @see es.upm.dit.gsi.beast.platform.Messenger#sendMessageToAgentsWithExtraProperties(java.lang.String[], java.lang.String, java.lang.Object, java.util.ArrayList, es.upm.dit.gsi.beast.platform.Connector)
@PostConstruct protected void buildCopyrightMap() { if (null == declaredPlugins) { return; } // go over all plug-ins, adding copyright info, avoiding duplicates (on object key) for (PluginInfo plugin : declaredPlugins.values()) { for (CopyrightInfo copyright : plugin.getCopyrightInfo()) { String key = copyright.getKey(); String msg = copyright.getKey() + ": " + copyright.getCopyright() + " : licensed as " + copyright.getLicenseName() + ", see " + copyright.getLicenseUrl(); if (null != copyright.getSourceUrl()) { msg += " source " + copyright.getSourceUrl(); } if (!copyrightMap.containsKey(key)) { log.info(msg); copyrightMap.put(key, copyright); } } } }
Build copyright map once.
public void storeIfNew(final DbArtifact fromClient) { final DbArtifact existing = repositoryHandler.getArtifact(fromClient.getGavc()); if(existing != null){ existing.setLicenses(fromClient.getLicenses()); store(existing); } if(existing == null){ store(fromClient); } }
If the Artifact does not exist, it will add it to the database. Nothing if it already exit. @param fromClient DbArtifact
public void addLicense(final String gavc, final String licenseId) { final DbArtifact dbArtifact = getArtifact(gavc); // Try to find an existing license that match the new one final LicenseHandler licenseHandler = new LicenseHandler(repositoryHandler); final DbLicense license = licenseHandler.resolve(licenseId); // If there is no existing license that match this one let's use the provided value but // only if the artifact has no license yet. Otherwise it could mean that users has already // identify the license manually. if(license == null){ if(dbArtifact.getLicenses().isEmpty()){ LOG.warn("Add reference to a non existing license called " + licenseId + " in artifact " + dbArtifact.getGavc()); repositoryHandler.addLicenseToArtifact(dbArtifact, licenseId); } } // Add only if the license is not already referenced else if(!dbArtifact.getLicenses().contains(license.getName())){ repositoryHandler.addLicenseToArtifact(dbArtifact, license.getName()); } }
Adds a license to an artifact if the license exist into the database @param gavc String @param licenseId String
public List<String> getArtifactVersions(final String gavc) { final DbArtifact artifact = getArtifact(gavc); return repositoryHandler.getArtifactVersions(artifact); }
Returns a the list of available version of an artifact @param gavc String @return List<String>
public String getArtifactLastVersion(final String gavc) { final List<String> versions = getArtifactVersions(gavc); final VersionsHandler versionHandler = new VersionsHandler(repositoryHandler); final String viaCompare = versionHandler.getLastVersion(versions); if (viaCompare != null) { return viaCompare; } // // These versions cannot be compared // Let's use the Collection.max() method by default, so goingo for a fallback // mechanism. // LOG.info("The versions cannot be compared"); return Collections.max(versions); }
Returns the last available version of an artifact @param gavc String @return String
public DbArtifact getArtifact(final String gavc) { final DbArtifact artifact = repositoryHandler.getArtifact(gavc); if(artifact == null){ throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) .entity("Artifact " + gavc + " does not exist.").build()); } return artifact; }
Return an artifact regarding its gavc @param gavc String @return DbArtifact
public DbOrganization getOrganization(final DbArtifact dbArtifact) { final DbModule module = getModule(dbArtifact); if(module == null || module.getOrganization() == null){ return null; } return repositoryHandler.getOrganization(module.getOrganization()); }
Returns the Organization that produce this artifact or null if there is none @param dbArtifact DbArtifact @return DbOrganization
public void updateDownLoadUrl(final String gavc, final String downLoadUrl) { final DbArtifact artifact = getArtifact(gavc); repositoryHandler.updateDownloadUrl(artifact, downLoadUrl); }
Update artifact download url of an artifact @param gavc String @param downLoadUrl String
public void updateProvider(final String gavc, final String provider) { final DbArtifact artifact = getArtifact(gavc); repositoryHandler.updateProvider(artifact, provider); }
Update artifact provider @param gavc String @param provider String
public void updateDoNotUse(final String gavc, final Boolean doNotUse) { final DbArtifact artifact = getArtifact(gavc); repositoryHandler.updateDoNotUse(artifact, doNotUse); }
Add "DO_NOT_USE" flag to an artifact @param gavc String @param doNotUse Boolean
public List<DbModule> getAncestors(final String gavc, final FiltersHolder filters) { final DbArtifact dbArtifact = getArtifact(gavc); return repositoryHandler.getAncestors(dbArtifact, filters); }
Return the list of module that uses the targeted artifact @param gavc String @param filters FiltersHolder @return List<DbModule>
public List<DbLicense> getArtifactLicenses(final String gavc, final FiltersHolder filters) { final DbArtifact artifact = getArtifact(gavc); final List<DbLicense> licenses = new ArrayList<>(); for(final String name: artifact.getLicenses()){ final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(name); // Here is a license to identify if(matchingLicenses.isEmpty()){ final DbLicense notIdentifiedLicense = new DbLicense(); notIdentifiedLicense.setName(name); licenses.add(notIdentifiedLicense); } else { matchingLicenses.stream() .filter(filters::shouldBeInReport) .forEach(licenses::add); } } return licenses; }
Return the list of licenses attached to an artifact @param gavc String @param filters FiltersHolder @return List<DbLicense>
public void addLicenseToArtifact(final String gavc, final String licenseId) { final DbArtifact dbArtifact = getArtifact(gavc); // Don't need to access the DB if the job is already done if(dbArtifact.getLicenses().contains(licenseId)){ return; } final DbLicense dbLicense = repositoryHandler.getLicense(licenseId); if(dbLicense == null){ throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) .entity("License " + licenseId + " does not exist.").build()); } repositoryHandler.addLicenseToArtifact(dbArtifact, dbLicense.getName()); }
Add a license to an artifact @param gavc String @param licenseId String
public void removeLicenseFromArtifact(final String gavc, final String licenseId) { final DbArtifact dbArtifact = getArtifact(gavc); // // The artifact may not have the exact string associated with it, but rather one // matching license regexp expression. // repositoryHandler.removeLicenseFromArtifact(dbArtifact, licenseId, licenseMatcher); }
Remove a license from an artifact @param gavc String The artifact GAVC @param licenseId String The license id to be removed.
public String getModuleJenkinsJobInfo(final DbArtifact dbArtifact) { final DbModule module = getModule(dbArtifact); if(module == null){ return ""; } final String jenkinsJobUrl = module.getBuildInfo().get("jenkins-job-url"); if(jenkinsJobUrl == null){ return ""; } return jenkinsJobUrl; }
k Returns a list of artifact regarding the filters @return List<DbArtifact>
static FieldCriteria buildEqualToCriteria(Object anAttribute, Object aValue, UserAlias anAlias) { return new FieldCriteria(anAttribute, aValue, EQUAL, anAlias); }
static FieldCriteria buildEqualToCriteria(Object anAttribute, Object aValue, String anAlias)
static FieldCriteria buildNotEqualToCriteria(Object anAttribute, Object aValue, UserAlias anAlias) { return new FieldCriteria(anAttribute, aValue, NOT_EQUAL, anAlias); }
static FieldCriteria buildNotEqualToCriteria(Object anAttribute, Object aValue, String anAlias)
static FieldCriteria buildGreaterCriteria(Object anAttribute, Object aValue, UserAlias anAlias) { return new FieldCriteria(anAttribute, aValue,GREATER, anAlias); }
static FieldCriteria buildGreaterCriteria(Object anAttribute, Object aValue, String anAlias)
static FieldCriteria buildNotGreaterCriteria(Object anAttribute, Object aValue, UserAlias anAlias) { return new FieldCriteria(anAttribute, aValue, NOT_GREATER, anAlias); }
static FieldCriteria buildNotGreaterCriteria(Object anAttribute, Object aValue, String anAlias)
static FieldCriteria buildLessCriteria(Object anAttribute, Object aValue, UserAlias anAlias) { return new FieldCriteria(anAttribute, aValue, LESS, anAlias); }
static FieldCriteria buildLessCriteria(Object anAttribute, Object aValue, String anAlias)
static FieldCriteria buildNotLessCriteria(Object anAttribute, Object aValue, UserAlias anAlias) { return new FieldCriteria(anAttribute, aValue, NOT_LESS, anAlias); }
static FieldCriteria buildNotLessCriteria(Object anAttribute, Object aValue, String anAlias)
public CollectionDescriptorDef getRemoteCollection() { if (!hasProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE)) { return null; } ModelDef modelDef = (ModelDef)getOwner().getOwner(); String elementClassName = getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF); ClassDescriptorDef elementClass = modelDef.getClass(elementClassName); String indirTable = getProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE); boolean hasRemoteKey = hasProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY); String remoteKey = getProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY); CollectionDescriptorDef remoteCollDef = null; // find the collection in the element class that has the same indirection table for (Iterator it = elementClass.getCollections(); it.hasNext();) { remoteCollDef = (CollectionDescriptorDef)it.next(); if (indirTable.equals(remoteCollDef.getProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE)) && (this != remoteCollDef) && (!hasRemoteKey || CommaListIterator.sameLists(remoteKey, remoteCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY)))) { return remoteCollDef; } } return null; }
Tries to find the corresponding remote collection for this m:n collection. @return The corresponding remote collection
public static String getDefaultJdbcTypeFor(String javaType) { return _jdbcMappings.containsKey(javaType) ? (String)_jdbcMappings.get(javaType) : JDBC_DEFAULT_TYPE; }
Returns the default jdbc type for the given java type. @param javaType The qualified java type @return The default jdbc type
public static String getDefaultConversionFor(String javaType) { return _jdbcConversions.containsKey(javaType) ? (String)_jdbcConversions.get(javaType) : null; }
Returns the default conversion for the given java type. @param javaType The qualified java type @return The default conversion or <code>null</code> if there is no default conversion for the type
protected Query buildPrefetchQuery(Collection ids) { CollectionDescriptor cds = getCollectionDescriptor(); String[] indFkCols = getFksToThisClass(); String[] indItemFkCols = getFksToItemClass(); FieldDescriptor[] itemPkFields = getItemClassDescriptor().getPkFields(); Criteria crit = buildPrefetchCriteria(ids, indFkCols, indItemFkCols, itemPkFields); // BRJ: do not use distinct: // // ORA-22901 cannot compare nested table or VARRAY or LOB attributes of an object type // Cause: Comparison of nested table or VARRAY or LOB attributes of an // object type was attempted in the absence of a MAP or ORDER method. // Action: Define a MAP or ORDER method for the object type. // // Without the distinct the resultset may contain duplicate rows return new QueryByMtoNCriteria(cds.getItemClass(), cds.getIndirectionTable(), crit, false); }
Build the prefetch query for a M-N relationship, The query looks like the following sample : <br> <pre> crit = new Criteria(); crit.addIn("PERSON_PROJECT.PROJECT_ID", ids); crit.addEqualToField("id","PERSON_PROJECT.PERSON_ID"); qry = new QueryByMtoNCriteria(Person.class, "PERSON_PROJECT", crit, true); </pre> @param ids Collection containing all identities of objects of the M side @return the prefetch Query
protected Query buildMtoNImplementorQuery(Collection ids) { String[] indFkCols = getFksToThisClass(); String[] indItemFkCols = getFksToItemClass(); FieldDescriptor[] pkFields = getOwnerClassDescriptor().getPkFields(); FieldDescriptor[] itemPkFields = getItemClassDescriptor().getPkFields(); String[] cols = new String[indFkCols.length + indItemFkCols.length]; int[] jdbcTypes = new int[indFkCols.length + indItemFkCols.length]; // concatenate the columns[] System.arraycopy(indFkCols, 0, cols, 0, indFkCols.length); System.arraycopy(indItemFkCols, 0, cols, indFkCols.length, indItemFkCols.length); Criteria crit = buildPrefetchCriteria(ids, indFkCols, indItemFkCols, itemPkFields); // determine the jdbcTypes of the pks for (int i = 0; i < pkFields.length; i++) { jdbcTypes[i] = pkFields[i].getJdbcType().getType(); } for (int i = 0; i < itemPkFields.length; i++) { jdbcTypes[pkFields.length + i] = itemPkFields[i].getJdbcType().getType(); } ReportQueryByMtoNCriteria q = new ReportQueryByMtoNCriteria(getItemClassDescriptor().getClassOfObject(), cols, crit, false); q.setIndirectionTable(getCollectionDescriptor().getIndirectionTable()); q.setJdbcTypes(jdbcTypes); CollectionDescriptor cds = getCollectionDescriptor(); //check if collection must be ordered if (!cds.getOrderBy().isEmpty()) { Iterator iter = cds.getOrderBy().iterator(); while (iter.hasNext()) { q.addOrderBy((FieldHelper) iter.next()); } } return q; }
Build a query to read the mn-implementors @param ids
private String[] getFksToThisClass() { String indTable = getCollectionDescriptor().getIndirectionTable(); String[] fks = getCollectionDescriptor().getFksToThisClass(); String[] result = new String[fks.length]; for (int i = 0; i < result.length; i++) { result[i] = indTable + "." + fks[i]; } return result; }
prefix the this class fk columns with the indirection table
protected Query[] buildMtoNImplementorQueries(Collection owners, Collection children) { ClassDescriptor cld = getOwnerClassDescriptor(); PersistenceBroker pb = getBroker(); //Class topLevelClass = pb.getTopLevelClass(cld.getClassOfObject()); //BrokerHelper helper = pb.serviceBrokerHelper(); Collection queries = new ArrayList(owners.size()); Collection idsSubset = new HashSet(owners.size()); //Object[] fkValues; Object owner; Identity id; Iterator iter = owners.iterator(); while (iter.hasNext()) { owner = iter.next(); id = pb.serviceIdentity().buildIdentity(cld, owner); idsSubset.add(id); if (idsSubset.size() == pkLimit) { queries.add(buildMtoNImplementorQuery(idsSubset)); idsSubset.clear(); } } if (idsSubset.size() > 0) { queries.add(buildMtoNImplementorQuery(idsSubset)); } return (Query[]) queries.toArray(new Query[queries.size()]); }
Build the multiple queries for one relationship because of limitation of IN(...) @param owners Collection containing all objects of the ONE side
private Criteria buildPrefetchCriteria(Collection ids, String[] fkCols, String[] itemFkCols, FieldDescriptor[] itemPkFields) { if (fkCols.length == 1 && itemFkCols.length == 1) { return buildPrefetchCriteriaSingleKey(ids, fkCols[0], itemFkCols[0], itemPkFields[0]); } else { return buildPrefetchCriteriaMultipleKeys(ids, fkCols, itemFkCols, itemPkFields); } }
Build the prefetch criteria @param ids Collection of identities of M side @param fkCols indirection table fks to this class @param itemFkCols indirection table fks to item class @param itemPkFields
private Criteria buildPrefetchCriteriaSingleKey(Collection ids, String fkCol, String itemFkCol, FieldDescriptor itemPkField) { Criteria crit = new Criteria(); ArrayList values = new ArrayList(ids.size()); Iterator iter = ids.iterator(); Identity id; while (iter.hasNext()) { id = (Identity) iter.next(); values.add(id.getPrimaryKeyValues()[0]); } switch (values.size()) { case 0 : break; case 1 : crit.addEqualTo(fkCol, values.get(0)); break; default : // create IN (...) for the single key field crit.addIn(fkCol, values); break; } crit.addEqualToField(itemPkField.getAttributeName(), itemFkCol); return crit; }
Build the prefetch criteria @param ids Collection of identities of M side @param fkCol indirection table fks to this class @param itemFkCol indirection table fks to item class @param itemPkField @return the Criteria
private Criteria buildPrefetchCriteriaMultipleKeys(Collection ids, String[] fkCols, String[] itemFkCols, FieldDescriptor[] itemPkFields) { Criteria crit = new Criteria(); Criteria critValue = new Criteria(); Iterator iter = ids.iterator(); for (int i = 0; i < itemPkFields.length; i++) { crit.addEqualToField(itemPkFields[i].getAttributeName(), itemFkCols[i]); } while (iter.hasNext()) { Criteria c = new Criteria(); Identity id = (Identity) iter.next(); Object[] val = id.getPrimaryKeyValues(); for (int i = 0; i < val.length; i++) { if (val[i] == null) { c.addIsNull(fkCols[i]); } else { c.addEqualTo(fkCols[i], val[i]); } } critValue.addOrCriteria(c); } crit.addAndCriteria(critValue); return crit; }
Build the prefetch criteria @param ids Collection of identities of M side @param fkCols indirection table fks to this class @param itemFkCols indirection table fks to item class @param itemPkFields @return the Criteria
private FieldConversion[] getPkFieldConversion(ClassDescriptor cld) { FieldDescriptor[] pks = cld.getPkFields(); FieldConversion[] fc = new FieldConversion[pks.length]; for (int i= 0; i < pks.length; i++) { fc[i] = pks[i].getFieldConversion(); } return fc; }
Answer the FieldConversions for the PkFields @param cld @return the pk FieldConversions
private Object[] convert(FieldConversion[] fcs, Object[] values) { Object[] convertedValues = new Object[values.length]; for (int i= 0; i < values.length; i++) { convertedValues[i] = fcs[i].sqlToJava(values[i]); } return convertedValues; }
Convert the Values using the FieldConversion.sqlToJava @param fcs @param values
protected void associateBatched(Collection owners, Collection children, Collection mToNImplementors) { CollectionDescriptor cds = getCollectionDescriptor(); PersistentField field = cds.getPersistentField(); PersistenceBroker pb = getBroker(); Class ownerTopLevelClass = pb.getTopLevelClass(getOwnerClassDescriptor().getClassOfObject()); Class childTopLevelClass = pb.getTopLevelClass(getItemClassDescriptor().getClassOfObject()); Class collectionClass = cds.getCollectionClass(); // this collection type will be used: HashMap childMap = new HashMap(); HashMap ownerIdsToLists = new HashMap(); FieldConversion[] ownerFc = getPkFieldConversion(getOwnerClassDescriptor()); FieldConversion[] childFc = getPkFieldConversion(getItemClassDescriptor()); // initialize the owner list map for (Iterator it = owners.iterator(); it.hasNext();) { Object owner = it.next(); Identity oid = pb.serviceIdentity().buildIdentity(owner); ownerIdsToLists.put(oid, new ArrayList()); } // build the children map for (Iterator it = children.iterator(); it.hasNext();) { Object child = it.next(); Identity oid = pb.serviceIdentity().buildIdentity(child); childMap.put(oid, child); } int ownerPkLen = getOwnerClassDescriptor().getPkFields().length; int childPkLen = getItemClassDescriptor().getPkFields().length; Object[] ownerPk = new Object[ownerPkLen]; Object[] childPk = new Object[childPkLen]; // build list of children based on m:n implementors for (Iterator it = mToNImplementors.iterator(); it.hasNext();) { Object[] mToN = (Object[]) it.next(); System.arraycopy(mToN, 0, ownerPk, 0, ownerPkLen); System.arraycopy(mToN, ownerPkLen, childPk, 0, childPkLen); // BRJ: apply the FieldConversions, OJB296 ownerPk = convert(ownerFc, ownerPk); childPk = convert(childFc, childPk); Identity ownerId = pb.serviceIdentity().buildIdentity(null, ownerTopLevelClass, ownerPk); Identity childId = pb.serviceIdentity().buildIdentity(null, childTopLevelClass, childPk); // Identities may not be equal due to type-mismatch Collection list = (Collection) ownerIdsToLists.get(ownerId); Object child = childMap.get(childId); list.add(child); } // connect children list to owners for (Iterator it = owners.iterator(); it.hasNext();) { Object result; Object owner = it.next(); Identity ownerId = pb.serviceIdentity().buildIdentity(owner); List list = (List) ownerIdsToLists.get(ownerId); if ((collectionClass == null) && field.getType().isArray()) { int length = list.size(); Class itemtype = field.getType().getComponentType(); result = Array.newInstance(itemtype, length); for (int j = 0; j < length; j++) { Array.set(result, j, list.get(j)); } } else { ManageableCollection col = createCollection(cds, collectionClass); for (Iterator it2 = list.iterator(); it2.hasNext();) { col.ojbAdd(it2.next()); } result = col; } Object value = field.get(owner); if ((value instanceof CollectionProxyDefaultImpl) && (result instanceof Collection)) { ((CollectionProxyDefaultImpl) value).setData((Collection) result); } else { field.set(owner, result); } } }
associate the batched Children with their owner object loop over children <br><br> BRJ: There is a potential problem with the type of the pks used to build the Identities. When creating an Identity for the owner, the type of pk is defined by the instvars representing the pk. When creating the Identity based on the mToNImplementor the type of the pk is defined by the jdbc-type of field-descriptor of the referenced class. This type mismatch results in Identities not being equal. Integer[] {10,20,30} is not equal Long[] {10,20,30} <br><br> This problem is documented in defect OJB296. The conversion of the keys of the mToNImplementor should solve this problem.
public void displayUseCases() { System.out.println(); for (int i = 0; i < useCases.size(); i++) { System.out.println("[" + i + "] " + ((UseCase) useCases.get(i)).getDescription()); } }
Disply available use cases.
private String readLine() { try { BufferedReader rin = new BufferedReader(new InputStreamReader(System.in)); return rin.readLine(); } catch (Exception e) { return ""; } }
read a single line from stdin and return as String
public void run() { System.out.println(AsciiSplash.getSplashArt()); System.out.println("Welcome to the OJB PB tutorial application"); System.out.println(); // never stop (there is a special use case to quit the application) while (true) { try { // select a use case and perform it UseCase uc = selectUseCase(); uc.apply(); } catch (Throwable t) { broker.close(); System.out.println(t.getMessage()); } } }
the applications main loop.
public UseCase selectUseCase() { displayUseCases(); System.out.println("type in number to select a use case"); String in = readLine(); int index = Integer.parseInt(in); return (UseCase) useCases.get(index); }
select a use case.
public boolean exists(String tableName) { boolean bReturn = false; if (tableName == null) return bReturn; PreparedStatement checkTable = null; try { //System.out.println("DBUtility: looking up table: " + tableName); //System.out.println("Select * from " + tableName + " where 1=0"); checkTable = m_connection.prepareStatement("Select * from " + tableName + " where 1=0"); checkTable.executeQuery(); bReturn = true; } catch(Exception e) { if (e.getMessage().startsWith(m_ORA_EXCEPTION_1000) || e.getMessage().startsWith(m_ORA_EXCEPTION_604)) { System.out.println("Exceeded available Oracle cursors. Resetting connection and trying the SQL statement again..."); resetConnection(); return exists(tableName); } else { //System.out.println("DD - " + e.getMessage()); bReturn = false; } } return bReturn; }
Checks the database for the existence of this table. Returns true if it exists, false if it doesn't exist, and throws a SQLException if the connection is not established. NOTE: If a schema is required for your database, then it should have been provided in the connection url. @param tableName String name of the table that you want check for existence. @return boolean true if the table exists, false if it doesn't exist.
public void exists(String tableName, String columnName, String jdbcType, boolean ignoreCase) throws SQLException { if (tableName == null) throw new SQLException("TableName was null. You must specify a valid table name."); if (columnName == null) throw new SQLException("Column name was null. You must specify a valid column name."); ResultSet columns = getColumns(tableName); if(columns == null) { //columns not in the cache, look them up and cache PreparedStatement checkTable = null; try { //System.out.println("DBUtility: looking up table: " + tableName); //System.out.println("Select * from " + tableName + " where 1=0"); checkTable = m_connection.prepareStatement("Select * from " + tableName + " where 1=0"); columns = checkTable.executeQuery(); putColumns(tableName, columns); } catch(SQLException sqle) { if (sqle.getMessage().startsWith(m_ORA_EXCEPTION_1000) || sqle.getMessage().startsWith(m_ORA_EXCEPTION_604)) { System.out.println("Exceeded available Oracle cursors. Resetting connection and trying the SQL statement again..."); resetConnection(); exists(tableName, columnName, jdbcType, ignoreCase); } else { //System.out.println(sqle.getMessage()); throw sqle; } } } ResultSetMetaData rsMeta = columns.getMetaData(); int iColumns = rsMeta.getColumnCount(); int jdbcTypeConst = this.getJdbcType(jdbcType); for(int i = 1; i <= iColumns; i++) { if(ignoreCase) { //ignore case while testing if(columnName.equalsIgnoreCase(rsMeta.getColumnName(i))) { //The column exists, does the type match? if(jdbcTypeConst != rsMeta.getColumnType(i)) { throw new SQLException("The column '" + tableName + "." + columnName + "' is of type '" + rsMeta.getColumnTypeName(i) + "' and cannot be mapped to the jdbc type '" + jdbcType + "'."); } else { return; } } } else { //enforce case-sensitive compare if(columnName.equals(rsMeta.getColumnName(i))) { //The column exists, does the type match? if(jdbcTypeConst != rsMeta.getColumnType(i)) { throw new SQLException("The column '" + tableName + "." + columnName + "' is of type '" + rsMeta.getColumnTypeName(i) + "' and cannot be mapped to the jdbc type '" + jdbcType + "'."); } else { return; } } } //System.out.println("Found column: " + rsMeta.getColumnName(i)); } throw new SQLException("The column '" + columnName + "' was not found in table '" + tableName + "'."); }
Checks the database for the existence of this table.column of the specified jdbc type. Returns true if it exists, false if it doesn't exist, and throws a SQLException if the connection is not established. NOTE: If a schema is required for your database, then it should have been provided in the connection url. @param tableName String name of the table to check. @param columnName String name of the table column to check. @param jdbcType Case insensitive String representation of the jdbc type of the column. Valid values are string representations of the types listed in java.sql.Types. For example, "bit", "float", "varchar", "clob", etc. @param ignoreCase boolean flag that determines if the utility should consider the column name case when searching for the database table.column. @throws SQLException if the Table doesn't exist, if the column doesn't exist, if the column type doesn't match the specified jdbcType.
public void exists(String tableName, String columnName, boolean ignoreCase) throws SQLException { if (tableName == null) throw new SQLException("TableName was null. You must specify a valid table name."); if (columnName == null) throw new SQLException("Column name was null. You must specify a valid column name."); ResultSet columns = getColumns(tableName); if(columns == null) { //columns not in the cache, look them up and cache try { //System.out.println("DBUtility: looking up table: " + tableName); //System.out.println("Select * from " + tableName + " where 1=0"); PreparedStatement checkTable = m_connection.prepareStatement("Select * from " + tableName + " where 1=0"); columns = checkTable.executeQuery(); putColumns(tableName, columns); } catch(SQLException sqle) { if (sqle.getMessage().startsWith(m_ORA_EXCEPTION_1000) || sqle.getMessage().startsWith(m_ORA_EXCEPTION_604)) { System.out.println("Exceeded available Oracle cursors. Resetting connection and trying the SQL statement again..."); resetConnection(); exists(tableName, columnName, ignoreCase); } else { System.out.println(sqle.getMessage()); throw sqle; } } } ResultSetMetaData rsMeta = columns.getMetaData(); int iColumns = rsMeta.getColumnCount(); for(int i = 1; i <= iColumns; i++) { if(ignoreCase) { //ignore case while testing if(columnName.equalsIgnoreCase(rsMeta.getColumnName(i))) { return; } } else { //enforce case-sensitive compare if(columnName.equals(rsMeta.getColumnName(i))) { return; } } //System.out.println("Found column: " + rsMeta.getColumnName(i)); } throw new SQLException("The column '" + columnName + "' was not found in table '" + tableName + "'."); }
Checks the database for the existence of this table.column. Throws a SQLException if if the Table.Column can not be found. NOTE: If a schema is required for your database, then it should have been provided in the connection url. @param tableName String name of the table to check. @param columnName String name of the table column to check. @param ignoreCase boolean flag that determines if the utility should consider the column name case when searching for the database table.column. @throws SQLException if the Table doesn't exist, if the column doesn't exist.
public int getJdbcType(String ojbType) throws SQLException { int result; if(ojbType == null) ojbType = ""; ojbType = ojbType.toLowerCase(); if (ojbType.equals("bit")) result = Types.BIT; else if (ojbType.equals("tinyint")) result = Types.TINYINT; else if (ojbType.equals("smallint")) result = Types.SMALLINT; else if (ojbType.equals("integer")) result = Types.INTEGER; else if (ojbType.equals("bigint")) result = Types.BIGINT; else if (ojbType.equals("float")) result = Types.FLOAT; else if (ojbType.equals("real")) result = Types.REAL; else if (ojbType.equals("double")) result = Types.DOUBLE; else if (ojbType.equals("numeric")) result = Types.NUMERIC; else if (ojbType.equals("decimal")) result = Types.DECIMAL; else if (ojbType.equals("char")) result = Types.CHAR; else if (ojbType.equals("varchar")) result = Types.VARCHAR; else if (ojbType.equals("longvarchar")) result = Types.LONGVARCHAR; else if (ojbType.equals("date")) result = Types.DATE; else if (ojbType.equals("time")) result = Types.TIME; else if (ojbType.equals("timestamp")) result = Types.TIMESTAMP; else if (ojbType.equals("binary")) result = Types.BINARY; else if (ojbType.equals("varbinary")) result = Types.VARBINARY; else if (ojbType.equals("longvarbinary")) result = Types.LONGVARBINARY; else if (ojbType.equals("clob")) result = Types.CLOB; else if (ojbType.equals("blob")) result = Types.BLOB; else throw new SQLException( "The type '"+ ojbType + "' is not a valid jdbc type."); return result; }
Determines the java.sql.Types constant value from an OJB FIELDDESCRIPTOR value. @param type The FIELDDESCRIPTOR which JDBC type is to be determined. @return int the int value representing the Type according to @throws SQLException if the type is not a valid jdbc type. java.sql.Types
private void appendListOfValues(StringBuffer stmt) { int cnt = getColumns().length; stmt.append(" VALUES ("); for (int i = 0; i < cnt; i++) { if (i > 0) { stmt.append(','); } stmt.append('?'); } stmt.append(')'); }
generates a values(?,) for a prepared insert statement. @param stmt the StringBuffer
public void addRoute(String path, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException { addRoute(new Route(path, false), actorClass); }
Add an exact path to the routing table. @throws RouteAlreadyMappedException
public void addRegexRoute(String urlPattern, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException { addRoute(new Route(urlPattern, true), actorClass); }
Add a URL pattern to the routing table. @param urlPattern A regular expression @throws RouteAlreadyMappedException
public Class<? extends Actor> getActorClassForPath(String path) { for (Route route : routes.keySet()) { if (route.isRegex) { Pattern p = Pattern.compile(route.path); Matcher m = p.matcher(path); if (m.matches()) { return routes.get(route); } } else if (route.path.equals(path)) { return routes.get(route); } } return null; }
Retrieve a matching actor class for a specific path. <br/><br/> The method will search the routing table for a matching entry on a FIFO basis. @see #addRoute(String, Class) @see #addRegexRoute(String, Class)
public void setObjectForStatement(PreparedStatement ps, int index, Object value, int sqlType) throws SQLException { if (sqlType == Types.TINYINT) { ps.setByte(index, ((Byte) value).byteValue()); } else { super.setObjectForStatement(ps, index, value, sqlType); } }
Patch provided by Avril Kotzen ([email protected]) DB2 handles TINYINT (for mapping a byte).
public Collection getAllObjects(Class target) { PersistenceBroker broker = getBroker(); Collection result; try { Query q = new QueryByCriteria(target); result = broker.getCollectionByQuery(q); } finally { if (broker != null) broker.close(); } return result; }
Return all objects for the given class.
public Object storeObject(Object object) { PersistenceBroker broker = getBroker(); try { broker.store(object); } finally { if (broker != null) broker.close(); } return object; }
Store an object.
public void deleteObject(Object object) { PersistenceBroker broker = null; try { broker = getBroker(); broker.delete(object); } finally { if (broker != null) broker.close(); } }
Delete an object.
public Collection storeObjects(Collection objects) { PersistenceBroker broker = null; Collection stored; try { broker = getBroker(); stored = this.storeObjects(broker, objects); } finally { if (broker != null) broker.close(); } return stored; }
Store a collection of objects.
public void deleteObjects(Collection objects) { PersistenceBroker broker = null; try { broker = getBroker(); this.deleteObjects(broker, objects); } finally { if (broker != null) broker.close(); } }
Delete a Collection of objects.
public PBKey getPBKey() { if (pbKey == null) { log.error("## PBKey not set, Database isOpen=" + isOpen + " ##"); if (!isOpen) throw new DatabaseClosedException("Database is not open"); } return pbKey; }
Return the {@link org.apache.ojb.broker.PBKey} associated with this Database.
public synchronized void open(String name, int accessMode) throws ODMGException { if (isOpen()) { throw new DatabaseOpenException("Database is already open"); } PersistenceBroker broker = null; try { if (name == null) { log.info("Given argument was 'null', open default database"); broker = PersistenceBrokerFactory.defaultPersistenceBroker(); } else { broker = PersistenceBrokerFactory.createPersistenceBroker( BrokerHelper.extractAllTokens(name)); } pbKey = broker.getPBKey(); isOpen = true; //register opened database odmg.registerOpenDatabase(this); if (log.isDebugEnabled()) log.debug("Open database using PBKey " + pbKey); } catch (PBFactoryException ex) { log.error("Open database failed: " + ex.getMessage(), ex); throw new DatabaseNotFoundException( "OJB can't open database " + name + "\n" + ex.getMessage()); } finally { // broker must be immediately closed if (broker != null) { broker.close(); } } }
Open the named database with the specified access mode. Attempts to open a database when it has already been opened will result in the throwing of the exception <code>DatabaseOpenException</code>. A <code>DatabaseNotFoundException</code> is thrown if the database does not exist. Some implementations may throw additional exceptions that are also derived from <code>ODMGException</code>. @param name The name of the database. @param accessMode The access mode, which should be one of the static fields: <code>OPEN_READ_ONLY</code>, <code>OPEN_READ_WRITE</code>, or <code>OPEN_EXCLUSIVE</code>. @exception ODMGException The database could not be opened.
public void close() throws ODMGException { /** * is the DB open? ODMG 3.0 says we can't close an already open database. */ if (!isOpen()) { throw new DatabaseClosedException("Database is not Open. Must have an open DB to call close."); } /** * is the associated Tx open? ODMG 3.0 says we can't close the database with an open Tx pending. * check if a tx was found, the tx was associated with database */ if (odmg.hasOpenTransaction() && getTransaction().getAssociatedDatabase().equals(this)) { String msg = "Database cannot be closed, associated Tx is still open." + " Transaction status is '" + TxUtil.getStatusString(getTransaction().getStatus()) + "'." + " Used PBKey was "+getTransaction().getBroker().getPBKey(); log.error(msg); throw new TransactionInProgressException(msg); } isOpen = false; // remove the current PBKey pbKey = null; // if we close current database, we have to notify implementation instance if (this == odmg.getCurrentDatabase()) { odmg.setCurrentDatabase(null); } }
Close the database. After you have closed a database, further attempts to access objects in the database will cause the exception <code>DatabaseClosedException</code> to be thrown. Some implementations may throw additional exceptions that are also derived from <code>ODMGException</code>. @exception ODMGException Unable to close the database.
public void bind(Object object, String name) throws ObjectNameNotUniqueException { /** * Is DB open? ODMG 3.0 says it has to be to call bind. */ if (!this.isOpen()) { throw new DatabaseClosedException("Database is not open. Must have an open DB to call bind."); } /** * Is Tx open? ODMG 3.0 says it has to be to call bind. */ TransactionImpl tx = getTransaction(); if (tx == null || !tx.isOpen()) { throw new TransactionNotInProgressException("Tx is not open. Must have an open TX to call bind."); } tx.getNamedRootsMap().bind(object, name); }
Associate a name with an object and make it persistent. An object instance may be bound to more than one name. Binding a previously transient object to a name makes that object persistent. @param object The object to be named. @param name The name to be given to the object. @exception org.odmg.ObjectNameNotUniqueException If an attempt is made to bind a name to an object and that name is already bound to an object.
public Object lookup(String name) throws ObjectNameNotFoundException { /** * Is DB open? ODMG 3.0 says it has to be to call bind. */ if (!this.isOpen()) { throw new DatabaseClosedException("Database is not open. Must have an open DB to call lookup"); } /** * Is Tx open? ODMG 3.0 says it has to be to call bind. */ TransactionImpl tx = getTransaction(); if (tx == null || !tx.isOpen()) { throw new TransactionNotInProgressException("Tx is not open. Must have an open TX to call lookup."); } return tx.getNamedRootsMap().lookup(name); }
Lookup an object via its name. @param name The name of an object. @return The object with that name. @exception ObjectNameNotFoundException There is no object with the specified name. ObjectNameNotFoundException
public void unbind(String name) throws ObjectNameNotFoundException { /** * Is DB open? ODMG 3.0 says it has to be to call unbind. */ if (!this.isOpen()) { throw new DatabaseClosedException("Database is not open. Must have an open DB to call unbind"); } TransactionImpl tx = getTransaction(); if (tx == null || !tx.isOpen()) { throw new TransactionNotInProgressException("Tx is not open. Must have an open TX to call lookup."); } tx.getNamedRootsMap().unbind(name); }
Disassociate a name with an object @param name The name of an object. @exception ObjectNameNotFoundException No object exists in the database with that name.
public void deletePersistent(Object object) { if (!this.isOpen()) { throw new DatabaseClosedException("Database is not open"); } TransactionImpl tx = getTransaction(); if (tx == null || !tx.isOpen()) { throw new TransactionNotInProgressException("No transaction in progress, cannot delete persistent"); } RuntimeObject rt = new RuntimeObject(object, tx); tx.deletePersistent(rt); // tx.moveToLastInOrderList(rt.getIdentity()); }
Deletes an object from the database. It must be executed in the context of an open transaction. If the object is not persistent, then ObjectNotPersistent is thrown. If the transaction in which this method is executed commits, then the object is removed from the database. If the transaction aborts, then the deletePersistent operation is considered not to have been executed, and the target object is again in the database. @param object The object to delete.
public void setup() { this.myIntrospector = JadeAgentIntrospector.getMyInstance((Agent) this); LogActivator.logToFile(logger, this.getName(), Level.ALL); // Register the service try { DFAgentDescription dfd = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType("server"); sd.setName("report-service"); // Sets the agent description dfd.setName(this.getAID()); dfd.addServices(sd); // Register the agent DFService.register(this, dfd); } catch (Exception e) { logger.severe("Exception registering agent in DF. Agent: " + this.getName()); } MessageTemplate t = MessageTemplate.MatchPerformative(ACLMessage.INFORM); addBehaviour(new ReportServer(this,t)); }
/* (non-Javadoc) @see jade.core.Agent#setup()
public static void main( String[] args ) { try { // Test encoding/decoding byte arrays { byte[] bytes1 = { (byte)2,(byte)2,(byte)3,(byte)0,(byte)9 }; // My zip code byte[] bytes2 = { (byte)99,(byte)2,(byte)2,(byte)3,(byte)0,(byte)9 }; System.out.println( "Bytes 2,2,3,0,9 as Base64: " + encodeBytes( bytes1 ) ); System.out.println( "Bytes 2,2,3,0,9 w/ offset: " + encodeBytes( bytes2, 1, bytes2.length-1 ) ); byte[] dbytes = decode( encodeBytes( bytes1 ) ); System.out.print( encodeBytes( bytes1 ) + " decoded: " ); for( int i = 0; i < dbytes.length; i++ ) System.out.print( dbytes[i] + (i<dbytes.length-1?",":"\n") ); } // end testing byte arrays // Test Input Stream { // Read GIF stored in base64 form. java.io.FileInputStream fis = new java.io.FileInputStream( "test.gif.b64" ); Base64.InputStream b64is = new Base64.InputStream( fis, DECODE ); byte[] bytes = new byte[0]; int b = -1; while( (b = b64is.read()) >= 0 ){ byte[] temp = new byte[ bytes.length + 1 ]; System.arraycopy( bytes,0, temp,0,bytes.length ); temp[bytes.length] = (byte)b; bytes = temp; } // end while: terribly inefficient way to read data b64is.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon( bytes ); javax.swing.JLabel jlabel = new javax.swing.JLabel( "Read from test.gif.b64", iicon,0 ); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.getContentPane().add( jlabel ); jframe.pack(); jframe.show(); // Write raw bytes to file java.io.FileOutputStream fos = new java.io.FileOutputStream( "test.gif_out" ); fos.write( bytes ); fos.close(); // Read raw bytes and encode fis = new java.io.FileInputStream( "test.gif_out" ); b64is = new Base64.InputStream( fis, ENCODE ); byte[] ebytes = new byte[0]; b = -1; while( (b = b64is.read()) >= 0 ){ byte[] temp = new byte[ ebytes.length + 1 ]; System.arraycopy( ebytes,0, temp,0,ebytes.length ); temp[ebytes.length] = (byte)b; ebytes = temp; } // end while: terribly inefficient way to read data b64is.close(); String s = new String( ebytes ); javax.swing.JTextArea jta = new javax.swing.JTextArea( s ); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane( jta ); jframe = new javax.swing.JFrame(); jframe.setTitle( "Read from test.gif_out" ); jframe.getContentPane().add( jsp ); jframe.pack(); jframe.show(); // Write encoded bytes to file fos = new java.io.FileOutputStream( "test.gif.b64_out" ); fos.write( ebytes ); // Read GIF stored in base64 form. fis = new java.io.FileInputStream( "test.gif.b64_out" ); b64is = new Base64.InputStream( fis, DECODE ); byte[] edbytes = new byte[0]; b = -1; while( (b = b64is.read()) >= 0 ){ byte[] temp = new byte[ edbytes.length + 1 ]; System.arraycopy( edbytes,0, temp,0,edbytes.length ); temp[edbytes.length] = (byte)b; edbytes = temp; } // end while: terribly inefficient way to read data b64is.close(); iicon = new javax.swing.ImageIcon( edbytes ); jlabel = new javax.swing.JLabel( "Read from test.gif.b64_out", iicon,0 ); jframe = new javax.swing.JFrame(); jframe.getContentPane().add( jlabel ); jframe.pack(); jframe.show(); } // end: Test Input Stream // Test Output Stream { // Read raw bytes java.io.FileInputStream fis = new java.io.FileInputStream( "test.gif_out" ); byte[] rbytes = new byte[0]; int b = -1; while( (b = fis.read()) >= 0 ){ byte[] temp = new byte[ rbytes.length + 1 ]; System.arraycopy( rbytes,0, temp,0,rbytes.length ); temp[rbytes.length] = (byte)b; rbytes = temp; } // end while: terribly inefficient way to read data fis.close(); // Write raw bytes to encoded file java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif.b64_out2"); Base64.OutputStream b64os = new Base64.OutputStream( fos, ENCODE ); b64os.write( rbytes ); b64os.close(); // Read raw bytes that are actually encoded (but we'll ignore that) fis = new java.io.FileInputStream( "test.gif.b64_out2" ); byte[] rebytes = new byte[0]; b = -1; while( (b = fis.read()) >= 0 ){ byte[] temp = new byte[ rebytes.length + 1 ]; System.arraycopy( rebytes,0, temp,0,rebytes.length ); temp[rebytes.length] = (byte)b; rebytes = temp; } // end while: terribly inefficient way to read data fis.close(); String s = new String( rebytes ); javax.swing.JTextArea jta = new javax.swing.JTextArea( s ); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane( jta ); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.setTitle( "Read from test.gif.b64_out2" ); jframe.getContentPane().add( jsp ); jframe.pack(); jframe.show(); // Write encoded bytes to decoded raw file fos = new java.io.FileOutputStream("test.gif_out2"); b64os = new Base64.OutputStream( fos, DECODE ); b64os.write( rebytes ); b64os.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon( "test.gif_out2" ); javax.swing.JLabel jlabel = new javax.swing.JLabel( "Read from test.gif_out2", iicon,0 ); jframe = new javax.swing.JFrame(); jframe.getContentPane().add( jlabel ); jframe.pack(); jframe.show(); } // end: Test Output Stream // Test wagner's files { java.io.FileInputStream fis = new java.io.FileInputStream("D:\\temp\\testencoding.txt"); Base64.InputStream b64is = new Base64.InputStream( fis, DECODE ); java.io.FileOutputStream fos = new java.io.FileOutputStream("D:\\temp\\file.zip"); int b; while( (b=b64is.read()) >= 0 ) fos.write( b ); fos.close(); b64is.close(); } // end test wagner's file } // end try catch( Exception e) { e.printStackTrace(); } }
Testing. Feel free--in fact I encourage you--to throw out this entire "main" method when you actually deploy this code.
public static String encodeBytes( byte[] source, int off, int len ) { return encodeBytes( source, off, len, true ); }
Encodes a byte array into Base64 notation. @param source The data to convert @param off Offset in array where conversion should begin @param len Length of data to convert @since 1.4
public static String encodeBytes( byte[] source, int off, int len, boolean breakLines ) { int len43 = len * 4 / 3; byte[] outBuff = new byte[ ( len43 ) // Main 4:3 + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e ); lineLength += 4; if( breakLines && lineLength == MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e ); e += 4; } // end if: some padding needed return new String( outBuff, 0, e ); }
Encodes a byte array into Base64 notation. @param source The data to convert @param off Offset in array where conversion should begin @param len Length of data to convert @param breakLines Break lines at 80 characters or less. @since 1.4
private static byte[] decode4to3( byte[] fourBytes ) { byte[] outBuff1 = new byte[3]; int count = decode4to3( fourBytes, 0, outBuff1, 0 ); byte[] outBuff2 = new byte[ count ]; System.arraycopy( outBuff1, 0, outBuff2, 0, count ); return outBuff2; }
Decodes the first four bytes of array <var>fourBytes</var> and returns an array up to three bytes long with the decoded values. @param fourBytes the array with Base64 content @return array with decoded values @since 1.3
private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset ) { // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { try{ // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; }catch( Exception e){ LoggerFactory.getDefaultLogger().error(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) ); LoggerFactory.getDefaultLogger().error(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) ); LoggerFactory.getDefaultLogger().error(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) ); LoggerFactory.getDefaultLogger().error(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) ); return -1; } // end catch } }
Decodes four bytes from array <var>source</var> and writes the resulting bytes (up to three of them) to <var>destination</var>. The source and destination arrays can be manipulated anywhere along their length by specifying <var>srcOffset</var> and <var>destOffset</var>. This method does not check to make sure your arrays are large enough to accomodate <var>srcOffset</var> + 4 for the <var>source</var> array or <var>destOffset</var> + 3 for the <var>destination</var> array. This method returns the actual number of bytes that were converted from the Base64 encoding. @param source the array to convert @param srcOffset the index where conversion begins @param destination the array to hold the conversion @param destOffset the index where output will be put @return the number of decoded bytes converted @since 1.3
public static byte[] decode( String s ) { byte[] bytes = s.getBytes(); return decode( bytes, 0, bytes.length ); }
Decodes data from Base64 notation. @param s the string to decode @return the decoded data @since 1.4
public static Object decodeToObject(String encodedObject) { byte[] objBytes = decode(encodedObject); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; try { bais = new java.io.ByteArrayInputStream(objBytes); ois = new java.io.ObjectInputStream(bais); return ois.readObject(); } // end try catch (java.io.IOException e) { e.printStackTrace(); return null; } // end catch catch (java.lang.ClassNotFoundException e) { e.printStackTrace(); return null; } // end catch finally { try { bais.close(); } catch (Exception e) { // ignore it } try { ois.close(); } catch (Exception e) { // ignore it } } // end finally }
Attempts to decode Base64 data and deserialize a Java Object within. Returns <tt>null if there was an error. @param encodedObject The Base64 data to decode @return The decoded and deserialized object @since 1.4
public static byte[] decode( byte[] source, int off, int len ) { int len34 = len * 3 / 4; byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for( i = 0; i < len; i++ ) { sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits sbiDecode = DECODABET[ sbiCrop ]; if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = sbiCrop; if( b4Posn > 3 ) { outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( sbiCrop == EQUALS_SIGN ) break; } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { LoggerFactory.getDefaultLogger().error( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" ); return null; } // end else: } // each input character byte[] out = new byte[ outBuffPosn ]; System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; }
Decodes Base64 content in byte array format and returns the decoded byte array. @param source The Base64 encoded data @param off The offset of where to begin decoding @param len The length of characters to decode @return decoded data @since 1.3
protected void appendWhereClause(StringBuffer stmt, Object[] columns) { stmt.append(" WHERE "); for (int i = 0; i < columns.length; i++) { if (i > 0) { stmt.append(" AND "); } stmt.append(columns[i]); stmt.append("=?"); } }
Generate a sql where-clause matching the contraints defined by the array of fields @param columns array containing all columns used in WHERE clause
protected List appendListOfColumns(String[] columns, StringBuffer stmt) { ArrayList columnList = new ArrayList(); for (int i = 0; i < columns.length; i++) { if (i > 0) { stmt.append(","); } stmt.append(columns[i]); columnList.add(columns[i]); } return columnList; }
Appends to the statement a comma separated list of column names. @param columns defines the columns to be selected (for reports) @return list of column names
private void logState(final FileRollEvent fileRollEvent) { // if (ApplicationState.isApplicationStateEnabled()) { synchronized (this) { final Collection<ApplicationState.ApplicationStateMessage> entries = ApplicationState.getAppStateEntries(); for (ApplicationState.ApplicationStateMessage entry : entries) { Level level = ApplicationState.getLog4jLevel(entry.getLevel()); if(level.isGreaterOrEqual(ApplicationState.LOGGER.getEffectiveLevel())) { final org.apache.log4j.spi.LoggingEvent loggingEvent = new org.apache.log4j.spi.LoggingEvent(ApplicationState.FQCN, ApplicationState.LOGGER, level, entry.getMessage(), null); //Save the current layout before changing it to the original (relevant for marker cases when the layout was changed) Layout current=fileRollEvent.getSource().getLayout(); //fileRollEvent.getSource().activeOriginalLayout(); String flowContext = (String) MDC.get("flowCtxt"); MDC.remove("flowCtxt"); //Write applicationState: if(fileRollEvent.getSource().isAddApplicationState() && fileRollEvent.getSource().getFile().endsWith("log")){ fileRollEvent.dispatchToAppender(loggingEvent); } //Set current again. fileRollEvent.getSource().setLayout(current); if (flowContext != null) { MDC.put("flowCtxt", flowContext); } } } } // } }
Write all state items to the log file. @param fileRollEvent the event to log
public void setBooleanAttribute(String name, Boolean value) { ensureValue(); Attribute attribute = new BooleanAttribute(value); attribute.setEditable(isEditable(name)); getValue().getAllAttributes().put(name, attribute); }
Sets the specified boolean attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public void setCurrencyAttribute(String name, String value) { ensureValue(); Attribute attribute = new CurrencyAttribute(value); attribute.setEditable(isEditable(name)); getValue().getAllAttributes().put(name, attribute); }
Sets the specified currency attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public void setFloatAttribute(String name, Float value) { ensureValue(); Attribute attribute = new FloatAttribute(value); attribute.setEditable(isEditable(name)); getValue().getAllAttributes().put(name, attribute); }
Sets the specified float attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public void setImageUrlAttribute(String name, String value) { ensureValue(); Attribute attribute = new ImageUrlAttribute(value); attribute.setEditable(isEditable(name)); getValue().getAllAttributes().put(name, attribute); }
Sets the specified image URL attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public void setIntegerAttribute(String name, Integer value) { ensureValue(); Attribute attribute = new IntegerAttribute(value); attribute.setEditable(isEditable(name)); getValue().getAllAttributes().put(name, attribute); }
Sets the specified integer attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public void setLongAttribute(String name, Long value) { ensureValue(); Attribute attribute = new LongAttribute(value); attribute.setEditable(isEditable(name)); getValue().getAllAttributes().put(name, attribute); }
Sets the specified long attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public void setShortAttribute(String name, Short value) { ensureValue(); Attribute attribute = new ShortAttribute(value); attribute.setEditable(isEditable(name)); getValue().getAllAttributes().put(name, attribute); }
Sets the specified short attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public void setStringAttribute(String name, String value) { ensureValue(); Attribute attribute = new StringAttribute(value); attribute.setEditable(isEditable(name)); getValue().getAllAttributes().put(name, attribute); }
Sets the specified string attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public void setUrlAttribute(String name, String value) { ensureValue(); Attribute attribute = new UrlAttribute(value); attribute.setEditable(isEditable(name)); getValue().getAllAttributes().put(name, attribute); }
Sets the specified URL attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public static String encrypt(final String password) throws AuthenticationException { String hashValue; try { final MessageDigest msgDigest = MessageDigest.getInstance("SHA"); msgDigest.update(password.getBytes("UTF-8")); final byte rawByte[] = msgDigest.digest(); hashValue = new String(Base64.encodeBase64(rawByte)); } catch (Exception e) { LOG.error("Encryption failed."); throw new AuthenticationException("Error occurred during password encryption", e); } return hashValue; }
Encrypt passwords @param password @return String @throws AuthenticationException
public boolean load() { _load(); java.util.Iterator it = this.alChildren.iterator(); while (it.hasNext()) { Object o = it.next(); if (o instanceof OjbMetaTreeNode) ((OjbMetaTreeNode)o).load(); } return true; }
Recursively loads the metadata for this node
public static int getIsolationLevelFor(String isoLevel) { if(isoLevel == null || StringUtils.isEmpty(isoLevel)) { LoggerFactory.getDefaultLogger().debug( "[LockHelper] Specified isolation level string is 'null', using the default isolation level"); return IsolationLevels.IL_DEFAULT; } if (isoLevel.equalsIgnoreCase(IsolationLevels.LITERAL_IL_READ_UNCOMMITTED)) { return IsolationLevels.IL_READ_UNCOMMITTED; } else if (isoLevel.equalsIgnoreCase(IsolationLevels.LITERAL_IL_READ_COMMITTED)) { return IsolationLevels.IL_READ_COMMITTED; } else if (isoLevel.equalsIgnoreCase(IsolationLevels.LITERAL_IL_REPEATABLE_READ)) { return IsolationLevels.IL_REPEATABLE_READ; } else if (isoLevel.equalsIgnoreCase(IsolationLevels.LITERAL_IL_SERIALIZABLE)) { return IsolationLevels.IL_SERIALIZABLE; } else if (isoLevel.equalsIgnoreCase(IsolationLevels.LITERAL_IL_OPTIMISTIC)) { return IsolationLevels.IL_OPTIMISTIC; } else if (isoLevel.equalsIgnoreCase(IsolationLevels.LITERAL_IL_NONE)) { return IsolationLevels.IL_NONE; } LoggerFactory.getDefaultLogger().warn("[LockHelper] Unknown isolation-level '" + isoLevel + "', using default isolation level"); return IsolationLevels.IL_DEFAULT; }
maps IsolationLevel literals to the corresponding id @param isoLevel @return the id
public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException { if (null == target) { return false; } if (target instanceof InternalFeature) { InternalFeature feature = (InternalFeature) target; return feature.getAttributes().containsKey(name) || ID_PROPERTY_NAME.equalsIgnoreCase(name); } else if (target instanceof AssociationValue) { AssociationValue associationValue = (AssociationValue) target; return associationValue.getAllAttributes().containsKey(name) || ID_PROPERTY_NAME.equalsIgnoreCase(name); } return false; }
{@inheritDoc}
public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException { if (target == null) { throw new AccessException("Cannot read property of null target"); } if (target instanceof InternalFeature) { InternalFeature feature = (InternalFeature) target; if (feature.getAttributes().containsKey(name)) { Attribute<?> attribute = feature.getAttributes().get(name); return new TypedValue(attribute.getValue()); } else if (ID_PROPERTY_NAME.equalsIgnoreCase(ID_PROPERTY_NAME)) { return new TypedValue(feature.getId()); } else { throw new AccessException("Unknown attribute " + name + "for layer " + feature.getLayer().getId()); } } else if (target instanceof AssociationValue) { AssociationValue associationValue = (AssociationValue) target; if (associationValue.getAllAttributes().containsKey(name)) { Attribute<?> attribute = associationValue.getAllAttributes().get(name); return new TypedValue(attribute.getValue()); } else if (ID_PROPERTY_NAME.equalsIgnoreCase(ID_PROPERTY_NAME)) { Attribute<?> attribute = associationValue.getId(); return new TypedValue(attribute.getValue()); } else { throw new AccessException("Unknown attribute " + name + " for association " + target); } } else { throw new AccessException("Cannot read property " + name + "from class " + target.getClass()); } }
{@inheritDoc}
public void write(EvaluationContext context, Object target, String name, Object newValue) throws AccessException { throw new AccessException("InternalFeaturePropertyAccess is read-only"); }
{@inheritDoc}
@Deprecated @SuppressWarnings({ "rawtypes", "unchecked" }) public Map<String, PrimitiveAttribute<?>> getAttributes() { if (!isPrimitiveOnly()) { throw new UnsupportedOperationException("Primitive API not supported for nested association values"); } return (Map) attributes; }
Get the primitive attributes for the associated object. @return attributes for associated objects @deprecated replaced by {@link #getAllAttributes()} after introduction of nested associations
@Deprecated @SuppressWarnings({ "rawtypes", "unchecked" }) public void setAttributes(Map<String, PrimitiveAttribute<?>> attributes) { if (!isPrimitiveOnly()) { throw new UnsupportedOperationException("Primitive API not supported for nested association values"); } this.attributes = (Map) attributes; }
Set the attributes for the associated object. @param attributes attributes for associated objects @deprecated replaced by {@link #setAllAttributes(Map)} after introduction of nested associations
public Object getAttributeValue(String attributeName) { Attribute attribute = getAllAttributes().get(attributeName); if (attribute != null) { return attribute.getValue(); } return null; }
Convenience method that returns the attribute value for the specified attribute name. @param attributeName the name of the attribute @return the value of the attribute or null if no such attribute exists @since 1.9.0
public void setCurrencyAttribute(String name, String value) { ensureAttributes(); Attribute attribute = new CurrencyAttribute(value); attribute.setEditable(isEditable(name)); getAllAttributes().put(name, attribute); }
Sets the specified currency attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public void setDateAttribute(String name, Date value) { ensureAttributes(); Attribute attribute = new DateAttribute(value); attribute.setEditable(isEditable(name)); getAllAttributes().put(name, attribute); }
Sets the specified date attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public void setDoubleAttribute(String name, Double value) { ensureAttributes(); Attribute attribute = new DoubleAttribute(value); attribute.setEditable(isEditable(name)); getAllAttributes().put(name, attribute); }
Sets the specified double attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public void setImageUrlAttribute(String name, String value) { ensureAttributes(); Attribute attribute = new ImageUrlAttribute(value); attribute.setEditable(isEditable(name)); getAllAttributes().put(name, attribute); }
Sets the specified image URL attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public void setStringAttribute(String name, String value) { ensureAttributes(); Attribute attribute = new StringAttribute(value); attribute.setEditable(isEditable(name)); getAllAttributes().put(name, attribute); }
Sets the specified string attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0
public void setUrlAttribute(String name, String value) { ensureAttributes(); Attribute attribute = new UrlAttribute(value); attribute.setEditable(isEditable(name)); getAllAttributes().put(name, attribute); }
Sets the specified URL attribute to the specified value. @param name name of the attribute @param value value of the attribute @since 1.9.0