Java Code Examples for java.io.Serializable

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.

Source file: Client.java

  18 
vote

Serializable readObject() throws IOException {
  Serializable ret=null;
  try {
    ret=(Serializable)inputStream.readObject();
  }
 catch (  final ClassNotFoundException e) {
    traceStack("readObject;classnotfoundexception",e);
    final IOException except=new IOException(Messages.Client_Class_Load_Failure_Protocol_Violation + e.getMessage());
    except.setStackTrace(e.getStackTrace());
    throw except;
  }
  return ret;
}
 

Example 2

From project bam, under directory /content/epn/src/main/java/org/overlord/bam/content/epn/.

Source file: ServiceResponseTimeProcessor.java

  18 
vote

/** 
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked") @Override public Serializable process(String source,Serializable event,int retriesLeft) throws Exception {
  Serializable ret=null;
  if (event instanceof ServiceDefinition) {
    ret=new java.util.LinkedList<ResponseTime>();
    ServiceDefinition sd=(ServiceDefinition)event;
    for (int j=0; j < sd.getOperations().size(); j++) {
      processOperation((java.util.LinkedList<ResponseTime>)ret,sd,sd.getOperations().get(j));
    }
    if (((java.util.LinkedList<Serializable>)ret).size() == 0) {
      ret=null;
    }
  }
  return (ret);
}
 

Example 3

From project bundlemaker, under directory /unittests/org.bundlemaker.core.itest/test-data/InnerClassTest/src/de/test/innertypes/.

Source file: A.java

  18 
vote

public A(){
  X x=new X();
  Serializable serializable=new Serializable(){
    @Override public String toString(){
      return new X2().toString();
    }
  }
;
}
 

Example 4

From project commons-io, under directory /src/test/java/org/apache/commons/io/.

Source file: TaggedIOExceptionTest.java

  18 
vote

public void testTaggedIOException(){
  Serializable tag=UUID.randomUUID();
  IOException exception=new IOException("Test exception");
  TaggedIOException tagged=new TaggedIOException(exception,tag);
  assertTrue(TaggedIOException.isTaggedWith(tagged,tag));
  assertFalse(TaggedIOException.isTaggedWith(tagged,UUID.randomUUID()));
  assertEquals(exception,tagged.getCause());
  assertEquals(exception.getMessage(),tagged.getMessage());
}
 

Example 5

From project dawn-ui, under directory /org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/tools/fitting/.

Source file: FittingTool.java

  18 
vote

protected void updatePlotServerConnection(FittedPeaks bean){
  if (bean == null)   return;
  if (plotServerConnection == null && getPart() instanceof IEditorPart) {
    this.plotServerConnection=new PlotServerConnection(((IEditorPart)getPart()).getEditorInput().getName());
  }
  if (plotServerConnection != null) {
    final Serializable peaks=(Serializable)bean.getPeakFunctions();
    if (peaks != null && !bean.isEmpty()) {
    }
  }
}
 

Example 6

From project dawn-workflow, under directory /org.dawb.passerelle.common/src/org/dawb/passerelle/common/message/.

Source file: DataMessageComponent.java

  18 
vote

/** 
 * Renames a list in the DataMessageComponent
 * @param existing
 * @param name
 * @return true if the name replaced was already there.
 */
public boolean renameList(String existing,String name){
  if (list == null)   return false;
  Map<String,Serializable> map=new LinkedHashMap<String,Serializable>(1);
  map.putAll(list);
  final Serializable set=map.remove(existing);
  if (set instanceof IDataset) {
    ((IDataset)set).setName(name);
  }
  boolean replaced=map.put(name,set) != null;
  this.list=map;
  return replaced;
}
 

Example 7

From project DirectMemory, under directory /DirectMemory-Cache/src/main/java/org/directmemory/serialization/.

Source file: StandardSerializer.java

  18 
vote

public Serializable deserialize(byte[] source,@SuppressWarnings({"rawtypes","unchecked"}) Class clazz) throws IOException, ClassNotFoundException {
  ByteArrayInputStream bis=new ByteArrayInputStream(source);
  ObjectInputStream ois=new ObjectInputStream(bis);
  Serializable obj=(Serializable)ois.readObject();
  ois.close();
  return obj;
}
 

Example 8

From project droolsjbpm-integration, under directory /drools-grid/drools-grid-impl/src/main/java/org/drools/grid/service/directory/impl/.

Source file: GridServiceDescriptionClient.java

  18 
vote

public Serializable getData(){
  InetSocketAddress[] sockets=(InetSocketAddress[])((Address)whitePagesGsd.getAddresses().get("socket")).getObject();
  CommandImpl cmd=new CommandImpl("GridServiceDescription.getData",null);
  Serializable data=(Serializable)sendMessage(this.conversationManager,sockets,whitePagesGsd.getId(),cmd);
  return data;
}
 

Example 9

From project AlarmApp-Android, under directory /src/org/alarmapp/model/classes/.

Source file: AlarmedUserData.java

  17 
vote

@SuppressWarnings("unchecked") public static AlarmedUserData create(Bundle bundle){
  Ensure.bundleHasKeys(bundle,OPERATION_ID,USER_ID,STATE,FIRST_NAME,LAST_NAME,ACK_DATE);
  AlarmedUserData a=new AlarmedUserData();
  a.ackDate=DateUtil.parse(bundle.getString(ACK_DATE));
  a.firstName=bundle.getString(FIRST_NAME);
  a.lastName=bundle.getString(LAST_NAME);
  a.state=AlarmState.create(bundle.getString(STATE));
  a.userId=bundle.getString(USER_ID);
  a.operationId=bundle.getString(OPERATION_ID);
  if (bundle.containsKey(FIREFIGHTER_POSITIONS)) {
    Serializable list=bundle.getSerializable(FIREFIGHTER_POSITIONS);
    if (list instanceof ArrayList<?>)     a.positions=(ArrayList<WayPoint>)list;
  }
  return a;
}
 

Example 10

From project apollo, under directory /injector/src/main/java/com/bskyb/cg/environments/hash/.

Source file: PersistentHash.java

  17 
vote

private synchronized void refreshFromStore(String dirname) throws IOException {
  FileInputStream fis;
  BufferedInputStream bis;
  Serializable messageEntry;
  ObjectInputStream ois;
  File emptyDir=new File(dirname);
  FilenameFilter onlyDat=new FileExtFilter(STOREFILEEXT);
  File[] files=emptyDir.listFiles(onlyDat);
  hash.clear();
  for (  File file : files) {
    fis=new FileInputStream(file);
    bis=new BufferedInputStream(fis);
    ois=new ObjectInputStream(bis);
    try {
      messageEntry=(Serializable)ois.readObject();
    }
 catch (    ClassNotFoundException e) {
      throw new IOException(e.toString());
    }
catch (    ClassCastException e) {
      throw new IOException(e.toString());
    }
catch (    StreamCorruptedException e) {
      throw new IOException(e.toString());
    }
    try {
      hash.put(file.getName(),(Message)messageEntry);
    }
 catch (    ClassCastException e) {
      throw new IOException(e.toString());
    }
    fis.close();
  }
}
 

Example 11

From project arquillian-extension-warp, under directory /impl/src/main/java/org/jboss/arquillian/warp/impl/client/transformation/.

Source file: MigratedAssertion.java

  17 
vote

@Override public MigrationResult process(String oldClassName,String newClassName,byte[] oldClassFile,ServerAssertion transformedAssertion) throws Exception {
  MigrationResult result=new MigrationResult();
  ClassPool pool=new ClassPool();
  CtClass clazz=pool.makeClassIfNew(new ByteArrayInputStream(oldClassFile));
  clazz.replaceClassName(oldClassName,newClassName);
  Class<Serializable> migratedClass=clazz.toClass();
  result.bytecode=clazz.toBytecode();
  try {
    Class<?> oldClass=transformedAssertion.getClass();
    Serializable migratedAssertion=migratedClass.newInstance();
    for (    Field newF : migratedClass.getDeclaredFields()) {
      if (java.lang.reflect.Modifier.isStatic(newF.getModifiers()) && java.lang.reflect.Modifier.isFinal(newF.getModifiers())) {
        continue;
      }
      Field oldF=oldClass.getDeclaredField(newF.getName());
      oldF.setAccessible(true);
      newF.setAccessible(true);
      newF.set(migratedAssertion,oldF.get(transformedAssertion));
    }
    result.serializedMigratedAssertion=SerializationUtils.serializeToBytes(migratedAssertion);
  }
 catch (  Exception e) {
    throw new IllegalStateException("Unable to clone " + transformedAssertion.getClass().getName() + " to migrated class "+ migratedClass.getName(),e);
  }
  return result;
}
 

Example 12

From project caseconductor-platform, under directory /utest-persistence/src/main/java/com/utest/dao/.

Source file: AuditTrailInterceptor.java

  17 
vote

@SuppressWarnings("unchecked") @Override public boolean onFlushDirty(final Object entity,final Serializable id,final Object[] currentState,final Object[] previousState,final String[] propertyNames,final Type[] types) throws CallbackException {
  boolean returnCode=false;
  if (entity instanceof TimelineVersionable) {
    returnCode=true;
    final Date date=new Date();
    final Integer userId=getCurrentUserId();
    setValue(currentState,propertyNames,"lastChangedBy",userId);
    setValue(currentState,propertyNames,"lastChangeDate",date);
  }
  if (entity.getClass().isAnnotationPresent(Audit.class)) {
    returnCode=true;
    final Session session=sessionFactory.openSession();
    final Class objectClass=entity.getClass();
    final String className=objectClass.getSimpleName();
    final Serializable persistedObjectId=getObjectId(entity);
    final Object preUpdateState=session.get(objectClass,persistedObjectId);
    try {
      logChanges(entity,preUpdateState,persistedObjectId,AuditRecord.UPDATE,className);
    }
 catch (    final Exception e) {
      e.printStackTrace();
    }
    session.close();
  }
  return returnCode;
}
 

Example 13

From project Cloud-Shout, under directory /ckdgcloudshout-Android/src/com/cloudshout/.

Source file: PlayerActivity.java

  17 
vote

public void OnCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  root=new RelativeLayout(this);
  mediaList=new ArrayList<SMILMedia>();
  Intent receive=getIntent();
  Bundle extras=receive.getExtras();
  Serializable test=extras.getSerializable("SMILObjects");
  if (test instanceof SerializeSO) {
    mediaList=((SerializeSO)test).getList();
    setMediaList(mediaList);
  }
  if (mediaList.isEmpty()) {
    Toast empty=Toast.makeText(this.getBaseContext(),"No Message",5000);
    empty.show();
  }
  setContentView(root);
}
 

Example 14

From project EasySOA, under directory /easysoa-registry/easysoa-registry-core/src/main/java/org/easysoa/services/.

Source file: DocumentServiceImpl.java

  17 
vote

public boolean mergeDocument(CoreSession session,DocumentModel from,DocumentModel to,boolean overwrite) throws ClientException {
  if (to.getType().equals(to.getType())) {
    for (    String schema : from.getDocumentType().getSchemaNames()) {
      Map<String,Object> schemaPropertiesFrom=from.getProperties(schema);
      Map<String,Object> schemaPropertiesTo=to.getProperties(schema);
      for (      Entry<String,Object> entry : schemaPropertiesFrom.entrySet()) {
        String property=entry.getKey();
        Serializable fromValue=(Serializable)entry.getValue();
        if (fromValue != null && (schemaPropertiesTo.get(property) == null || overwrite)) {
          to.setPropertyValue(property,fromValue);
        }
      }
    }
    session.removeDocument(from.getRef());
    return true;
  }
 else {
    return false;
  }
}
 

Example 15

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.

Source file: Webserver.java

  15 
vote

void save(Writer w) throws IOException {
  if (expired)   return;
  w.write(id);
  w.write(':');
  w.write(Integer.toString(inactiveInterval));
  w.write(':');
  w.write(servletContext == null || servletContext.getServletContextName() == null ? "" : servletContext.getServletContextName());
  w.write(':');
  w.write(Long.toString(lastAccessTime));
  w.write("\r\n");
  Enumeration<String> e=getAttributeNames();
  ByteArrayOutputStream os=new ByteArrayOutputStream(1024 * 16);
  while (e.hasMoreElements()) {
    String aname=(String)e.nextElement();
    Object so=get(aname);
    if (so instanceof Serializable) {
      os.reset();
      ObjectOutputStream oos=new ObjectOutputStream(os);
      try {
        oos.writeObject(so);
        w.write(aname);
        w.write(":");
        w.write(Utils.base64Encode(os.toByteArray()));
        w.write("\r\n");
      }
 catch (      IOException ioe) {
        servletContext.log("Can't replicate/store a session value of '" + aname + "' class:"+ so.getClass().getName(),ioe);
      }
    }
 else     servletContext.log("Non serializable session object has been " + so.getClass().getName() + " skiped in storing of "+ aname,null);
    if (so instanceof HttpSessionActivationListener)     ((HttpSessionActivationListener)so).sessionWillPassivate(new HttpSessionEvent((HttpSession)this));
  }
  w.write("$$\r\n");
}
 

Example 16

From project activemq-apollo, under directory /apollo-openwire/src/main/scala/org/apache/activemq/apollo/openwire/command/.

Source file: ActiveMQObjectMessage.java

  15 
vote

public void setObject(Serializable newObject) throws OpenwireException {
  checkReadOnlyBody();
  this.object=newObject;
  setContent(null);
  storeContent();
}
 

Example 17

From project airlift, under directory /testing/src/test/java/io/airlift/testing/.

Source file: TestAssertions.java

  15 
vote

@Test public void testAssertInstanceof(){
  passInstanceOf("hello",Object.class);
  passInstanceOf("hello",String.class);
  passInstanceOf("hello",Serializable.class);
  passInstanceOf("hello",CharSequence.class);
  passInstanceOf("hello",Comparable.class);
  passInstanceOf(42,Integer.class);
  failInstanceOf("hello",Integer.class);
}
 

Example 18

From project Airports, under directory /src/com/nadmm/airports/wx/.

Source file: NoaaService.java

  15 
vote

protected void sendSerializableResultIntent(String action,String stationId,Serializable result){
  Intent intent=makeResultIntent(action,TYPE_TEXT);
  intent.putExtra(STATION_ID,stationId);
  intent.putExtra(RESULT,result);
  sendResultIntent(intent);
}
 

Example 19

From project akubra, under directory /akubra-rmi/src/main/java/org/akubraproject/rmi/server/.

Source file: ServerXAResource.java

  15 
vote

public Xid[] recover(int flag) throws XAException {
  Xid[] ids=xaRes.recover(flag);
  if (ids == null)   return new Xid[0];
  for (int i=0; i < ids.length; i++)   if ((ids[i] != null) && !(ids[i] instanceof Serializable))   ids[i]=new SerializedXid(ids[i]);
  return ids;
}
 

Example 20

From project alphaportal_dev, under directory /sys-src/alphaportal/web/src/main/java/alpha/portal/webapp/controller/.

Source file: BaseFormController.java

  15 
vote

/** 
 * Convenience message to send messages to users, includes app URL as footer.
 * @param user the user to send a message to.
 * @param msg the message to send.
 * @param url the URL of the application.
 */
protected void sendUserMessage(final User user,final String msg,final String url){
  if (this.log.isDebugEnabled()) {
    this.log.debug("sending e-mail to user [" + user.getEmail() + "]...");
  }
  this.message.setTo(user.getFullName() + "<" + user.getEmail()+ ">");
  final Map<String,Serializable> model=new HashMap<String,Serializable>();
  model.put("user",user);
  model.put("message",msg);
  model.put("applicationURL",url);
  this.mailEngine.sendMessage(this.message,this.templateName,model);
}
 

Example 21

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/entity/.

Source file: SerializableEntity.java

  15 
vote

/** 
 * Creates new instance of this class.
 * @param ser input
 * @param bufferize tells whether the content should bestored in an internal buffer
 * @throws IOException in case of an I/O error
 */
public SerializableEntity(Serializable ser,boolean bufferize) throws IOException {
  super();
  if (ser == null) {
    throw new IllegalArgumentException("Source object may not be null");
  }
  if (bufferize) {
    createBytes(ser);
  }
 else {
    this.objRef=ser;
  }
}
 

Example 22

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/bean/.

Source file: PureJavaReflectionProvider.java

  15 
vote

public Object newInstance(Class type){
  try {
    Constructor[] constructors=type.getDeclaredConstructors();
    for (int i=0; i < constructors.length; i++) {
      if (constructors[i].getParameterTypes().length == 0) {
        if (!Modifier.isPublic(constructors[i].getModifiers())) {
          constructors[i].setAccessible(true);
        }
        return constructors[i].newInstance(new Object[0]);
      }
    }
    if (Serializable.class.isAssignableFrom(type)) {
      return instantiateUsingSerialization(type);
    }
 else {
      throw new ObjectAccessException("Cannot construct " + type.getName() + " as it does not have a no-args constructor");
    }
  }
 catch (  InstantiationException e) {
    throw new ObjectAccessException("Cannot construct " + type.getName(),e);
  }
catch (  IllegalAccessException e) {
    throw new ObjectAccessException("Cannot construct " + type.getName(),e);
  }
catch (  InvocationTargetException e) {
    if (e.getTargetException() instanceof RuntimeException) {
      throw (RuntimeException)e.getTargetException();
    }
 else     if (e.getTargetException() instanceof Error) {
      throw (Error)e.getTargetException();
    }
 else {
      throw new ObjectAccessException("Constructor for " + type.getName() + " threw an exception",e.getTargetException());
    }
  }
}
 

Example 23

From project Android, under directory /app/src/main/java/com/github/mobile/ui/gist/.

Source file: GistsViewActivity.java

  15 
vote

/** 
 * Create an intent to show gists with an initial selected Gist
 * @param gists
 * @param position
 * @return intent
 */
public static Intent createIntent(List<Gist> gists,int position){
  String[] ids=new String[gists.size()];
  int index=0;
  for (  Gist gist : gists)   ids[index++]=gist.getId();
  return new Builder("gists.VIEW").add(EXTRA_GIST_IDS,(Serializable)ids).add(EXTRA_POSITION,position).toIntent();
}
 

Example 24

From project android-client_2, under directory /src/org/mifos/androidclient/main/.

Source file: AccountDetailsActivity.java

  15 
vote

/** 
 * A handler of the button for disbursing a loan account.
 * @param view the view on which the pressed button resides
 */
public void onDisburseLoanSelected(View view){
  Intent intent=new Intent().setClass(this,DisburseLoanActivity.class);
  intent.putExtra(AbstractAccountDetails.ACCOUNT_NUMBER_BUNDLE_KEY,mDetails.getGlobalAccountNum());
  String originalPrincipal=((LoanAccountDetails)mDetails).getLoanSummary().getOriginalPrincipal();
  intent.putExtra(LoanSummary.ORIGINAL_PRINCIPAL_BUNDLE_KEY,originalPrincipal);
  List<AccountFee> onDisbursementFees=new ArrayList<AccountFee>();
  for (  AccountFee fee : ((LoanAccountDetails)mDetails).getAccountFees()) {
    if (fee.getFeeFrequencyTypeId().equals(AccountFee.FeeFrequency.ONE_TIME) && fee.getFeePaymentTypeId().equals(AccountFee.FeePayment.TIME_OF_DISBURSEMENT)) {
      onDisbursementFees.add(fee);
    }
  }
  intent.putExtra(AccountFee.BUNDLE_KEY,(Serializable)onDisbursementFees);
  intent.putExtra(AcceptedPaymentTypes.ACCEPTED_DISBURSEMENT_PAYMENT_TYPES_BUNDLE_KEY,(Serializable)mAcceptedPaymentTypes.asMap(mAcceptedPaymentTypes.getOutDisbursementList()));
  intent.putExtra(AcceptedPaymentTypes.ACCEPTED_FEE_PAYMENT_TYPES_BUNDLE_KEY,(Serializable)mAcceptedPaymentTypes.asMap(mAcceptedPaymentTypes.getOutFeeList()));
  startActivityForResult(intent,DisburseLoanActivity.REQUEST_CODE);
}
 

Example 25

From project androidannotations, under directory /AndroidAnnotations/functional-test-1-5-tests/src/test/java/com/xtremelabs/robolectric/shadows/.

Source file: CustomShadowBundle.java

  15 
vote

@Implementation public Serializable getSerializable(String key){
  Object o=mMap.get(key);
  if (o == null) {
    return null;
  }
  try {
    return (Serializable)o;
  }
 catch (  ClassCastException e) {
    return null;
  }
}
 

Example 26

From project AndroidCommon, under directory /src/com/asksven/android/common/utils/.

Source file: DataStorage.java

  15 
vote

public static boolean objectToFile(Context context,String fileName,Object serializableObject){
  boolean bRet=true;
  if (!(serializableObject instanceof java.io.Serializable)) {
    Log.e(TAG,"The object is not serializable: " + fileName);
    return false;
  }
  try {
    FileOutputStream fos=context.openFileOutput(fileName,Context.MODE_PRIVATE);
    ObjectOutputStream os=new ObjectOutputStream(fos);
    os.writeObject(serializableObject);
    os.close();
  }
 catch (  Exception e) {
    Log.e(TAG,"An error occured while writing " + fileName + " "+ e.getMessage());
    bRet=false;
  }
  return bRet;
}
 

Example 27

From project android_external_easymock, under directory /src/org/easymock/internal/.

Source file: Result.java

  15 
vote

public static Result createThrowResult(final Throwable throwable){
class ThrowingAnswer implements IAnswer<Object>, Serializable {
    private static final long serialVersionUID=-332797751209289222L;
    public Object answer() throws Throwable {
      throw throwable;
    }
    @Override public String toString(){
      return "Answer throwing " + throwable;
    }
  }
  return new Result(new ThrowingAnswer(),true);
}
 

Example 28

From project appengine-java-mapreduce, under directory /java/src/com/google/appengine/tools/mapreduce/impl/util/.

Source file: SerializationUtil.java

  15 
vote

public static byte[] serializeToByteArray(Serializable o){
  try {
    ByteArrayOutputStream bytes=new ByteArrayOutputStream();
    ObjectOutputStream out=new ObjectOutputStream(bytes);
    try {
      out.writeObject(o);
    }
  finally {
      out.close();
    }
    return bytes.toByteArray();
  }
 catch (  IOException e) {
    throw new RuntimeException("Can't serialize object: " + o,e);
  }
}
 

Example 29

From project arquillian-examples, under directory /jpalab/src/main/java/com/acme/jpa/business/.

Source file: RepositoryBean.java

  15 
vote

public <T extends Serializable>T save(final T entity){
  if (!em.contains(entity)) {
    return em.merge(entity);
  }
  return entity;
}
 

Example 30

From project arquillian-extension-drone, under directory /drone-webdriver/src/main/java/org/jboss/arquillian/drone/webdriver/factory/remote/reusable/.

Source file: ReusedSessionStoreImpl.java

  15 
vote

static ByteArray fromObject(Serializable object){
  ByteArray bytes=new ByteArray();
  try {
    bytes.raw=SerializationUtils.serializeToBytes(object);
    return bytes;
  }
 catch (  IOException e) {
    log.log(Level.FINE,"Unable to deserialize object of " + object.getClass().getName(),e);
  }
  return null;
}
 

Example 31

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/cache/.

Source file: CacheFactory.java

  15 
vote

/** 
 * Gets a cache specified by the given cache name.
 * @param cacheName the given cache name
 * @return a cache specified by the given cache name
 */
@SuppressWarnings("unchecked") public static synchronized Cache<String,? extends Serializable> getCache(final String cacheName){
  LOGGER.log(Level.INFO,"Constructing Cache[name={0}]....",cacheName);
  Cache<String,?> ret=CACHES.get(cacheName);
  try {
    if (null == ret) {
switch (Latkes.getRuntime("cache")) {
case LOCAL:
        final Class<Cache<String,?>> localLruCache=(Class<Cache<String,?>>)Class.forName("org.b3log.latke.cache.local.memory.LruMemoryCache");
      ret=localLruCache.newInstance();
    break;
case GAE:
  final Class<Cache<String,?>> gaeMemcache=(Class<Cache<String,?>>)Class.forName("org.b3log.latke.cache.gae.Memcache");
final Constructor<Cache<String,?>> gaeMemcacheConstructor=gaeMemcache.getConstructor(String.class);
ret=gaeMemcacheConstructor.newInstance(cacheName);
break;
case BAE:
final Class<Cache<String,?>> baeMemcache=(Class<Cache<String,?>>)Class.forName("org.b3log.latke.cache.NoCache");
final Constructor<Cache<String,?>> baeMemcacheConstructor=baeMemcache.getConstructor(String.class);
ret=baeMemcacheConstructor.newInstance(cacheName);
break;
default :
throw new RuntimeException("Latke runs in the hell.... Please set the enviornment correctly");
}
CACHES.put(cacheName,ret);
}
}
 catch (final Exception e) {
throw new RuntimeException("Can not get cache: " + e.getMessage(),e);
}
LOGGER.log(Level.INFO,"Constructed Cache[name={0}]",cacheName);
return (Cache<String,Serializable>)ret;
}
 

Example 32

From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/repository/impl/.

Source file: CommentRepositoryImpl.java

  15 
vote

@Override @SuppressWarnings("unchecked") public List<JSONObject> getRecentComments(final int num) throws RepositoryException {
  if (isCacheEnabled()) {
    final Cache<String,Serializable> cache=getCache();
    final Object ret=cache.get(RECENT_CMTS_CACHE_KEY);
    if (null != ret) {
      return (List<JSONObject>)ret;
    }
  }
  final Query query=new Query().addSort(Keys.OBJECT_ID,SortDirection.DESCENDING).setCurrentPageNum(1).setPageSize(num).setPageCount(1);
  List<JSONObject> ret;
  final JSONObject result=get(query);
  final JSONArray array=result.optJSONArray(Keys.RESULTS);
  ret=CollectionUtils.jsonArrayToList(array);
  removeForUnpublishedArticles(ret);
  if (isCacheEnabled()) {
    final Cache<String,Serializable> cache=getCache();
    cache.put(RECENT_CMTS_CACHE_KEY,(Serializable)ret);
  }
  return ret;
}
 

Example 33

From project BART, under directory /src/pro/dbro/bart/.

Source file: BartRouteParser.java

  15 
vote

private void sendMessage(routeResponse result){
  int status=4;
  Log.d("sender","Sending AsyncTask message");
  Intent intent=new Intent("service_status_change");
  intent.putExtra("status",status);
  intent.putExtra("result",(Serializable)result);
  intent.putExtra("updateUI",updateUI);
  LocalBroadcastManager.getInstance(TheActivity.c).sendBroadcast(intent);
}
 

Example 34

From project baseunits, under directory /src/test/java/jp/xet/baseunits/tests/.

Source file: SerializationTester.java

  15 
vote

/** 
 * ????€?????????????????????
 * @param serializable ????€????????????????
 * @throws AssertionError ????€??????????????
 */
public static void assertCanBeSerialized(Object serializable){
  if (Serializable.class.isInstance(serializable) == false) {
    fail("Object doesn't implement java.io.Serializable interface: " + serializable.getClass());
  }
  ObjectOutputStream out=null;
  ObjectInputStream in=null;
  ByteArrayOutputStream byteArrayOut=new ByteArrayOutputStream();
  ByteArrayInputStream byteArrayIn=null;
  try {
    out=new ObjectOutputStream(byteArrayOut);
    out.writeObject(serializable);
    byteArrayIn=new ByteArrayInputStream(byteArrayOut.toByteArray());
    in=new ObjectInputStream(byteArrayIn);
    Object deserialized=in.readObject();
    if (serializable.equals(deserialized) == false) {
      fail("Reconstituted object is expected to be equal to serialized");
    }
  }
 catch (  IOException e) {
    fail(e.getMessage());
  }
catch (  ClassNotFoundException e) {
    fail(e.getMessage());
  }
 finally {
    IOUtils.closeQuietly(out);
    IOUtils.closeQuietly(in);
  }
}
 

Example 35

From project bioportal-service, under directory /src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/rest/.

Source file: BioportalRestService.java

  15 
vote

/** 
 * Write cache.
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void writeCache(){
  log.info("Writing cache");
synchronized (cache) {
    if (cache instanceof Serializable) {
      FileOutputStream fos=null;
      ObjectOutputStream oos=null;
      try {
        File file=getCacheFile();
        fos=new FileOutputStream(file);
        oos=new ObjectOutputStream(fos);
        oos.writeObject((Serializable)Collections.synchronizedMap(cache));
      }
 catch (      Exception e) {
        throw new RuntimeException(e);
      }
 finally {
        try {
          if (fos != null) {
            fos.close();
          }
          if (oos != null) {
            oos.close();
          }
        }
 catch (        IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
 else {
      throw new RuntimeException(cache.getClass().getName() + " is not Serializable!");
    }
  }
}
 

Example 36

From project blueprint-namespaces, under directory /blueprint/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/.

Source file: FooRegistrationListener.java

  15 
vote

public void serviceRegistered(Serializable foo,Map props){
  System.out.println("Service registration notification: " + foo + " "+ props);
synchronized (lock) {
    this.props=props;
  }
}
 

Example 37

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/database/.

Source file: SerializationUtils.java

  15 
vote

/** 
 * Utility routine to convert a Serializable object to a byte array.
 * @param o		Object to convert
 * @return		Resulting byte array. NULL on failure.
 */
public static byte[] serializeObject(Serializable o){
  ByteArrayOutputStream bos=new ByteArrayOutputStream();
  ObjectOutput out;
  try {
    out=new ObjectOutputStream(bos);
    out.writeObject(o);
    out.close();
  }
 catch (  Exception e) {
    out=null;
  }
  byte[] buf;
  if (out != null) {
    buf=bos.toByteArray();
  }
 else {
    buf=null;
  }
  return buf;
}
 

Example 38

From project BookmarksPortlet, under directory /src/main/java/edu/wisc/my/portlets/bookmarks/domain/.

Source file: Folder.java

  15 
vote

private void writeObject(ObjectOutputStream out) throws IOException {
  out.defaultWriteObject();
  if (this.childComparator instanceof Serializable) {
    out.writeObject(this.childComparator);
  }
 else {
    out.writeObject(this.childComparator.getClass());
  }
}
 

Example 39

From project brix-cms, under directory /brix-core/src/main/java/org/brixcms/plugin/site/folder/.

Source file: CreateFolderPanel.java

  15 
vote

private void createFolder(){
  final JcrNode parent=(JcrNode)getModelObject();
  final Path path=new Path(parent.getPath());
  final Path newPath=path.append(new Path(name));
  final JcrSession session=parent.getSession();
  if (session.itemExists(newPath.toString())) {
class ModelObject implements Serializable {
      @SuppressWarnings("unused") public String path=SitePlugin.get().fromRealWebNodePath(newPath.toString());
    }
    ;
    String error=getString("resourceExists",new Model<ModelObject>(new ModelObject()));
    error(error);
  }
 else {
    FolderNode node=(FolderNode)parent.addNode(name,"nt:folder");
    parent.save();
    SitePlugin.get().selectNode(this,node,true);
  }
}
 

Example 40

From project camel-twitter, under directory /src/main/java/org/apache/camel/component/twitter/consumer/.

Source file: TwitterConsumerDirect.java

  15 
vote

@Override protected void doStart() throws Exception {
  super.doStart();
  Iterator<? extends Serializable> i=twitter4jConsumer.directConsume().iterator();
  while (i.hasNext()) {
    Exchange e=getEndpoint().createExchange();
    e.getIn().setBody(i.next());
    getProcessor().process(e);
  }
}
 

Example 41

From project candlepin, under directory /src/main/java/org/candlepin/pinsetter/core/.

Source file: PinsetterKernel.java

  15 
vote

public void cancelJob(Serializable id,String group) throws PinsetterException {
  try {
    if (scheduler.deleteJob(jobKey((String)id,group))) {
      log.info("canceled job " + group + ":"+ id+ " in scheduler");
    }
  }
 catch (  SchedulerException e) {
    throw new PinsetterException("problem canceling " + group + ":"+ id,e);
  }
}
 

Example 42

From project capedwarf-green, under directory /common/src/main/java/org/jboss/capedwarf/common/dto/.

Source file: DefaultDTOModelFactory.java

  15 
vote

@SuppressWarnings({"unchecked"}) public <E extends Serializable>DTOModel<E> createModel(Class<E> clazz){
  DTOModel model=models.get(clazz);
  if (model != null)   return model;
  model=createModelInternal(clazz);
  models.put(clazz,model);
  return model;
}
 

Example 43

From project cascading, under directory /src/core/cascading/operation/function/.

Source file: SetValue.java

  15 
vote

/** 
 * Constructor SetValue creates a new SetValue instance.
 * @param fieldDeclaration of type Fields
 * @param filter           of type Filter
 * @param firstValue       of type Serializable
 * @param secondValue      of type Serializable
 */
@ConstructorProperties({"fieldDeclaration","filter","values"}) public SetValue(Fields fieldDeclaration,Filter filter,Serializable firstValue,Serializable secondValue){
  super(fieldDeclaration);
  this.filter=filter;
  this.values=new Tuple[]{new Tuple(firstValue),new Tuple(secondValue)};
  verify();
}
 

Example 44

From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/util/.

Source file: SerializationUtils.java

  15 
vote

public static byte[] serializeToBytes(Serializable object){
  try {
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    ObjectOutputStream oos=new ObjectOutputStream(baos);
    oos.writeObject(object);
    return baos.toByteArray();
  }
 catch (  IOException e) {
    throw new IllegalStateException(e);
  }
}
 

Example 45

From project cmsandroid, under directory /src/com/zia/freshdocs/preference/.

Source file: CMISPreferencesManager.java

  15 
vote

protected void storePreferences(Context ctx,Map<String,CMISHost> map){
  SharedPreferences sharedPrefs=PreferenceManager.getDefaultSharedPreferences(ctx);
  byte[] encPrefs=Base64.encodeBase64(SerializationUtils.serialize((Serializable)map));
  Editor prefsEditor=sharedPrefs.edit();
  prefsEditor.putString(SERVERS_KEY,new String(encPrefs));
  prefsEditor.putBoolean(PREFS_SET_KEY,true);
  prefsEditor.commit();
}
 

Example 46

From project collections-generic, under directory /src/test/org/apache/commons/collections15/bag/.

Source file: AbstractTestBag.java

  15 
vote

public void testEmptyBagSerialization() throws IOException, ClassNotFoundException {
  Bag bag=makeBag();
  if (!(bag instanceof Serializable && isTestSerialization()))   return;
  byte[] objekt=writeExternalFormToBytes((Serializable)bag);
  Bag bag2=(Bag)readExternalFormFromBytes(objekt);
  assertEquals("Bag should be empty",0,bag.size());
  assertEquals("Bag should be empty",0,bag2.size());
}
 

Example 47

From project components, under directory /jca/src/main/java/org/switchyard/component/jca/composer/.

Source file: JMSMessageComposer.java

  15 
vote

/** 
 * {@inheritDoc}
 */
@Override public JMSBindingData decompose(Exchange exchange,JMSBindingData target) throws Exception {
  getContextMapper().mapTo(exchange.getContext(),target);
  Message jmsMessage=target.getMessage();
  ObjectMessage targetObj=ObjectMessage.class.cast(jmsMessage);
  targetObj.setObject(exchange.getMessage().getContent(Serializable.class));
  return target;
}
 

Example 48

From project Core_2, under directory /javaee-impl/src/main/java/org/jboss/forge/spec/javaee/jpa/.

Source file: EntityPlugin.java

  15 
vote

@SuppressWarnings("unchecked") @DefaultCommand(help="Create a JPA @Entity") public void newEntity(@Option(required=true,name="named",description="The @Entity name") final String entityName,@Option(required=false,name="package",type=PromptType.JAVA_PACKAGE,description="The package name") final String packageName,@Option(name="idStrategy",defaultValue="AUTO",description="The GenerationType name for the ID") final GenerationType idStrategy) throws Throwable {
  final PersistenceFacet jpa=project.getFacet(PersistenceFacet.class);
  final JavaSourceFacet java=project.getFacet(JavaSourceFacet.class);
  String entityPackage;
  if ((packageName != null) && !"".equals(packageName)) {
    entityPackage=packageName;
  }
 else   if (getPackagePortionOfCurrentDirectory() != null) {
    entityPackage=getPackagePortionOfCurrentDirectory();
  }
 else {
    entityPackage=shell.promptCommon("In which package you'd like to create this @Entity, or enter for default",PromptType.JAVA_PACKAGE,jpa.getEntityPackage());
  }
  JavaClass javaClass=JavaParser.create(JavaClass.class).setPackage(entityPackage).setName(entityName).setPublic().addAnnotation(Entity.class).getOrigin().addInterface(Serializable.class);
  Field<JavaClass> id=javaClass.addField("private Long id = null;");
  id.addAnnotation(Id.class);
  id.addAnnotation(GeneratedValue.class).setEnumValue("strategy",idStrategy);
  id.addAnnotation(Column.class).setStringValue("name","id").setLiteralValue("updatable","false").setLiteralValue("nullable","false");
  Field<JavaClass> version=javaClass.addField("private int version = 0;");
  version.addAnnotation(Version.class);
  version.addAnnotation(Column.class).setStringValue("name","version");
  Refactory.createGetterAndSetter(javaClass,id);
  Refactory.createGetterAndSetter(javaClass,version);
  Refactory.createToStringFromFields(javaClass,id);
  Refactory.createHashCodeAndEquals(javaClass);
  JavaResource javaFileLocation=java.saveJavaSource(javaClass);
  shell.println("Created @Entity [" + javaClass.getQualifiedName() + "]");
  shell.execute("pick-up " + javaFileLocation.getFullyQualifiedName().replace(" ","\\ "));
}
 

Example 49

From project core_5, under directory /exo.core.component.database/src/main/java/org/exoplatform/services/database/impl/.

Source file: HibernateServiceImpl.java

  15 
vote

@SuppressWarnings("rawtypes") public Object remove(Class clazz,Serializable id) throws Exception {
  Session session=openSession();
  Object obj=session.get(clazz,id);
  session.delete(obj);
  session.flush();
  return obj;
}
 

Example 50

From project culvert, under directory /culvert-accumulo/src/main/java/com/bah/culvert/accumulo/database/.

Source file: AccumuloTableAdapter.java

  15 
vote

@Override public <T>List<T> remoteExec(byte[] startKey,byte[] endKey,Class<? extends RemoteOp<T>> remoteCallable,Object... array){
  for (  Object o : array)   if (!(o instanceof Writable || o instanceof Serializable))   throw new IllegalArgumentException("Argument " + o + " is not serializable or writable!");
  try {
    RemoteOp operation=remoteCallable.newInstance();
    operation.setConf(this.getConf());
    operation.setLocalTableAdapter(new AccumuloLocalTableAdapter(this));
    return (List<T>)Arrays.asList(operation.call(array));
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 51

From project daily-money, under directory /dailymoney/src/com/bottleworks/dailymoney/data/.

Source file: Balance.java

  15 
vote

public Balance(String name,String type,double money,Serializable target){
  this.name=name;
  this.type=type;
  this.money=money;
  this.target=target;
}
 

Example 52

From project data-access, under directory /test-src/org/pentaho/platform/dataaccess/datasource/wizard/csv/.

Source file: FileUploadServiceTest.java

  15 
vote

/** 
 * Serialize the attributes of this session into an object that can be turned into a byte array with standard Java serialization.
 * @return a representation of this session's serialized state
 */
public Serializable serializeState(){
  HashMap state=new HashMap();
  for (Iterator it=this.attributes.entrySet().iterator(); it.hasNext(); ) {
    Map.Entry entry=(Map.Entry)it.next();
    String name=(String)entry.getKey();
    Object value=entry.getValue();
    it.remove();
    if (value instanceof Serializable) {
      state.put(name,value);
    }
 else {
      if (value instanceof HttpSessionBindingListener) {
        ((HttpSessionBindingListener)value).valueUnbound(new HttpSessionBindingEvent(this,name,value));
      }
    }
  }
  return state;
}
 

Example 53

From project des, under directory /daemon/lib/apache-log4j-1.2.16/tests/src/java/org/apache/log4j/or/.

Source file: ORTestCase.java

  15 
vote

public void test8(){
  RendererMap map=new RendererMap();
  map.put(Serializable.class,sor);
  ObjectRenderer r=map.get(Integer.class);
  assertEquals(r,sor);
}
 

Example 54

From project dharma-pm-portlet, under directory /docroot/WEB-INF/src/com/dharma/service/persistence/.

Source file: PMBlockedUserPersistenceImpl.java

  15 
vote

/** 
 * Removes the p m blocked user with the primary key from the database. Also notifies the appropriate model listeners.
 * @param primaryKey the primary key of the p m blocked user
 * @return the p m blocked user that was removed
 * @throws com.dharma.NoSuchPMBlockedUserException if a p m blocked user with the primary key could not be found
 * @throws SystemException if a system exception occurred
 */
@Override public PMBlockedUser remove(Serializable primaryKey) throws NoSuchPMBlockedUserException, SystemException {
  Session session=null;
  try {
    session=openSession();
    PMBlockedUser pmBlockedUser=(PMBlockedUser)session.get(PMBlockedUserImpl.class,primaryKey);
    if (pmBlockedUser == null) {
      if (_log.isWarnEnabled()) {
        _log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
      }
      throw new NoSuchPMBlockedUserException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
    }
    return remove(pmBlockedUser);
  }
 catch (  NoSuchPMBlockedUserException nsee) {
    throw nsee;
  }
catch (  Exception e) {
    throw processException(e);
  }
 finally {
    closeSession(session);
  }
}
 

Example 55

From project discovery, under directory /src/test/java/com/tacitknowledge/util/discovery/.

Source file: ClassCriteriaTest.java

  15 
vote

/** 
 * Valiates the normal operation of <code>matches</code> when matching on a single class.
 */
public void testMatchesMultipleInterfaces(){
  ClassCriteria criteria=new ClassCriteria(new Class[]{getClass(),Serializable.class});
  String className=getClass().getName().replace('.',File.separatorChar);
  assertTrue(criteria.matches(className + ".class"));
  assertFalse(criteria.matches(new File("java/lang/Object.class").getPath()));
  assertFalse(criteria.matches(new File("java/lang/String.class").getPath()));
}
 

Example 56

From project dl-usage-reports-portlet, under directory /docroot/WEB-INF/src/org/gnenc/dlusagereports/service/persistence/.

Source file: AllocatedStoragePersistenceImpl.java

  15 
vote

/** 
 * Removes the AllocatedStorage with the primary key from the database. Also notifies the appropriate model listeners.
 * @param primaryKey the primary key of the AllocatedStorage
 * @return the AllocatedStorage that was removed
 * @throws org.gnenc.dlusagereports.NoSuchAllocatedStorageException if a AllocatedStorage with the primary key could not be found
 * @throws SystemException if a system exception occurred
 */
@Override public AllocatedStorage remove(Serializable primaryKey) throws NoSuchAllocatedStorageException, SystemException {
  Session session=null;
  try {
    session=openSession();
    AllocatedStorage allocatedStorage=(AllocatedStorage)session.get(AllocatedStorageImpl.class,primaryKey);
    if (allocatedStorage == null) {
      if (_log.isWarnEnabled()) {
        _log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
      }
      throw new NoSuchAllocatedStorageException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
    }
    return remove(allocatedStorage);
  }
 catch (  NoSuchAllocatedStorageException nsee) {
    throw nsee;
  }
catch (  Exception e) {
    throw processException(e);
  }
 finally {
    closeSession(session);
  }
}
 

Example 57

From project dozer, under directory /core/src/test/java/org/dozer/functional_tests/.

Source file: ExceptionHandlingFunctionalTest.java

  15 
vote

@Test public void shouldRecoverOnInvalidMappingFile(){
  DozerBeanMapper mapper=new DozerBeanMapper(Arrays.asList(new String[]{"invalidmapping1.xml"}));
  Map<String,Serializable> src=new HashMap<String,Serializable>();
  src.put("field1","mapnestedfield1value");
  try {
    SimpleObjPrime result=mapper.map(src,SimpleObjPrime.class);
  }
 catch (  MappingException ex) {
  }
  SimpleObjPrime result=mapper.map(src,SimpleObjPrime.class);
  assertEquals(src.get("field1"),result.getField1());
}
 

Example 58

From project echo2, under directory /src/app/java/nextapp/echo2/app/event/.

Source file: EventListenerList.java

  15 
vote

/** 
 * @see java.io.Serializable
 */
private void writeObject(ObjectOutputStream out) throws IOException {
  out.defaultWriteObject();
  for (int index=0; index < size; ++index) {
    String listenerClassName=((Class)listeners[index * 2]).getName();
    EventListener listener=(EventListener)listeners[index * 2 + 1];
    if (listener instanceof Serializable) {
      out.writeObject(listenerClassName);
      out.writeObject(listener);
    }
  }
  out.writeObject(null);
}
 

Example 59

From project echo3, under directory /src/server-java/app/nextapp/echo/app/event/.

Source file: EventListenerList.java

  15 
vote

/** 
 * @see java.io.Serializable
 */
private void writeObject(ObjectOutputStream out) throws IOException {
  out.defaultWriteObject();
  for (int index=0; index < size; ++index) {
    String listenerClassName=((Class)listeners[index * 2]).getName();
    EventListener listener=(EventListener)listeners[index * 2 + 1];
    if (listener instanceof Serializable) {
      out.writeObject(listenerClassName);
      out.writeObject(listener);
    }
  }
  out.writeObject(null);
}
 

Example 60

From project eclipse-integration-gradle, under directory /org.springsource.ide.eclipse.gradle.core/src/org/springsource/ide/eclipse/gradle/core/classpathcontainer/.

Source file: GradleClassPathContainer.java

  15 
vote

private IClasspathEntry[] decode(Serializable serializable){
  JavaProject jp=(JavaProject)project.getJavaProject();
  if (serializable != null) {
    String[] encoded=(String[])serializable;
    IClasspathEntry[] decoded=new IClasspathEntry[encoded.length];
    for (int i=0; i < decoded.length; i++) {
      decoded[i]=jp.decodeClasspathEntry(encoded[i]);
    }
    return decoded;
  }
  return null;
}