Java Code Examples for java.io.Serializable

The following are top voted examples for showing how to use java.io.Serializable. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: richfaces   File: AjaxBehavior.java View source code Vote up 6 votes
private Set<String> toSet(Serializable propertyName, Object value) {

        Set<String> result = null;

        result = Sets.asSet(value);

        if (result == null) {
            throw new FacesException(
                propertyName.toString()
                    + "' attribute value must be Collection, List, array, String, comma-separated String, whitespace-separate String'");
        }

        return result;
    }
 
Example 2
Project: palava-ipc-xml-rpc   File: StringAdapter.java View source code Vote up 6 votes
@Override
public String decode(Value input) {
    Preconditions.checkNotNull(input, "Input");
    final Serializable first = input.getContent().get(0);
    if (first instanceof String) {
        return first.toString();
    } else {
        return JAXBElement.class.cast(first).getValue().toString();
    }
}
 
Example 3
Project: eGov   File: VoucherHelper.java View source code Vote up 6 votes
public String getEg_Voucher(String vouType,String fiscalPeriodIdStr) throws TaskFailedException,Exception
	{
		if(LOGGER.isDebugEnabled())     LOGGER.debug(" In EGovernCommon :getEg_Voucher method ");
		Query query = HibernateUtil.getCurrentSession().createSQLQuery("select name from fiscalperiod where id="+Integer.parseInt(fiscalPeriodIdStr)+"");
		List<String> fc  = query.list();
		//Sequence name will be SQ_U_DBP_CGVN_FP7 for vouType U/DBP/CGVN and fiscalPeriodIdStr 7
		 Serializable sequenceNumber;
		 String sequenceName ;
		 sequenceName = sequenceNameFor(vouType, fc.get(0).toString());
		try {
            sequenceNumber = sequenceNumberGenerator.getNextSequence(sequenceName);
        } catch (final SQLGrammarException e) {
            sequenceNumber = dbSequenceGenerator.createAndGetNextSequence(sequenceName);
        }
		return sequenceNumber.toString();
		
}
 
Example 4
Project: usercenter   File: DefaultWebSessionManager.java View source code Vote up 6 votes
private void storeSessionId(Serializable currentId, HttpServletRequest request, HttpServletResponse response) {
    if (currentId == null) {
        String msg = "sessionId cannot be null when persisting for subsequent requests.";
        throw new IllegalArgumentException(msg);
    }
    Cookie template = getSessionIdCookie();
    Cookie cookie = new SimpleCookie(template);
    String idString = currentId.toString();
    cookie.setValue(idString);
    cookie.saveTo(request, response);
    if (log.isTraceEnabled()) {
        log.trace("Set session ID cookie for session with id {}", idString);
    }
}
 
Example 5
Project: teiid-designer   File: FunctionMethods.java View source code Vote up 6 votes
public static Object commandPayload(CommandContext context) {
    Serializable payload = context.getCommandPayload();
    if(payload == null) {
        return null;
    }
    // 0-arg form - just return payload as a string if it exists
    return payload.toString();
}
 
Example 6
Project: ddf-spatial   File: GenericFeatureConverterWfs20.java View source code Vote up 6 votes
private void writeAttributeToXml(Attribute attribute, QName qname, AttributeFormat format,
        MarshallingContext context, HierarchicalStreamWriter writer) {
    // Loop to handle multi-valued attributes

    String name = qname.getPrefix() + ":" + attribute.getName();
    for (Serializable value : attribute.getValues()) {
        String xmlValue = null;

        switch (format) {
        case XML:
            String cdata = (String) value;
            if (cdata != null && (writer.underlyingWriter() instanceof EnhancedStaxWriter)) {
                writer.startNode(name);
                EnhancedStaxWriter eWriter = (EnhancedStaxWriter) writer.underlyingWriter();
                eWriter.writeCdata(cdata);
                writer.endNode();
            }
            break;
        case GEOMETRY:
            XmlNode.writeGeometry(name, context, writer, XmlNode.readGeometry((String) value));
            break;
        case BINARY:
            xmlValue = Base64.encodeBase64String((byte[]) value);
            break;
        case DATE:
            Date date = (Date) value;
            xmlValue = DateFormatUtils.formatUTC(date,
                    DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
            break;
        case OBJECT:
            // Probably won't translate at all.
            break;
        default:
            xmlValue = value.toString();
            break;
        }
        // Write the node if we were able to convert it.
        if (xmlValue != null) {

            writer.startNode(name);
            writer.setValue(xmlValue);
            writer.endNode();
        }
    }
}
 
Example 7
Project: gda-common   File: TestHelpers.java View source code Vote up 6 votes
@Override
public String toString() {
	if (useSuperToString) {
		return super.toString();
	}
	Serializable s = getBuffer();
	if (s instanceof byte[]) {
		String sb = "";
		for (byte b : (byte[]) s) {
			sb += Byte.toString(b) + ",";
		}
		return sb.toString();
	}
	return s.toString();
}
 
Example 8
Project: deep-spark   File: DeepSparkContext.java View source code Vote up 6 votes
/**
 * Returns a Cells RDD from HDFS.
 * @param config HDFS ExtractorConfig.
 * @return Cells RDD.
 */
public RDD<Cells> createHDFSRDD(ExtractorConfig<Cells> config) {

    Serializable host = config.getValues().get(ExtractorConstants.HOST);
    Serializable port = config.getValues().get(ExtractorConstants.PORT);
    Serializable path = config.getValues().get(ExtractorConstants.FS_FILE_PATH);

    final TextFileDataTable textFileDataTable = UtilFS.createTextFileMetaDataFromConfig(config, this);

    String filePath = path.toString();
    if (config.getExtractorImplClassName().equals(ExtractorConstants.HDFS)) {
        filePath = ExtractorConstants.HDFS_PREFIX + host.toString() + ":" + port + path.toString();
    }

    return createRDDFromFilePath(filePath, textFileDataTable);
}
 
Example 9
Project: jeppetto   File: AccessControlHelper.java View source code Vote up 6 votes
void validateContextAllowsWrite(Class<?> objectType, Serializable id, AccessControlContext accessControlContext,
                                boolean checkIfReadable) {
    if (annotationAllowsAccess(objectType, accessControlContext, AccessType.ReadWrite)
        || accessControlEntryAllowsAccess(objectType, id, accessControlContext.getAccessId(), AccessType.ReadWrite)) {
        return;
    }

    if (checkIfReadable && !accessControlEntryAllowsAccess(objectType, id, accessControlContext.getAccessId(), AccessType.Read)) {
        throw new NoSuchItemException(objectType.getSimpleName(), id.toString());
    }

    throw new AccessControlException("Can't access object [" + id + "] for ReadWrite with " + accessControlContext);
}
 
Example 10
Project: ehour   File: EntityParser.java View source code Vote up 6 votes
private <PK extends Serializable> Serializable castOrLog(PK originalKey, Serializable primaryKey) throws ImportException {
    try {
        if (primaryKey.getClass().equals(originalKey.getClass())) {
            return originalKey.getClass().cast(primaryKey);
        } else {
            LOG.error("This should only happen while running junit tests.");
            return null;
        }
    } catch (ClassCastException cce) {
        throw new ImportException("can't cast " + primaryKey.toString() + " to " + originalKey.toString()+ ": " + cce.getMessage(), cce);
    }
}
 
Example 11
Project: researchzilla   File: EmailUtil.java View source code Vote up 6 votes
public static void sendActivateEmailString(String smtp, int port, String username, String password, String registerName, String sender, String subject, String receiver, String remoteAddress, Serializable id, String secret, int ttl) throws EmailException {
    String msg = "?? " + "'" + registerName + "'" + ",\n" +
            "\n" +
            "????researchzilla??????????????? (" + receiver + ") ????????\n" +
            "\n" +
            "???????????????????????????IP???" + remoteAddress + "?????????\n" +
            "\n" +
            "???????????????????????? \n" +
            " http://localhost:8080/accountconfirmAction?uid=" + id.toString() + "&secret=" + secret + " \n" +
            "\n" +
            "??????????????????\n" +
            "\n" +
            "????" + ttl + "???????????????????\n" +
            "\n";

    Email emailAgent = new SimpleEmail();

    emailAgent.setHostName(smtp);
    emailAgent.setSmtpPort(port);
    emailAgent.setAuthentication(username, password);
    emailAgent.setSSL(true);
    emailAgent.setFrom(sender);
    emailAgent.setSubject(subject);
    emailAgent.setCharset("utf8");
    emailAgent.setMsg(msg);
    emailAgent.addTo(receiver);
    emailAgent.send();
}
 
Example 12
Project: records-management   File: CurrentClassificationPropertyDecorator.java View source code Vote up 6 votes
/**
 * @see org.alfresco.repo.jscript.app.PropertyDecorator#decorate(org.alfresco.service.namespace.QName, org.alfresco.service.cmr.repository.NodeRef, java.io.Serializable)
 */
@SuppressWarnings("unchecked")
public JSONAware decorate(QName propertyName, NodeRef nodeRef, Serializable value)
{
    mandatory("value", value);
    JSONObject jsonObj = new JSONObject();
    String currentClassificationId = value.toString();
    jsonObj.put(ID, currentClassificationId);
    jsonObj.put(LABEL, getClassificationSchemeService().getClassificationLevelById(currentClassificationId).getDisplayLabel());
    return jsonObj;
}
 
Example 13
Project: usercenter   File: SimpleSession.java View source code Vote up 6 votes
/**
 * Returns [email protected] true} if the specified argument is an [email protected] instanceof} [email protected] SimpleSession} and both
 * [email protected] #getId() id}s are equal.  If the argument is a [email protected] SimpleSession} and either 'this' or the argument
 * does not yet have an ID assigned, the value of [email protected] #onEquals(SimpleSession) onEquals} is returned, which
 * does a necessary attribute-based comparison when IDs are not available.
 * <p/>
 * Do your best to ensure [email protected] SimpleSession} instances receive an ID very early in their lifecycle to
 * avoid the more expensive attributes-based comparison.
 *
 * @param obj the object to compare with this one for equality.
 * @return [email protected] true} if this object is equivalent to the specified argument, [email protected] false} otherwise.
 */
@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj instanceof SimpleSession) {
        SimpleSession other = (SimpleSession) obj;
        Serializable thisId = getId();
        Serializable otherId = other.getId();
        if (thisId != null && otherId != null) {
            return thisId.equals(otherId);
        } else {
            //fall back to an attribute based comparison:
            return onEquals(other);
        }
    }
    return false;
}
 
Example 14
Project: quickml   File: LossFunctionCorrectedForDownsampling.java View source code Vote up 6 votes
@Override
public PredictionMapResult getCorrectedLabelPredictionWeight(LabelPredictionWeight<Serializable, PredictionMap> labelPredictionWeight) {
    PredictionMap correctedPredictionMap = PredictionMap.newMap();
    PredictionMap uncorrectedPrediction = labelPredictionWeight.getPrediction();
    double correctedProbability;
    for (Serializable key : uncorrectedPrediction.keySet()) {
        if (key.equals(negativeLabel)) {
            correctedProbability = 1.0 - DownsamplingUtils.correctProbability(dropProbability, 1.0 - uncorrectedPrediction.get(key));
            correctedPredictionMap.put(key, correctedProbability);
        } else {
            correctedProbability = DownsamplingUtils.correctProbability(dropProbability, uncorrectedPrediction.get(key));
            correctedPredictionMap.put(key, correctedProbability);
        }
    }
    double correctedWeight = labelPredictionWeight.getWeight();
    if (labelPredictionWeight.getLabel().equals(negativeLabel))
        correctedWeight/=(1.0 - dropProbability);
    return new PredictionMapResult(correctedPredictionMap, labelPredictionWeight.label, correctedWeight);
}
 
Example 15
Project: quickml   File: SplitOnAttributeClassifierBuilder.java View source code Vote up 6 votes
private boolean shouldAddInstance(Serializable attributeValue, I instance, ClassificationCounter crossDataCount, double targetCount) {
        //if the model's split valaue is not the same as the instance's split value (avoids redundancy)
        if (!attributeValue.equals(instance.getAttributes().get(attributeKey))) {
            //if we still need instances of a particular classification
//            if (targetCount > crossDataCount.getCount(instance.getLabel())) {
            return true;
            //          }
        }
        return false;
    }
 
Example 16
Project: cdo   File: CDOSyntheticIdPropertyHandler.java View source code Vote up 6 votes
public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
{
  if (value == null)
  {
    return;
  }

  final InternalCDORevision revision = HibernateUtil.getInstance().getCDORevision(target);
  final CDOID id = HibernateUtil.getInstance().getCDOID(revision);
  if (id == null || id instanceof CDOIDTemp)
  {
    final CDOID newCDOID = HibernateUtil.getInstance().createCDOID(new CDOClassifierRef(revision.getEClass()), value);
    revision.setID(newCDOID);
    if (HibernateThreadContext.isCommitContextSet())
    {
      final HibernateCommitContext commitContext = HibernateThreadContext.getCommitContext();
      commitContext.setNewID(id, newCDOID);
      if (id instanceof CDOIDTemp)
      {
        commitContext.getCommitContext().addIDMapping(id, newCDOID);
      }
    }
  }
  else
  {
    final Serializable idValue = HibernateUtil.getInstance().getIdValue(id);
    if (!idValue.equals(value))
    {
      throw new IllegalStateException("Current id and new id are different " + value + "/" + idValue); //$NON-NLS-1$ //$NON-NLS-2$
    }
  }
}
 
Example 17
Project: cdo   File: CDOIDPropertySetter.java View source code Vote up 6 votes
@Override
public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
{
  final InternalCDORevision revision = (InternalCDORevision)target;
  if (value == null)
  {
    if (getEStructuralFeature().isUnsettable())
    {
      revision.unset(getEStructuralFeature());
    }

    return;
  }

  final CDOID revisionID = HibernateUtil.getInstance().getCDOID(revision);
  if (revisionID == null || revisionID instanceof CDOIDTemp)
  {
    final CDOID newCDOID = HibernateUtil.getInstance().createCDOID(new CDOClassifierRef(revision.getEClass()), value);
    revision.setID(newCDOID);
    if (HibernateThreadContext.isCommitContextSet())
    {
      final HibernateCommitContext commitContext = HibernateThreadContext.getCommitContext();
      commitContext.setNewID(revisionID, newCDOID);
      if (revisionID instanceof CDOIDTemp)
      {
        commitContext.getCommitContext().addIDMapping(revisionID, newCDOID);
      }
    }
  }
  else
  {
    final Serializable idValue = HibernateUtil.getInstance().getIdValue(revisionID);
    if (idValue == null)
    {
      throw new IllegalStateException("ID value is null for revision " + revision); //$NON-NLS-1$
    }

    if (!idValue.equals(value))
    {
      throw new IllegalStateException("Current id and new id are different " + value + "/" + idValue); //$NON-NLS-1$ //$NON-NLS-2$
    }
  }

  if (!isVirtualProperty())
  {
    super.set(target, value, factory);
  }
}
 
Example 18
Project: records-management   File: DispositionProperty.java View source code Vote up 6 votes
/**
 * Indicates whether the property has been updated or not.
 *
 * @param before
 * @param after
 * @return
 */
private boolean isPropertyUpdated(Map<QName, Serializable> before, Map<QName, Serializable> after)
{
    boolean result = false;

    Serializable beforeValue = before.get(propertyName);
    Serializable afterValue = after.get(propertyName);

    if (beforeValue == null && afterValue != null)
    {
        result = true;
    }
    else if (beforeValue != null && afterValue == null)
    {
        result = true;
    }
    else if (beforeValue != null && afterValue != null &&
             !beforeValue.equals(afterValue))
    {
        result = true;
    }

    return result;
}
 
Example 19
Project: nuxeo-common   File: SerializableArrayMap.java View source code Vote up 6 votes
@Override
public boolean equals(Object obj) {
    if (obj == this) {
        return true;
    }
    if (obj instanceof SerializableArrayMap) {
        SerializableArrayMap map = (SerializableArrayMap) obj;
        if (count != map.count) {
            return false;
        }
        int len = count << 1;
        for (int i = 0; i < len; i += 2) {
            Serializable key1 = elements[i];
            Serializable key2 = map.elements[i];
            if (!key1.equals(key2)) {
                return false;
            }
            Serializable val1 = elements[i + 1];
            Serializable val2 = map.elements[i + 1];
            if (val1 == null) {
                if (val1 != val2) {
                    return false;
                }
            } else if (!val1.equals(val2)) {
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example 20
Project: org.eclipse.ecr   File: EmbeddedFunctions.java View source code Vote up 6 votes
/**
 * Checks if an id is a (strict) descendant of a given base id.
 *
 * @param conn the connection to the database
 * @param id the id to check for
 * @param baseId the base id
 */
public static boolean isInTree(Connection conn, Serializable id,
        Serializable baseId) throws SQLException {
    if (baseId == null || id == null || baseId.equals(id)) {
        // containment check is strict
        return false;
    }
    PreparedStatement ps = null;
    try {
        ps = conn.prepareStatement("SELECT PARENTID FROM HIERARCHY WHERE ID = ?");
        do {
            ps.setObject(1, id);
            ResultSet rs = ps.executeQuery();
            if (!rs.next()) {
                // no such id
                return false;
            }
            if (id instanceof String) {
                id = rs.getString(1);
            } else {
                id = Long.valueOf(rs.getLong(1));
            }
            if (rs.wasNull()) {
                id = null;
            }
            rs.close();
            if (baseId.equals(id)) {
                // found a match
                return true;
            }
        } while (id != null);
        // got to the root
        return false;
    } finally {
        if (ps != null) {
            ps.close();
        }
    }
}
 
Example 21
Project: org.eclipse.ecr   File: ACLCollectionIO.java View source code Vote up 6 votes
@Override
public ACLRow getCurrentFromResultSet(ResultSet rs, List<Column> columns,
        Model model, Serializable[] returnId, int[] returnPos)
        throws SQLException {
    Serializable id = null;
    String name = null;
    boolean grant = false;
    String permission = null;
    String user = null;
    String group = null;
    int i = 0;
    for (Column column : columns) {
        i++;
        String key = column.getKey();
        Serializable v = column.getFromResultSet(rs, i);
        if (key.equals(model.MAIN_KEY)) {
            id = v;
        } else if (key.equals(model.ACL_NAME_KEY)) {
            name = (String) v;
        } else if (key.equals(model.ACL_GRANT_KEY)) {
            grant = v == null ? false : (Boolean) v;
        } else if (key.equals(model.ACL_PERMISSION_KEY)) {
            permission = (String) v;
        } else if (key.equals(model.ACL_USER_KEY)) {
            user = (String) v;
        } else if (key.equals(model.ACL_GROUP_KEY)) {
            group = (String) v;
        } else {
            throw new RuntimeException(key);
        }
    }
    Serializable prevId = returnId[0];
    returnId[0] = id;
    int pos = (id != null && !id.equals(prevId)) ? 0 : returnPos[0] + 1;
    returnPos[0] = pos;
    return new ACLRow(pos, name, grant, permission, user, group);
}
 
Example 22
Project: JDK   File: CDROutputStream_1_0.java View source code Vote up 6 votes
public void write_value(Serializable object, String repository_id) {

        // Handle null references
        if (object == null) {
            // Write null tag and return
            write_long(0);
            return;
        }

        // Handle shared references
        if (valueCache != null && valueCache.containsKey(object)) {
            writeIndirection(INDIRECTION_TAG, valueCache.getVal(object));
            return;
        }

        Class clazz = object.getClass();
        boolean oldMustChunk = mustChunk;

        if (mustChunk)
            mustChunk = true;

        if (inBlock)
            end_block();

        if (clazz.isArray()) {
            // Handle arrays
            writeArray(object, clazz);
        } else if (object instanceof org.omg.CORBA.portable.ValueBase) {
            // Handle IDL Value types
            writeValueBase((org.omg.CORBA.portable.ValueBase)object, clazz);
        } else if (shouldWriteAsIDLEntity(object)) {
            writeIDLEntity((IDLEntity)object);
        } else if (object instanceof java.lang.String) {
            writeWStringValue((String)object);
        } else if (object instanceof java.lang.Class) {
            writeClass(repository_id, (Class)object);
        } else {
            // RMI-IIOP value type
            writeRMIIIOPValueType(object, clazz);
        }

        mustChunk = oldMustChunk;

        // Check to see if we need to start another block for a
        // possible outer value
        if (mustChunk)
            start_block();

    }
 
Example 23
Project: ikvm-openjdk   File: CDROutputStream_1_0.java View source code Vote up 6 votes
public void write_value(Serializable object, String repository_id) {

        // Handle null references
        if (object == null) {
            // Write null tag and return
            write_long(0);
            return;
        }

        // Handle shared references
        if (valueCache != null && valueCache.containsKey(object)) {
            writeIndirection(INDIRECTION_TAG, valueCache.getVal(object));
            return;
        }

        Class clazz = object.getClass();
        boolean oldMustChunk = mustChunk;

        if (mustChunk)
            mustChunk = true;

        if (inBlock)
            end_block();

        if (clazz.isArray()) {
            // Handle arrays
            writeArray(object, clazz);
        } else if (object instanceof org.omg.CORBA.portable.ValueBase) {
            // Handle IDL Value types
            writeValueBase((org.omg.CORBA.portable.ValueBase)object, clazz);
        } else if (shouldWriteAsIDLEntity(object)) {
            writeIDLEntity((IDLEntity)object);
        } else if (object instanceof java.lang.String) {
            writeWStringValue((String)object);
        } else if (object instanceof java.lang.Class) {
            writeClass(repository_id, (Class)object);
        } else {
            // RMI-IIOP value type
            writeRMIIIOPValueType(object, clazz);
        }

        mustChunk = oldMustChunk;

        // Check to see if we need to start another block for a
        // possible outer value
        if (mustChunk)
            start_block();

    }
 
Example 24
Project: org.eclipse.ecr   File: ArrayProperty.java View source code Vote up 6 votes
@SuppressWarnings("unchecked")
@Override
public <T> T convertTo(Serializable value, Class<T> toType)
        throws PropertyConversionException {
    if (toType.isArray()) {
        return (T) PrimitiveArrays.toObjectArray(value);
    } else if (Collection.class.isAssignableFrom(toType)) {
        return (T) Arrays.asList((Object[]) value);
    }
    throw new PropertyConversionException(value.getClass(), toType);
}
 
Example 25
Project: seasar2   File: LobParameter.java View source code Vote up 6 votes
/**
 * ?????????????
 * 
 * @param value
 *            ?
 */
public LobParameter(final Serializable value) {
    this.value = value;
    if (value != null) {
        this.lobClass = value.getClass();
    } else {
        this.lobClass = Serializable.class;
    }
}
 
Example 26
Project: ManagedRuntimeInitiative   File: CDROutputStream_1_0.java View source code Vote up 6 votes
public void write_value(Serializable object, String repository_id) {

        // Handle null references
        if (object == null) {
            // Write null tag and return
            write_long(0);
            return;
        }

        // Handle shared references
        if (valueCache != null && valueCache.containsKey(object)) {
            writeIndirection(INDIRECTION_TAG, valueCache.getVal(object));
            return;
        }

        Class clazz = object.getClass();
        boolean oldMustChunk = mustChunk;

        if (mustChunk)
            mustChunk = true;

        if (inBlock)
            end_block();

        if (clazz.isArray()) {
            // Handle arrays
            writeArray(object, clazz);
        } else if (object instanceof org.omg.CORBA.portable.ValueBase) {
            // Handle IDL Value types
            writeValueBase((org.omg.CORBA.portable.ValueBase)object, clazz);
        } else if (shouldWriteAsIDLEntity(object)) {
            writeIDLEntity((IDLEntity)object);
        } else if (object instanceof java.lang.String) {
            writeWStringValue((String)object);
        } else if (object instanceof java.lang.Class) {
            writeClass(repository_id, (Class)object);
        } else {
            // RMI-IIOP value type
            writeRMIIIOPValueType(object, clazz);
        }

        mustChunk = oldMustChunk;

        // Check to see if we need to start another block for a
        // possible outer value
        if (mustChunk)
            start_block();

    }
 
Example 27
Project: sitebricks   File: DiskEntityStore.java View source code Vote up 6 votes
@Override
public <T> T find(Class<T> type, Serializable key) {
  // Reading methods do not lock.
  EntityMetadata.EntityDescriptor descriptor = metadata.of(type);
  String idField = descriptor.idField();
  EntityMetadata.MemberReader idReader = descriptor.fields().get(idField);

  if (!idReader.type().isAssignableFrom(key.getClass()))
    throw new IllegalArgumentException("Given key is not of compatible type with @Id field of "
        + type + ". Expected: " + idReader.type() + " but found: " + key.getClass());

  Map<String, EntityQuery.FieldMatcher<?>> query =
      new HashMap<String, EntityQuery.FieldMatcher<?>>(1);
  query.put(idField, EntityQuery.FieldMatcher.is(key));

  List<T> results = execute(type, query, 0, 1);
  return results != null ? results.get(0) : null;
}
 
Example 28
Project: openjdk   File: CDROutputStream_1_0.java View source code Vote up 6 votes
public void write_value(Serializable object, String repository_id) {

        // Handle null references
        if (object == null) {
            // Write null tag and return
            write_long(0);
            return;
        }

        // Handle shared references
        if (valueCache != null && valueCache.containsKey(object)) {
            writeIndirection(INDIRECTION_TAG, valueCache.getVal(object));
            return;
        }

        Class clazz = object.getClass();
        boolean oldMustChunk = mustChunk;

        if (mustChunk)
            mustChunk = true;

        if (inBlock)
            end_block();

        if (clazz.isArray()) {
            // Handle arrays
            writeArray(object, clazz);
        } else if (object instanceof org.omg.CORBA.portable.ValueBase) {
            // Handle IDL Value types
            writeValueBase((org.omg.CORBA.portable.ValueBase)object, clazz);
        } else if (shouldWriteAsIDLEntity(object)) {
            writeIDLEntity((IDLEntity)object);
        } else if (object instanceof java.lang.String) {
            writeWStringValue((String)object);
        } else if (object instanceof java.lang.Class) {
            writeClass(repository_id, (Class)object);
        } else {
            // RMI-IIOP value type
            writeRMIIIOPValueType(object, clazz);
        }

        mustChunk = oldMustChunk;

        // Check to see if we need to start another block for a
        // possible outer value
        if (mustChunk)
            start_block();

    }
 
Example 29
Project: kaleido-repository   File: JpaModelConfiguration.java View source code Vote up 6 votes
@Override
  protected Cache<String, Serializable> storeProperties(final ResourceHandler resourceHandler, final Cache<String, Serializable> properties)
   throws ResourceException, ConfigurationException {

ConfigurationModel configurationModel;
Query query = em.createQuery(Query_FindConfigurationByName.Jql);
query.setParameter(Query_FindConfigurationByName.Parameter_ConfigurationName, getName());

try {
   configurationModel = (ConfigurationModel) query.getSingleResult();
} catch (NoResultException nre) {
   configurationModel = new ConfigurationModel(getName(), getResourceUri());
   configurationModel.setLoaded(isLoaded());
   configurationModel.setUpdateable(isUpdateable());
   configurationModel.setStorable(isStorable());
}

// create configuration model if needed
em.merge(configurationModel);

// create each current configuration property
for (String key : keySet()) {
   ConfigurationProperty prop;
   Serializable value = getProperty(key);
   if (configurationModel.getPropertiesByName().containsKey(key)) {
	prop = configurationModel.getPropertiesByName().get(key);
   } else {
	prop = new ConfigurationProperty(key, value != null ? value.getClass() : String.class);
   }
   prop.setValue(value);
   prop.getConfigurations().add(configurationModel);
   configurationModel.getProperties().add(prop);
   em.merge(prop);
}

em.merge(configurationModel);
em.flush();

return properties;
  }
 
Example 30
Project: jradius   File: JRadiusSessionManager.java View source code Vote up 5 votes
/**
 * Returns a session object. First, a key is generated by
 * the session manager's key provider, based on the JRadiusRequest.
 * If there is a stored session based on the key, this session is
 * returned, otherwise a new session created by the session factory
 * is returned
 * @param request a JRadiusRequest used to retrieve or generate a session with
 * @return Returns a RadiusSession
 * @throws RadiusException
 */
public JRadiusSession getSession(JRadiusRequest request) throws RadiusException
{
    SessionKeyProvider skp = getSessionKeyProvider(request.getSender());
    Serializable key = skp.getAppSessionKey(request);
    JRadiusSession session = null;
    Serializable nkey = null;
    
    if (key != null) 
    {
        RadiusLog.debug("** Looking for session: " + key);
        
        session = getSession(request, key);
        if (session == null)
        {
            RadiusLog.error("Broken JRadius-Session-Id implementation for session: " + key);
            key = null;
        }
    }

    if (key == null)
    {
        key = skp.getClassKey(request);
        
        if (key != null) 
        {
            RadiusLog.debug("** Looking for session: " + key);
            
            session = getSession(request, key);
            if (session == null)
            {
                RadiusLog.error("Broken Class implementation for session: " + key);
                key = null;
            }
            else
            {
                if (session.getJRadiusKey() != null && !session.getJRadiusKey().equals(session.getSessionKey()))
                {
                    rehashSession(session, session.getJRadiusKey(), key);
                }
            }
        }
    }

    if (key == null)
    {
        Serializable keys = skp.getRequestSessionKey(request);
    
        if (keys == null)
        {
            return null;
        }
    
        if (keys instanceof Serializable[])
        {
            key = ((Serializable[])(keys))[0];
            nkey = ((Serializable[])(keys))[1];
            RadiusLog.debug("Rehashing session with key " + key + " under new key " + nkey);
        }
        else
        {
            key = keys;
        }
        
        RadiusLog.debug("** Looking for session: " + key);
        session = getSession(request, key);

        if (session != null && nkey != null && !nkey.equals(key))
        {
            rehashSession(session, key, nkey);
        }
    }        

    if (session == null) 
    {
        session = newSession(request, nkey == null ? key : nkey);
    }
    
    session.setTimeStamp(System.currentTimeMillis());
    //session.setLastRadiusRequest(request);
    
    return session;
}
 
Example 31
Project: records-management   File: RecordServiceImpl.java View source code Vote up 5 votes
/**
 * Ensure that the user only updates record properties that they have permission to.
 *
 * @see org.alfresco.repo.node.NodeServicePolicies.OnUpdatePropertiesPolicy#onUpdateProperties(org.alfresco.service.cmr.repository.NodeRef, java.util.Map, java.util.Map)
 */
@Override
@Behaviour
(
        name = "onUpdateProperties",
        kind = BehaviourKind.CLASS,
        type= "rma:record"
)
public void onUpdateProperties(final NodeRef nodeRef, final Map<QName, Serializable> before, final Map<QName, Serializable> after)
{
    if (AuthenticationUtil.getFullyAuthenticatedUser() != null &&
        !AuthenticationUtil.isRunAsUserTheSystemUser() &&
        nodeService.exists(nodeRef) &&
        isRecord(nodeRef) &&
        !transactionalResourceHelper.getSet(KEY_IGNORE_ON_UPDATE).contains(nodeRef))
    {
        for (Map.Entry<QName, Serializable> entry : after.entrySet())
        {
            Serializable beforeValue = null;
            QName property = entry.getKey();
            if (before != null)
            {
                beforeValue = before.get(property);
            }

            Serializable afterValue = entry.getValue();
            boolean propertyUnchanged = false;
            if (beforeValue instanceof Date && afterValue instanceof Date)
            {
                // deal with date values, remove the seconds and milliseconds for the
            	// comparison as they are removed from the submitted for data
            	Calendar beforeCal = Calendar.getInstance();
            	beforeCal.setTime((Date)beforeValue);
            	Calendar afterCal = Calendar.getInstance();
            	afterCal.setTime((Date)afterValue);
            	beforeCal.set(Calendar.SECOND, 0);
            	beforeCal.set(Calendar.MILLISECOND, 0);
            	afterCal.set(Calendar.SECOND, 0);
            	afterCal.set(Calendar.MILLISECOND, 0);
            	propertyUnchanged = (beforeCal.compareTo(afterCal) == 0);
            }
            else if ((afterValue instanceof Boolean) && (beforeValue == null) && (afterValue.equals(Boolean.FALSE)))
            {
        		propertyUnchanged = true;
            }
            else
            {
                // otherwise
                propertyUnchanged = EqualsHelper.nullSafeEquals(beforeValue, afterValue);
            }

            if (!propertyUnchanged &&
                !(ContentModel.PROP_CONTENT.equals(property) && beforeValue == null) &&
                !isPropertyEditable(nodeRef, property))
            {
                // the user can't edit the record property
                throw new ModelAccessDeniedException(
                        "The user " + AuthenticationUtil.getFullyAuthenticatedUser() +
                        " does not have the permission to edit the record property " + property.toString() +
                        " on the node " + nodeRef.toString());
            }
        }
    }
}
 
Example 32
Project: classpath   File: RmiUtilities.java View source code Vote up 5 votes
/**
 * Write all fields of the passed value.
 */
void writeFields(OutputStream an_output, Serializable object)
{
  org.omg.CORBA_2_3.portable.OutputStream output = (org.omg.CORBA_2_3.portable.OutputStream) an_output;
  try
    {
      Class o_class = object.getClass();
      Field[] fields = getWritableFields(o_class);
      Field f;

      Class fc;

      for (int i = 0; i < fields.length; i++)
        {
          f = fields[i];
          fc = f.getType();
          Object v = f.get(object);

          if (fc == String.class)
            {
              output.write_value((Serializable) v, wStringValueHelper);
            }
          else if (fc == int.class)
            output.write_long(((Integer) v).intValue());
          else if (fc == long.class)
            output.write_longlong(((Number) v).longValue());
          else if (fc == double.class)
            output.write_double(((Number) v).doubleValue());
          else if (fc == float.class)
            output.write_float(((Number) v).floatValue());
          else if (fc == boolean.class)
            output.write_boolean(((Boolean) v).booleanValue());
          else if (fc == short.class)
            output.write_short(((Number) v).shortValue());
          else if (fc == byte.class)
            output.write_octet(((Number) v).byteValue());
          else if (fc == char.class)
            output.write_wchar(((Character) v).charValue());
          else
            {
              if (!fc.isInterface() && Remote.class.isAssignableFrom(fc))
                fc = getExportedInterface(fc);
              writeMember(output, v, fc);
            }
        }
    }
  catch (Exception ex)
    {
      MARSHAL m = new MARSHAL("Cannot write " + object);
      m.minor = Minor.ValueFields;
      m.initCause(ex);
      throw m;
    }
}