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 generate more good examples.
Example 1
Project: alfresco-repository   File: ActivitiMultitenantWorkflowTest.java   Source Code and License 6 votes vote down vote up
/**
 * ALF-15939: Call-activity should be multi-tenant aware.
 */
public void testSubProcessCallActivity() throws Exception
{
	// Run as User1 so tenant domain 1
    AuthenticationUtil.setFullyAuthenticatedUser(user1);
    
    // Deploy called sub-process on tenant domain 1
    InputStream input = getInputStream(CALLACTIVITY_SUBPROCESS_LOCATION);
    WorkflowDeployment deployment = workflowService.deployDefinition(getEngine(), input, XML);
    
    // Deploy called main-process on tenant domain 1
    input = getInputStream(CALLACTIVITY_MAINPROCESS_LOCATION);
    deployment = workflowService.deployDefinition(getEngine(), input, XML);
    WorkflowDefinition mainProcessDefinition = deployment.getDefinition();
    
    // Start a process, which immediately tries to call the sub-process before returning control to thread
    try {
    	workflowService.startWorkflow(mainProcessDefinition.getId(), new HashMap<QName, Serializable>());
    } catch(Exception e) {
    	e.printStackTrace();
    	fail("No exception was expected while running process, but got: " + e.toString());
    }
}
 
Example 2
Project: backbone   File: BaseParser.java   Source Code and License 6 votes vote down vote up
private String getSelectField(String field, Query<? extends Serializable> query, boolean inWhere) {
    Class<?> beanType = query.getBeanType();
    AnnotationHolder ah = AnnotationHelper.getAnnotationHolder(field, beanType);
    if (ah == null) throw new IllegalArgumentException(" Can't find field `"+ field +"` in class["+ beanType +"]");

    String name = ah.getField().getName();
    if (!inWhere) {
        String ref = ah.getColumn().referenceField();
        if (SqlUtils.isNotBlank(ah.getOgnl())) {
            name = "`" + name + "` as `" + ah.getOgnl() + "." + ah.getField().getName() + "`";
        } else if (SqlUtils.isNotBlank(ref)) {
            name = "`" + name + "` as `" + ah.getField().getName() + "." + ref + "`";
        }
    }

    return name;
}
 
Example 3
Project: alfresco-repository   File: NodePropertyValue.java   Source Code and License 6 votes vote down vote up
@Override
Serializable convert(Serializable value)
{
    if (value == null)
    {
        return null;
    }
    else if (value instanceof Long)
    {
        return value;
    }
    else if (value instanceof ContentDataId)
    {
        return ((ContentDataId)value).getId();
    }
    else
    {
        return DefaultTypeConverter.INSTANCE.convert(ContentData.class, value);
    }
}
 
Example 4
Project: alfresco-repository   File: BaseNodeServiceTest.java   Source Code and License 6 votes vote down vote up
public void testAddProperties() throws Exception
{
    Map<QName, Serializable> properties = nodeService.getProperties(rootNodeRef);
    // Add an aspect with a default value
    nodeService.addAspect(rootNodeRef, ASPECT_QNAME_TEST_TITLED, null);
    assertNull("Expected null property", nodeService.getProperty(rootNodeRef, PROP_QNAME_TEST_TITLE));
    assertNull("Expected null property", nodeService.getProperty(rootNodeRef, PROP_QNAME_TEST_DESCRIPTION));
    
    // Now add a map of two properties and check
    Map<QName, Serializable> addProperties = new HashMap<QName, Serializable>(11);
    addProperties.put(PROP_QNAME_TEST_TITLE, "Title");
    addProperties.put(PROP_QNAME_TEST_DESCRIPTION, "Description");
    nodeService.addProperties(rootNodeRef, addProperties);
    
    // Check
    Map<QName, Serializable> checkProperties = nodeService.getProperties(rootNodeRef);
    assertEquals("Title", checkProperties.get(PROP_QNAME_TEST_TITLE));
    assertEquals("Description", checkProperties.get(PROP_QNAME_TEST_DESCRIPTION));
}
 
Example 5
Project: alfresco-repository   File: TikaAutoMetadataExtracterTest.java   Source Code and License 6 votes vote down vote up
private Map<String, Serializable> openAndCheck(String fileBase, String expMimeType) throws Throwable {
   // Get the mimetype via the MimeTypeMap 
   // (Uses Tika internally for the detection)
   File file = open(fileBase);
   ContentReader detectReader = new FileContentReader(file);
   String mimetype = mimetypeMap.guessMimetype(fileBase, detectReader);

   assertEquals("Wrong mimetype for " + fileBase, mimetype, expMimeType);
   
   // Ensure the Tika Auto parser actually handles this
   assertTrue("Mimetype should be supported but isn't: " + mimetype, extracter.isSupported(mimetype));
   
   // Now create our proper reader
   ContentReader sourceReader = new FileContentReader(file);
   sourceReader.setMimetype(mimetype);
   
   // And finally do the properties extraction
   return extracter.extractRaw(sourceReader);
}
 
Example 6
Project: alfresco-remote-api   File: NodesImpl.java   Source Code and License 6 votes vote down vote up
private NodeRef createNodeImpl(NodeRef parentNodeRef, String nodeName, QName nodeTypeQName, Map<QName, Serializable> props, QName assocTypeQName)
{
    NodeRef newNode = null;
    if (props == null)
    {
        props = new HashMap<>(1);
    }
    props.put(ContentModel.PROP_NAME, nodeName);

    validatePropValues(props);

    QName assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, QName.createValidLocalName(nodeName));
    try
    {
        newNode = nodeService.createNode(parentNodeRef, assocTypeQName, assocQName, nodeTypeQName, props).getChildRef();
    }
    catch (DuplicateChildNodeNameException dcne)
    {
        // duplicate - name clash
        throw new ConstraintViolatedException(dcne.getMessage());
    }

    ActivityInfo activityInfo =  getActivityInfo(parentNodeRef, newNode);
    postActivity(Activity_Type.ADDED, activityInfo, false);
    return newNode;
}
 
Example 7
Project: lazycat   File: XByteBuffer.java   Source Code and License 6 votes vote down vote up
public static Serializable deserialize(byte[] data, int offset, int length, ClassLoader[] cls)
		throws IOException, ClassNotFoundException, ClassCastException {
	invokecount.addAndGet(1);
	Object message = null;
	if (cls == null)
		cls = new ClassLoader[0];
	if (data != null && length > 0) {
		InputStream instream = new ByteArrayInputStream(data, offset, length);
		ObjectInputStream stream = null;
		stream = (cls.length > 0) ? new ReplicationStream(instream, cls) : new ObjectInputStream(instream);
		message = stream.readObject();
		instream.close();
		stream.close();
	}
	if (message == null) {
		return null;
	} else if (message instanceof Serializable)
		return (Serializable) message;
	else {
		throw new ClassCastException("Message has the wrong class. It should implement Serializable, instead it is:"
				+ message.getClass().getName());
	}
}
 
Example 8
Project: Spring-Shiro-Spark   File: ShiroSessionDao.java   Source Code and License 6 votes vote down vote up
@Override
protected Session doReadSession(Serializable sessionId) {
    logger.debug("begin doReadSession {}", sessionId);
    Jedis jedis = jedisPool.getResource();
    Session session = null;
    try {
        String key = prefix + sessionId;
        String value = jedis.get(key);
        if(StringUtils.isNotBlank(value)){
            session = SerializeUtils.deserializeFromString(value);
            logger.info("sessionId {} ttl {}: ", sessionId, jedis.ttl(key));
            //重置Redis中缓存过期的时间
            jedis.expire(key,expireTime);
            logger.info("sessionId {} name {} 被读取", sessionId, session.getClass().getName());
        }
    } catch (Exception e){
        logger.warn("读取session失败");
    } finally {
        jedis.close();
    }
    return session;
}
 
Example 9
Project: Equella   File: ClusteredTaskServiceImpl.java   Source Code and License 6 votes vote down vote up
protected Serializable[] getArgsForTask(ClusteredTaskWithArgs withArgs)
{
	String argsId = withArgs.getArgsId();
	if( argsId != null )
	{
		String nodeId = withArgs.getNodeId();
		if( nodeId.equals(ourNodeId) )
		{
			Serializable[] args = taskArgs.getIfPresent(argsId);
			taskArgs.invalidate(argsId);
			return args;
		}
		else
		{
			BlockingQueue<SimpleMessage> mq = createResponseQueue(argsId);
			clusterMessagingService.postMessage(nodeId, new ArgsMessage(argsId, ourNodeId));
			ArgsMessage argsResponse = waitForResponse(5000, mq);
			return argsResponse.getArgs();
		}
	}
	else
	{
		return withArgs.getArgs();
	}
}
 
Example 10
Project: neoscada   File: DataNode.java   Source Code and License 6 votes vote down vote up
/**
 * Create a new data node and fill it with the serialized representation of
 * the data object provided.
 * 
 * @param id
 *            the node id
 * @param data
 *            the data to serialize
 */
public DataNode ( final String id, final Serializable data )
{
    this.id = id;

    if ( data == null )
    {
        this.data = null;
    }
    else
    {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream ();
        try
        {
            final ObjectOutputStream os = new ObjectOutputStream ( bos );
            os.writeObject ( data );
            os.close ();
            this.data = bos.toByteArray ();
        }
        catch ( final IOException e )
        {
            throw new RuntimeException ( "Failed to store data node", e );
        }
    }
}
 
Example 11
Project: lazycat   File: SerializablePrincipal.java   Source Code and License 6 votes vote down vote up
public static void writePrincipal(GenericPrincipal p, ObjectOutput out) throws IOException {
	out.writeUTF(p.getName());
	out.writeBoolean(p.getPassword() != null);
	if (p.getPassword() != null)
		out.writeUTF(p.getPassword());
	String[] roles = p.getRoles();
	if (roles == null)
		roles = new String[0];
	out.writeInt(roles.length);
	for (int i = 0; i < roles.length; i++)
		out.writeUTF(roles[i]);
	boolean hasUserPrincipal = (p != p.getUserPrincipal() && p.getUserPrincipal() instanceof Serializable);
	out.writeBoolean(hasUserPrincipal);
	if (hasUserPrincipal)
		out.writeObject(p.getUserPrincipal());
}
 
Example 12
Project: alfresco-repository   File: CheckOutCheckInServiceImplTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test when the aspect is not set when check-in is performed
 */
public void testVersionAspectNotSetOnCheckIn()
{
    // Create a bag of props
    Map<QName, Serializable> bagOfProps = createTypePropertyBag();
    bagOfProps.put(ContentModel.PROP_CONTENT, new ContentData(null, MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, "UTF-8"));

    // Create a new node 
    ChildAssociationRef childAssocRef = nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("test"),
            ContentModel.TYPE_CONTENT,
            bagOfProps);
    NodeRef noVersionNodeRef = childAssocRef.getChildRef();
    
    // Check out and check in
    NodeRef workingCopy = cociService.checkout(noVersionNodeRef);
    cociService.checkin(workingCopy, new HashMap<String, Serializable>());
    
    // Check that the origional node has no version history dispite sending verion props
    assertNull(this.versionService.getVersionHistory(noVersionNodeRef));        
}
 
Example 13
Project: alfresco-repository   File: AccessAuditorTest.java   Source Code and License 6 votes vote down vote up
@Test
public final void test02OnCopyComplete() throws Exception
{
  serviceRegistry.getFileFolderService().copy(content2, folder1, null); // keep leaf name

  txn.commit();
  txn = null;
  
  // TODO do we record the parent or the full path? Do we need to?

  assertEquals(1, auditMapList.size());
  Map<String, Serializable> auditMap = auditMapList.get(0);
  assertEquals("COPY", auditMap.get("action"));
  assertContains("createNode", auditMap.get("sub-actions"));
  assertContains("updateNodeProperties", auditMap.get("sub-actions"));
  assertContains("addNodeAspect", auditMap.get("sub-actions"));
  assertContains("copyNode", auditMap.get("sub-actions"));
  assertEquals("/cm:homeFolder/cm:folder1/cm:content2", auditMap.get("path"));
  assertEquals("/cm:homeFolder/cm:folder2/cm:content2", auditMap.get("copy/from/path"));
  assertEquals("cm:content", auditMap.get("type"));
}
 
Example 14
Project: alfresco-repository   File: VersionServiceImplTest.java   Source Code and License 6 votes vote down vote up
public void testAR807() 
{
	QName prop = QName.createQName("http://www.alfresco.org/test/versionstorebasetest/1.0", "intProp");
	
    ChildAssociationRef childAssociation = 
    	nodeService.createNode(this.rootNodeRef, 
                				 ContentModel.ASSOC_CHILDREN, 
                				 QName.createQName("http://www.alfresco.org/test/versionstorebasetest/1.0", "integerTest"), 
                				 TEST_TYPE_QNAME);
    NodeRef newNode = childAssociation.getChildRef();
    nodeService.setProperty(newNode, prop, 1);

    Object editionCode = nodeService.getProperty(newNode, prop);
    assertEquals(editionCode.getClass(), Integer.class);

    Map<String, Serializable> versionProps = new HashMap<String, Serializable>(1);
    versionProps.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
    Version version = versionService.createVersion(newNode, versionProps);

    NodeRef versionNodeRef = version.getFrozenStateNodeRef();
    assertNotNull(versionNodeRef);
    
    Object editionCodeArchive = nodeService.getProperty(versionNodeRef, prop);
    assertEquals(editionCodeArchive.getClass(), Integer.class);
}
 
Example 15
Project: parabuild-ci   File: PersistentCollection.java   Source Code and License 6 votes vote down vote up
static void identityRemove(Collection list, Object object, SessionImplementor session) 
throws HibernateException {
	
	if ( object!=null && session.isSaved(object) ) {
	
		Serializable idOfCurrent = session.getEntityIdentifierIfNotUnsaved(object);
		Iterator iter = list.iterator();
		while ( iter.hasNext() ) {
			Serializable idOfOld = session.getEntityIdentifierIfNotUnsaved( iter.next() );
			if ( idOfCurrent.equals(idOfOld) ) {
				iter.remove();
				break;
			}
		}
		
	}
}
 
Example 16
Project: scanning   File: SampleInformationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDialog() throws Exception {
	Shell shell = bot.shell("Sample").widget;

	List<Exception> errors = new ArrayList<>();
	shell.getDisplay().syncExec(()->{
		try {
			// Intentionally loose generics here because the
			// ModelCellEditor cannot type check so we mimik
			// what it does to reproduce an old defect
			IModelDialog dialog = interfaceService.createModelDialog(shell);
			dialog.create();
			dialog.setModel((Serializable)config);
		} catch (Exception ne) {
			errors.add(ne);
		}
	});
	if (errors.size()>0) throw errors.get(0);
}
 
Example 17
Project: alfresco-repository   File: ScriptAction.java   Source Code and License 6 votes vote down vote up
/**
 * Return all the properties known about this node. The Map returned implements the Scriptable interface to allow access to the properties via JavaScript associative array
 * access. This means properties of a node can be access thus: <code>node.properties["name"]</code>
 * 
 * @return Map of properties for this Node.
 */
@SuppressWarnings("synthetic-access")
public Map<String, Serializable> getParameters()
{
    if (this.parameters == null)
    {
        // this Map implements the Scriptable interface for native JS syntax property access
        this.parameters = new ScriptableParameterMap<String, Serializable>();
        Map<String, Serializable> actionParams = this.action.getParameterValues();
        for (Map.Entry<String, Serializable> entry : actionParams.entrySet())
        {
            String name = entry.getKey();
            this.parameters.put(name, converter.convertActionParamForScript(name, entry.getValue()));
        }
        this.parameters.setModified(false);
    }
    return this.parameters;
}
 
Example 18
Project: alfresco-repository   File: ActivitiDueDatePropertyHandler.java   Source Code and License 5 votes vote down vote up
/**
* {@inheritDoc}
*/
@Override
protected Object handleDelegateTaskProperty(DelegateTask task, TypeDefinition type, QName key, Serializable value)
{
    checkType(key, value, Date.class);
    task.setDueDate((Date) value);
    return DO_NOT_ADD;
}
 
Example 19
Project: rekit-game   File: LevelManager.java   Source Code and License 5 votes vote down vote up
private static Serializable fromBase64(String s) {
	try {
		byte[] data = Base64.getDecoder().decode(s);
		ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
		Object o = ois.readObject();
		ois.close();
		return (Serializable) o;
	} catch (IOException | IllegalArgumentException | ClassNotFoundException e) {
		GameConf.GAME_LOGGER.error(e.getMessage());
		return null;
	}
}
 
Example 20
Project: lams   File: PersistentArrayHolder.java   Source Code and License 5 votes vote down vote up
@Override
public void initializeFromCache(CollectionPersister persister, Serializable disassembled, Object owner)
		throws HibernateException {
	final Serializable[] cached = (Serializable[]) disassembled;
	array = Array.newInstance( persister.getElementClass(), cached.length );

	for ( int i=0; i<cached.length; i++ ) {
		Array.set( array, i, persister.getElementType().assemble( cached[i], getSession(), owner ) );
	}
}
 
Example 21
Project: apache-tomcat-7.0.73-with-comment   File: RpcChannel.java   Source Code and License 5 votes vote down vote up
/**
 * Send a message and wait for the response.
 * @param destination Member[] - the destination for the message, and the members you request a reply from
 * @param message Serializable - the message you are sending out
 * @param rpcOptions int - FIRST_REPLY, MAJORITY_REPLY or ALL_REPLY
 * @param channelOptions channel sender options
 * @param timeout long - timeout in milliseconds, if no reply is received within this time null is returned
 * @return Response[] - an array of response objects.
 * @throws ChannelException
 */
public Response[] send(Member[] destination, 
                       Serializable message,
                       int rpcOptions, 
                       int channelOptions,
                       long timeout) throws ChannelException {
    
    if ( destination==null || destination.length == 0 ) return new Response[0];
    
    //avoid dead lock
    int sendOptions =
        channelOptions & ~Channel.SEND_OPTIONS_SYNCHRONIZED_ACK;
    
    RpcCollectorKey key = new RpcCollectorKey(UUIDGenerator.randomUUID(false));
    RpcCollector collector = new RpcCollector(key,rpcOptions,destination.length);
    try {
        synchronized (collector) {
            if ( rpcOptions != NO_REPLY ) responseMap.put(key, collector);
            RpcMessage rmsg = new RpcMessage(rpcId, key.id, message);
            channel.send(destination, rmsg, sendOptions);
            if ( rpcOptions != NO_REPLY ) collector.wait(timeout);
        }
    } catch ( InterruptedException ix ) {
        Thread.currentThread().interrupt();
    } finally {
        responseMap.remove(key);
    }
    return collector.getResponses();
}
 
Example 22
Project: alfresco-repository   File: JscriptWorkflowTask.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the value of the <code>properties</code> property
 * 
 * @return the properties
 */
public Scriptable getProperties()
{
    // instantiate ScriptableQNameMap<String, Serializable> properties
    // from WorkflowTasks's Map<QName, Serializable> properties
    ScriptableQNameMap<String, Serializable> properties = new ScriptableQNameMap<String, Serializable>(namespaceProvider);
    properties.putAll(task.getProperties());
    return properties;
}
 
Example 23
Project: sucok-framework   File: BaseDao.java   Source Code and License 5 votes vote down vote up
/**
 * 通过Ids列表查询对象列表
 *
 * @param ids
 * @return 返回查询出的所有列表
 */
public List<T> findByIds(List<ID> ids) {
	List<T> list = new ArrayList<>(ids.size());
	for (Serializable id : ids) {
		T item = em.find(entityClass, id);
		if (item != null) {
			list.add(item);
		}
	}
	return list;
}
 
Example 24
Project: alfresco-repository   File: ActivitiWorkflowEngine.java   Source Code and License 5 votes vote down vote up
private boolean checkPropertiesPresent(Map<QName, Object> expectedProperties, Map<QName, Serializable> props)
{
    for(Map.Entry<QName, Object> entry : expectedProperties.entrySet())
    {
        if(props.containsKey(entry.getKey())) 
        {
            Object requiredValue = entry.getValue();
            Object actualValue = props.get(entry.getKey());
            
            if(requiredValue != null)
            {
                if(!requiredValue.equals(actualValue))
                {
                    return false;
                }
                break;
            }
            else
            {
                if(actualValue != null)
                {
                    return false;
                }
                break;
            }
        }
        if(entry.getValue() != null)
        {
            // If variable is not found and required value is non null, start-task doesn't match
            return false;                    
        }
    }
    
    return true;
}
 
Example 25
Project: beaker-notebook-archive   File: CommMsgHandler.java   Source Code and License 5 votes vote down vote up
private void handleMsg(Message message) {
  Map<String, Serializable> commMap = message.getContent();
  Comm comm = kernel.getComm(getString(commMap, COMM_ID));
  logger.debug("Comm message handling, target name: " + (comm != null ? comm.getTargetName() : "undefined"));
  if (comm != null) {
    comm.handleMsg(message);
  }
}
 
Example 26
Project: openjdk-jdk10   File: PropertyChangeSupport.java   Source Code and License 5 votes vote down vote up
/**
 * @serialData Null terminated list of {@code PropertyChangeListeners}.
 * <p>
 * At serialization time we skip non-serializable listeners and
 * only serialize the serializable listeners.
 */
private void writeObject(ObjectOutputStream s) throws IOException {
    Hashtable<String, PropertyChangeSupport> children = null;
    PropertyChangeListener[] listeners = null;
    synchronized (this.map) {
        for (Entry<String, PropertyChangeListener[]> entry : this.map.getEntries()) {
            String property = entry.getKey();
            if (property == null) {
                listeners = entry.getValue();
            } else {
                if (children == null) {
                    children = new Hashtable<>();
                }
                PropertyChangeSupport pcs = new PropertyChangeSupport(this.source);
                pcs.map.set(null, entry.getValue());
                children.put(property, pcs);
            }
        }
    }
    ObjectOutputStream.PutField fields = s.putFields();
    fields.put("children", children);
    fields.put("source", this.source);
    fields.put("propertyChangeSupportSerializedDataVersion", 2);
    s.writeFields();

    if (listeners != null) {
        for (PropertyChangeListener l : listeners) {
            if (l instanceof Serializable) {
                s.writeObject(l);
            }
        }
    }
    s.writeObject(null);
}
 
Example 27
Project: alfresco-repository   File: CheckOutCheckInServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Extend(traitAPI=CheckOutCheckInServiceTrait.class,extensionAPI=CheckOutCheckInServiceExtension.class)
public NodeRef checkin(
        NodeRef workingCopyNodeRef,
        Map<String, Serializable> versionProperties, 
        String contentUrl) 
{
    return checkin(workingCopyNodeRef, versionProperties, contentUrl, false);
}
 
Example 28
Project: beaker-notebook-archive   File: MessageFactoryTest.java   Source Code and License 5 votes vote down vote up
public static Message getExecuteRequestMessage(String code) {
  Message message = new Message();
  Header header = new Header();
  header.setTypeEnum(JupyterMessages.EXECUTE_REQUEST);
  message.setHeader(header);
  HashMap<String, Serializable> content = new HashMap<>();
  content.put("code", code);
  message.setContent(content);
  return message;
}
 
Example 29
Project: EasyTransaction   File: DubboEasyTransRpcConsumerImpl.java   Source Code and License 5 votes vote down vote up
@Override
public <P extends EasyTransRequest<R, ?>, R extends Serializable> void callWithNoReturn(
		String appId, String busCode, String innerMethod, Map<String,Object> header, P params) {
	GenericService caller = getCaller(appId, busCode,params);
	caller.$invoke(innerMethod, new String[]{params.getClass().getName(), header.getClass().getName()}, new Object[]{params,header});
	return;
}
 
Example 30
Project: ArchUnit   File: FirstClassWithDependency.java   Source Code and License 5 votes vote down vote up
void first() {
    ClassHoldingDependencies instanceOne = new ClassHoldingDependencies();
    Object someOtherObject = new Object();
    Serializable someSerializable = new Serializable() {
    };
    instanceOne.setSomeInt(1);
    someOtherObject.toString();
    someSerializable.hashCode();
    instanceOne.someInt = 5;
}
 
Example 31
Project: objectbox-java   File: TestUtils.java   Source Code and License 5 votes vote down vote up
public static <T extends Serializable> T serializeDeserialize(T entity) throws IOException, ClassNotFoundException {
    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bytesOut);
    out.writeObject(entity);
    out.close();
    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytesOut.toByteArray()));
    Object entityDeserialized = in.readObject();
    in.close();
    return (T) entityDeserialized;
}
 
Example 32
Project: ipf-flow-manager   File: RenderedMessageEncryptEventListener.java   Source Code and License 5 votes vote down vote up
protected void encrypt(Object entityObject, Serializable id, Object[] state) {
    if (entityObject instanceof TextMessage) {
        TextMessage entity = (TextMessage) entityObject;
        if (state[0] instanceof String) {
                String decrypted = ((String) state[0]);
                String encryptedString = stringEncryptor.encrypt(decrypted);
                state[0] = encryptedString;
                entity.setText(encryptedString);
        }
    }
}
 
Example 33
Project: open-rmbt   File: SmoothGraph.java   Source Code and License 5 votes vote down vote up
@Override
public GraphData getGraphData() {
	final Bundle options = new Bundle();
	options.putLong(OPTION_STARTTIME, startTime);
	options.putSerializable(OPTION_VALUELIST, (Serializable) valueList);
	options.putParcelable(OPTION_FIRSTPOINT, firstPoint);

	return new GraphData(pathStroke, pathFill, paintStroke, paintFill, options);
}
 
Example 34
Project: tomcat7   File: AbstractReplicatedMap.java   Source Code and License 5 votes vote down vote up
@Override
public boolean accept(Serializable msg, Member sender) {
    boolean result = false;
    if (msg instanceof MapMessage) {
        if ( log.isTraceEnabled() ) log.trace("Map["+mapname+"] accepting...."+msg);
        result = Arrays.equals(mapContextName, ( (MapMessage) msg).getMapId());
        if ( log.isTraceEnabled() ) log.trace("Msg["+mapname+"] accepted["+result+"]...."+msg);
    }
    return result;
}
 
Example 35
Project: alfresco-repository   File: TransitionSimpleWorkflowActionExecuterTest.java   Source Code and License 5 votes vote down vote up
private void addWorkflowAspect(NodeRef node, NodeRef destinationFolder, Boolean moveOnApprove, Boolean moveOnReject)
{
    // Set up workflow details on the node
    Map<QName, Serializable> propertyValues = createWorkflowProperties(destinationFolder, moveOnApprove, moveOnReject);

    // Apply the simple workflow aspect to the node
    this.nodeService.addAspect(node, ApplicationModel.ASPECT_SIMPLE_WORKFLOW, propertyValues);
}
 
Example 36
Project: gitplex-mit   File: HibernateInterceptor.java   Source Code and License 5 votes vote down vote up
@Override
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames,
		Type[] types) throws CallbackException {
	boolean changed = false;
	for (PersistListener listener: listeners) {
		if (listener.onLoad(entity, id, state, propertyNames, types))
			changed = true;
	}
		
	return changed;
}
 
Example 37
Project: NotifyTools   File: BeanContextSupport.java   Source Code and License 5 votes vote down vote up
/**
 * Serializes children to the given object input stream.
 * <p>
 * The implementation iterates through all children and writes out pairs 
 * of child object and <code>BCSChild</code> object if the child is 
 * serializable (implements <code>Serialization</code>.</p>
 * <p>
 * This method is called by <code>writeObject()</code> if the context
 * works standalone. Or if this support object is a delegate of another 
 * <code>BeanContext</code> implementation, then this method should be 
 * called by the peer to avoid the 'chicken and egg' problem during
 * deserialization.</p>
 * 
 * @param oos   the stream to write
 * @throws IOException if I/O exception occurs
 */
public final void writeChildren(ObjectOutputStream oos) throws IOException {
    boolean origSer = serializing;
    serializing = true;

    try {
        int count = 0;
        synchronized (children) {
            for (Iterator iter = children.values().iterator(); iter
                    .hasNext();) {
                BCSChild bcsc = (BCSChild) iter.next();
                if (bcsc.child instanceof Serializable
                        && (bcsc.proxyPeer == null || bcsc.proxyPeer instanceof Serializable)) {
                    oos.writeObject(bcsc.child);
                    oos.writeObject(bcsc);
                    count++;
                }
            }
        }

        // what if count not equals to serializable?
        if (count != serializable) {
            throw new IOException(Messages.getString("beans.6F"));
        }
    } finally {
        serializing = origSer;
    }
}
 
Example 38
Project: alfresco-repository   File: PersonServiceImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Determine if the updated properties constitute a valid user update.
 * Currently we only check for updates to the user firstname, lastname
 * 
 * @param before Map<QName, Serializable>
 * @param after Map<QName, Serializable>
 * @return boolean
 */
private boolean validUserUpdateEvent(Map<QName, Serializable> before, Map<QName, Serializable> after)
{
	final String firstnameBefore = (String)before.get(ContentModel.PROP_FIRSTNAME);
    final String lastnameBefore  = (String)before.get(ContentModel.PROP_LASTNAME);
    final String firstnameAfter  = (String)after.get(ContentModel.PROP_FIRSTNAME);
    final String lastnameAfter   = (String)after.get(ContentModel.PROP_LASTNAME);
    
    boolean updatedFirstName = !EqualsHelper.nullSafeEquals(firstnameBefore, firstnameAfter);
    boolean updatedLastName  = !EqualsHelper.nullSafeEquals(lastnameBefore, lastnameAfter);
    
    return updatedFirstName || updatedLastName;
}
 
Example 39
Project: ArchUnit   File: HasParameterTypesTest.java   Source Code and License 5 votes vote down vote up
@Test
public void predicate_on_parameters_by_Class() {
    HasParameterTypes hasParameterTypes = newHasParameterTypes(String.class, Serializable.class);

    assertThat(parameterTypes(String.class, Serializable.class).apply(hasParameterTypes)).as("predicate matches").isTrue();
    assertThat(parameterTypes(String.class).apply(hasParameterTypes)).as("predicate matches").isFalse();
    assertThat(parameterTypes(Serializable.class).apply(hasParameterTypes)).as("predicate matches").isFalse();
    assertThat(parameterTypes(Object.class).apply(hasParameterTypes)).as("predicate matches").isFalse();
    assertThat(parameterTypes(String.class, Serializable.class).getDescription())
            .isEqualTo("parameter types [java.lang.String, java.io.Serializable]");
}
 
Example 40
Project: lams   File: BatchingEntityLoader.java   Source Code and License 5 votes vote down vote up
protected Object getObjectFromList(List results, Serializable id, SessionImplementor session) {
	for ( Object obj : results ) {
		final boolean equal = persister.getIdentifierType().isEqual(
				id,
				session.getContextEntityIdentifier( obj ),
				session.getFactory()
		);
		if ( equal ) {
			return obj;
		}
	}
	return null;
}
 
Example 41
Project: openaudible   File: DefaultTreeModel.java   Source Code and License 5 votes vote down vote up
private void writeObject(ObjectOutputStream s) throws IOException {
    Vector values = new Vector();

    s.defaultWriteObject();
    // Save the root, if its Serializable.
    if (root != null && root instanceof Serializable) {
        values.addElement("root");
        values.addElement(root);
    }
    s.writeObject(values);
}
 
Example 42
Project: rubenlagus-TelegramBots   File: AbsSender.java   Source Code and License 5 votes vote down vote up
public final void editMessageTextAsync(EditMessageText editMessageText, SentCallback<Serializable> sentCallback) throws TelegramApiException {
    if (editMessageText == null) {
        throw new TelegramApiException("Parameter editMessageText can not be null");
    }
    if (sentCallback == null) {
        throw new TelegramApiException("Parameter sentCallback can not be null");
    }

    sendApiMethodAsync(editMessageText, sentCallback);
}
 
Example 43
Project: lams   File: DefaultResolveNaturalIdEventListener.java   Source Code and License 5 votes vote down vote up
/**
 * Performs the process of loading an entity from the configured
 * underlying datasource.
 * 
 * @param event The load event
 *
 * @return The object loaded from the datasource, or null if not found.
 */
protected Serializable loadFromDatasource(final ResolveNaturalIdEvent event) {
	final SessionFactoryImplementor factory = event.getSession().getFactory();
	final boolean stats = factory.getStatistics().isStatisticsEnabled();
	long startTime = 0;
	if ( stats ) {
		startTime = System.nanoTime();
	}
	
	final Serializable pk = event.getEntityPersister().loadEntityIdByNaturalId(
			event.getOrderedNaturalIdValues(),
			event.getLockOptions(),
			event.getSession()
	);
	
	if ( stats ) {
		final NaturalIdRegionAccessStrategy naturalIdCacheAccessStrategy = event.getEntityPersister().getNaturalIdCacheAccessStrategy();
		final String regionName = naturalIdCacheAccessStrategy == null ? null : naturalIdCacheAccessStrategy.getRegion().getName();
		final long endTime = System.nanoTime();
		final long milliseconds = TimeUnit.MILLISECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS );
		factory.getStatisticsImplementor().naturalIdQueryExecuted(
				regionName,
				milliseconds );
	}
	
	//PK can be null if the entity doesn't exist
	if (pk != null) {
		event.getSession().getPersistenceContext().getNaturalIdHelper().cacheNaturalIdCrossReferenceFromLoad(
				event.getEntityPersister(),
				pk,
				event.getOrderedNaturalIdValues()
		);
	}
	
	return pk;
}
 
Example 44
Project: openjdk-jdk10   File: ProfilingInfoTest.java   Source Code and License 5 votes vote down vote up
public static Serializable checkCastSnippet(Object obj) {
    try {
        return (Serializable) obj;
    } catch (ClassCastException e) {
        return null;
    }
}
 
Example 45
Project: alfresco-repository   File: FavouritesServiceImpl.java   Source Code and License 5 votes vote down vote up
private PersonFavourite addFavouriteSite(String userName, NodeRef nodeRef)
{
	PersonFavourite favourite = null;

	SiteInfo siteInfo = siteService.getSite(nodeRef);
	if(siteInfo != null)
	{
 	favourite = getFavouriteSite(userName, siteInfo);
 	if(favourite == null)
 	{
 		Map<String, Serializable> preferences = new HashMap<String, Serializable>(1);
	
 		String siteFavouritedKey = siteFavouritedKey(siteInfo);
 		preferences.put(siteFavouritedKey, Boolean.TRUE);

 		// ISO8601 string format: PreferenceService works with strings only for dates it seems
 		String siteCreatedAtKey = siteCreatedAtKey(siteInfo);
 		Date createdAt = new Date();
 		String createdAtStr = ISO8601DateFormat.format(createdAt);
 		preferences.put(siteCreatedAtKey, createdAtStr);
	
 		preferenceService.setPreferences(userName, preferences);
	
 		favourite = new PersonFavourite(userName, siteInfo.getNodeRef(), Type.SITE, siteInfo.getTitle(), createdAt);
	
 		QName nodeClass = nodeService.getType(nodeRef);
         OnAddFavouritePolicy policy = onAddFavouriteDelegate.get(nodeRef, nodeClass);
         policy.onAddFavourite(userName, nodeRef);
 	}
	}
	else
	{
		// shouldn't happen, getType recognizes it as a site or subtype
		logger.warn("Unable to get site for " + nodeRef);
	}

	return favourite;
}
 
Example 46
Project: alfresco-repository   File: NodePropertyValue.java   Source Code and License 4 votes vote down vote up
@Override
protected ValueType getPersistedType(Serializable value)
{
    return ValueType.STRING;
}
 
Example 47
Project: lams   File: IdentifierValue.java   Source Code and License 4 votes vote down vote up
@Override
public Serializable getDefaultValue(Object currentValue) {
	return value;
}
 
Example 48
Project: lams   File: ResolveNaturalIdEvent.java   Source Code and License 4 votes vote down vote up
public void setEntityId(Serializable entityId) {
	this.entityId = entityId;
}
 
Example 49
Project: Equella   File: HibernateEscapedString.java   Source Code and License 4 votes vote down vote up
@Override
public Serializable disassemble(Object value)
{
	return (Serializable) deepCopy(value);
}
 
Example 50
Project: alfresco-repository   File: NodeRefPropertyMethodInterceptorTest.java   Source Code and License 4 votes vote down vote up
public void testAddAspectNodeRefList()
{
    NodeRef invalidNodeRef = new NodeRef(rootNodeRef.getStoreRef(), "InvalidNode");

    NodeRef n1 = mlAwareNodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{namespace}one"), ContentModel.TYPE_FOLDER).getChildRef();

    NodeRef cat = mlAwareNodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{namespace}cat"), ContentModel.TYPE_CATEGORY).getChildRef();

    HashMap<QName, Serializable> properties1 = new HashMap<QName, Serializable>();
    HashMap<QName, Serializable> properties2 = new HashMap<QName, Serializable>();
    HashMap<QName, Serializable> properties3 = new HashMap<QName, Serializable>();
    HashMap<QName, Serializable> properties4 = new HashMap<QName, Serializable>();
    ArrayList<NodeRef> vals = new ArrayList<NodeRef>();
    vals.add(rootNodeRef);
    properties2.put(aspectCategoriesProp, vals);
    properties4.put(aspectNoderefsProp, vals);

    // Add aspect

    nodeService.addAspect(n1, categoryAspect, properties1);
    nodeService.addAspect(n1, categoriesAspect, properties2);
    nodeService.addAspect(n1, noderefAspect, properties3);
    nodeService.addAspect(n1, noderefsAspect, properties4);

    assertNotNull(mlAwareNodeService.getProperty(n1, aspectCategoriesProp));
    assertEquals(0, ((Collection) mlAwareNodeService.getProperty(n1, aspectCategoriesProp)).size());
    assertNotNull(mlAwareNodeService.getProperty(n1, aspectNoderefsProp));
    assertEquals(1, ((Collection) mlAwareNodeService.getProperty(n1, aspectNoderefsProp)).size());
    assertNotNull(mlAwareNodeService.getProperty(n1, aspectCategoriesProp));
    assertEquals(0, ((Collection) mlAwareNodeService.getProperty(n1, aspectCategoriesProp)).size());
    assertNotNull(mlAwareNodeService.getProperty(n1, aspectNoderefsProp));
    assertEquals(1, ((Collection) mlAwareNodeService.getProperty(n1, aspectNoderefsProp)).size());
    assertNotNull(nodeService.getProperties(n1).get(aspectCategoriesProp));
    assertEquals(0, ((Collection) nodeService.getProperties(n1).get(aspectCategoriesProp)).size());
    assertNotNull(nodeService.getProperties(n1).get(aspectNoderefsProp));
    assertEquals(1, ((Collection) nodeService.getProperties(n1).get(aspectNoderefsProp)).size());
    assertNotNull(nodeService.getProperties(n1).get(aspectCategoriesProp));
    assertEquals(0, ((Collection) nodeService.getProperties(n1).get(aspectCategoriesProp)).size());
    assertNotNull(nodeService.getProperties(n1).get(aspectNoderefsProp));
    assertEquals(1, ((Collection) nodeService.getProperties(n1).get(aspectNoderefsProp)).size());
}
 
Example 51
Project: alfresco-data-model   File: NotEquals.java   Source Code and License 4 votes vote down vote up
public Serializable getValue(Map<String, Argument> args, FunctionEvaluationContext context)
{
    throw new UnsupportedOperationException();
}
 
Example 52
Project: alfresco-repository   File: ResetPasswordServiceImpl.java   Source Code and License 4 votes vote down vote up
public Map<String, Serializable> getTemplateModel()
{
    return templateModel;
}
 
Example 53
Project: alfresco-repository   File: NodeRefPropertyMethodInterceptorTest.java   Source Code and License 4 votes vote down vote up
public void testAddAspectValidNode()
{
    NodeRef invalidNodeRef = new NodeRef(rootNodeRef.getStoreRef(), "InvalidNode");

    NodeRef n1 = mlAwareNodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{namespace}one"), ContentModel.TYPE_FOLDER).getChildRef();

    NodeRef cat = mlAwareNodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{namespace}cat"), ContentModel.TYPE_CATEGORY).getChildRef();

    HashMap<QName, Serializable> properties1 = new HashMap<QName, Serializable>();
    HashMap<QName, Serializable> properties2 = new HashMap<QName, Serializable>();
    HashMap<QName, Serializable> properties3 = new HashMap<QName, Serializable>();
    HashMap<QName, Serializable> properties4 = new HashMap<QName, Serializable>();
    properties1.put(aspectCategoryProp, rootNodeRef);
    properties2.put(aspectCategoriesProp, rootNodeRef);
    properties3.put(aspectNoderefProp, rootNodeRef);
    properties4.put(aspectNoderefsProp, rootNodeRef);

    // Add aspect

    nodeService.addAspect(n1, categoryAspect, properties1);
    nodeService.addAspect(n1, categoriesAspect, properties2);
    nodeService.addAspect(n1, noderefAspect, properties3);
    nodeService.addAspect(n1, noderefsAspect, properties4);

    assertNull(mlAwareNodeService.getProperty(n1, aspectCategoryProp));
    assertNull(mlAwareNodeService.getProperty(n1, aspectCategoriesProp));
    assertNotNull(mlAwareNodeService.getProperty(n1, aspectNoderefProp));
    assertNotNull(mlAwareNodeService.getProperty(n1, aspectNoderefsProp));
    assertNull(mlAwareNodeService.getProperties(n1).get(aspectCategoryProp));
    assertNull(mlAwareNodeService.getProperties(n1).get(aspectCategoriesProp));
    assertNotNull(mlAwareNodeService.getProperties(n1).get(aspectNoderefProp));
    assertNotNull(mlAwareNodeService.getProperties(n1).get(aspectNoderefsProp));
    assertNull(nodeService.getProperty(n1, aspectCategoryProp));
    assertNull(nodeService.getProperty(n1, aspectCategoriesProp));
    assertNotNull(nodeService.getProperty(n1, aspectNoderefProp));
    assertNotNull(nodeService.getProperty(n1, aspectNoderefsProp));
    assertNull(nodeService.getProperties(n1).get(aspectCategoryProp));
    assertNull(nodeService.getProperties(n1).get(aspectCategoriesProp));
    assertNotNull(nodeService.getProperties(n1).get(aspectNoderefProp));
    assertNotNull(nodeService.getProperties(n1).get(aspectNoderefsProp));
}
 
Example 54
Project: monarch   File: LocalThread.java   Source Code and License 4 votes vote down vote up
public LocalThread(Serializable locatility, ThreadInfo info) {
  this.locality = locatility;
  this.threadName = info.getThreadName();
  this.threadStack = generateThreadStack(info);
  this.threadId = info.getThreadId();
}
 
Example 55
Project: alfresco-repository   File: CMISConnector.java   Source Code and License 4 votes vote down vote up
public boolean handleAuditEntry(Long entryId, String user, long time, Map<String, Serializable> values)
{
    this.entryId = entryId;
    return true;
}
 
Example 56
Project: alfresco-repository   File: QuickShareServiceIntegrationTest.java   Source Code and License 4 votes vote down vote up
private Serializable getProperty(NodeRef nodeRef, QName property)
{
    return AuthenticationUtil.runAsSystem(() -> nodeService.getProperty(nodeRef, property));
}
 
Example 57
Project: azeroth   File: KafkaConsumerCommand.java   Source Code and License 4 votes vote down vote up
public ConsumerGroupInfo consumerGroup(String group) {
    KafkaConsumer<String, Serializable> kafkaConsumer = getConsumer(group);
    return consumerGroup(kafkaConsumer, group);
}
 
Example 58
Project: lams   File: PostUpdateEvent.java   Source Code and License 4 votes vote down vote up
public Serializable getId() {
	return id;
}
 
Example 59
Project: jdk8u-jdk   File: ProxyInputStream.java   Source Code and License 4 votes vote down vote up
@Override
public Serializable read_value(Serializable value) {
    return narrow().read_value(value);
}
 
Example 60
Project: kettle_support_kettle8.0   File: AccessControl2Filter.java   Source Code and License 4 votes vote down vote up
public void setCache(Cache<String, Deque<Serializable>> cache) {
	this.cache = cache;
}