@Test public void when_A_Valid_Pair_Is_Supplied_And_Retrieve_Then_Get_It() { persistence.save(KEY, VALUE); String result = persistence.retrieve(KEY, String.class); assertThat(result, is(VALUE)); }
public static void main(String[] args) { // this program needs a persistence framework // at runtime an implementor is chosen between file system // implementation and // database implememtor , depending on existence of databse drivers PersistenceImplementor implementor = null; if (databaseDriverExists()) { implementor = new DabatasePersistenceImplementor(); } else { implementor = new FileSystemPersistenceImplementor(); } Persistence persistenceAPI = new PersistenceImp(implementor); Object o = persistenceAPI.findById("12343755"); // do changes to the object // then persist persistenceAPI.persist(o); // can also change implementor persistenceAPI = new PersistenceImp(new DabatasePersistenceImplementor()); persistenceAPI.deleteById("2323"); }
public void testScanReverseKeysOnly() { persistence.mutate("A1", Functions.constant("A1".getBytes())); persistence.mutate("A2", Functions.constant("A2".getBytes())); persistence.mutate("A3", Functions.constant("A3".getBytes())); assertEquals(Lists.newArrayList("A3", "A2", "A1"), persistence.keyScanReverse("A", "B", 10)); assertEquals(Lists.newArrayList("A3", "A2"), persistence.keyScanReverse("A", "B", 2)); assertEquals(Lists.newArrayList("A2", "A1"), persistence.keyScanReverse("A", "A3", 5)); }
public void testDefensiveCopy() { byte[] input = "B".getBytes(); persistence.mutate("A", Functions.constant(input)); input[0]++; if (supportsDefensiveCopy) { assertTrue(Arrays.equals(persistence.get("A"), "B".getBytes())); } else { assertTrue(Arrays.equals(persistence.get("A"), input)); } }
public void testFunctionInput() { persistence.mutate("A", Functions.constant("B".getBytes())); persistence.mutate( "A", new Function<byte[], byte[]>() { @Override public byte[] apply(byte[] fromPersistence) { assertTrue(Arrays.equals(fromPersistence, "B".getBytes())); return "C".getBytes(); } }); assertTrue(Arrays.equals(persistence.get("A"), "C".getBytes())); }
@Override public void doFilter( final ServletRequest arg0, final ServletResponse arg1, final FilterChain chain) throws IOException, ServletException { try { chain.doFilter(arg0, arg1); } finally { Persistence.close(); } }
@Before public void init() { emf = Persistence.createEntityManagerFactory("core-sample"); CriteriaBuilderConfiguration config = Criteria.getDefault(); cbf = config.createCriteriaBuilderFactory(emf); EntityViewConfiguration entityViewConfiguration = EntityViews.createDefaultConfiguration(); for (Class<?> entityViewClazz : getEntityViewClasses()) { entityViewConfiguration.addEntityView(entityViewClazz); } evm = entityViewConfiguration.createEntityViewManager(cbf, emf); transactional(em -> { Person p1 = new Person("P1"); Person p2 = new Person("P2"); Person p3 = new Person("P3"); em.persist(p1); em.persist(p2); em.persist(p3); Cat c1 = new Cat("C1", 1, p2); Cat c2 = new Cat("C2", 2, p2); Cat c3 = new Cat("C3", 4, p2); Cat c4 = new Cat("C4", 6, p3); Cat c5 = new Cat("C5", 8, null); Cat c6 = new Cat("C6", 7, null); em.persist(c1); em.persist(c2); em.persist(c3); em.persist(c4); em.persist(c5); em.persist(c6); c1.setMother(c3); c3.getKittens().add(c1); c1.setFather(c5); c5.getKittens().add(c1); c2.setMother(c3); c3.getKittens().add(c2); c2.setFather(c6); c6.getKittens().add(c2); c4.setFather(c6); c6.getKittens().add(c4); }); }
private static InputStream storeInputStreamToFile( String filePath, Business.InputAtom inputAtom, boolean closeInput) { try { return Persistence.storeInputStream( new FileOutputStream(filePath), inputAtom.inputStream, closeInput, " corresponding to the file '" + filePath + "'"); } catch (FileNotFoundException exception) { if (log.isWarnEnabled()) { log.warn("Could not access to the file '" + filePath + "' for writing", exception); } return null; } }
@SuppressWarnings("unchecked") public <T> T main(String[] args) throws Exception { InputStream input = new FileInputStream(new File("myfile")); // HTMObjectInput reader = Persistence.get().serializer().getObjectInput(input); try (HTMObjectInput reader = Persistence.get().serializer().getObjectInput(input)) { Class<?> aClass = null; // ... // Persistable subclass T t = (T) reader.readObject( aClass); // Where T is the Persistable subclass type (HTM.java object). return t; } catch (Exception e) { throw e; } }
/** * Create a <code>Genotype</code> from XML. * * @param generationNode XML * @param config * @param db persistence repository from which to read chromosomes * @return new genotype * @throws Exception */ private static Genotype genotypeFromXml(Node generationNode, Configuration config, Persistence db) throws Exception { if (Generation.GENERATION_TAG.equals(generationNode.getNodeName()) == false) throw new IllegalArgumentException("node name not " + Generation.GENERATION_TAG); // loop through list to find chromosomes ArrayList chroms = new ArrayList(); for (int generationChildIdx = 0; generationChildIdx < generationNode.getChildNodes().getLength(); ++generationChildIdx) { Node specieNode = generationNode.getChildNodes().item(generationChildIdx); if (Specie.SPECIE_TAG.equals(specieNode.getNodeName())) { // for each specie ... NamedNodeMap specieAttrs = specieNode.getAttributes(); if (specieAttrs == null) throw new IllegalArgumentException("missing specie attributes"); // ... and loop through chromosomes for (int specieChildIdx = 0; specieChildIdx < specieNode.getChildNodes().getLength(); ++specieChildIdx) { Node chromNode = specieNode.getChildNodes().item(specieChildIdx); if (Specie.CHROMOSOME_TAG.equals(chromNode.getNodeName())) { NamedNodeMap chromAttrs = chromNode.getAttributes(); if (chromAttrs == null) throw new IllegalArgumentException("missing chromosome attributes"); Node chromIdNode = chromAttrs.getNamedItem(Specie.ID_TAG); if (chromIdNode == null) throw new IllegalArgumentException("missing chromosome id"); // get id and load chromosome from persistence (skip if representative since its // already been added Long chromId = Long.valueOf(chromIdNode.getNodeValue()); Chromosome c = db.loadChromosome(chromId.toString(), config); if (c != null) chroms.add(c); else logger.warn("chromosome in run not found: " + chromId); } } } } // don't return empty genotype if (chroms.size() <= 0) return null; // sort in order of id so that they will be added in proper order (age) Collections.sort(chroms); return new Genotype(config, chroms); }
public String migrateFromMultipleAccounts(Context paramContext, List<String> paramList) { String str = null; int i = -1; Iterator localIterator = paramList.iterator(); paramList = str; while (localIterator.hasNext()) { str = (String) localIterator.next(); str = Persistence.access$200(this$0, paramContext, str, "auto-advance", null); if (str != null) { int j = autoAdvanceSettingPriority(str); if (j > i) { i = j; paramList = str; } } } return paramList; }
public void testScan() { persistence.mutate("A1", Functions.constant("A1".getBytes())); persistence.mutate("A2", Functions.constant("A2".getBytes())); persistence.mutate("A3", Functions.constant("A3".getBytes())); persistence.mutate("A2", Functions.constant((byte[]) null)); List<Entry<String, byte[]>> scanResult = persistence.scan("A", "B", 10); assertEquals(2, scanResult.size()); assertEquals("A1", scanResult.get(0).getKey()); assertEquals("A3", scanResult.get(1).getKey()); assertTrue(Arrays.equals("A1".getBytes(), scanResult.get(0).getValue())); assertTrue(Arrays.equals("A3".getBytes(), scanResult.get(1).getValue())); scanResult = persistence.scan("A1", "A3", 10); assertEquals(1, scanResult.size()); assertEquals("A1", scanResult.get(0).getKey()); scanResult = persistence.scan("A1", "A4", 1); assertEquals(1, scanResult.size()); assertEquals("A1", scanResult.get(0).getKey()); scanResult = persistence.scan("B", "Z", 10); assertEquals(0, scanResult.size()); scanResult = persistence.scan("A1", "A4", 0); assertEquals(0, scanResult.size()); }
/** * 解析符合fastDB的 Annotation 注解对象 注:该方法是升级版,支持继承注解属性获取;采用的是 getMethods 获取继承的所有公共方法,然后解析 getter * 方法获得字段属性(这就要求getter方法和字段属性必须是严格的生成关系)。 * * @param obj 注解对象 * @param isPersistenced 对象是否已经被持久化了, false -- 用在 insert 时; true -- 用在 update 时 * @return Persistence对象 */ public static Persistence parsePersistence(Object obj, boolean isPersistenced) { Class<?> clz = obj.getClass(); // 只有通过 getMethods 方法才能获取到继承自父类的私有字段属性 Method[] methods = clz.getMethods(); // 字段是否存在,用来递归解析注解字段 boolean isFieldExist = true; // 用于内部强制异常时,中断catch;此处用在下面的 sequence 判断 boolean isBreak = false; // 主键字段 // PrimaryField p_field = null; // 普通字段 ColumnField n_field = null; String col_name = null; Object col_val = null; Persistence persistence = new Persistence(); persistence.setTableName(getTableName(clz)); for (Method m : methods) { /* 每次字段查找都要从当前类开始,然后再递归父类。 因为 getMethods()返回的数组中的元素没有排序,也没有任何特定的顺序,有可能当前类的某(些)字段被放置到了父类属性的后面, 而后面的递归父类操作改变了 clz 的对象,这样一来会造成这些字段被丢弃; 所以每次查找开始都要将 clz 对象重置为当前对象。 */ clz = obj.getClass(); String m_name = m.getName(); // 只解析getter方法,对于Boolean类型,其getter方法可能是 isAbc if (!m_name.startsWith("get") && !m_name.startsWith("is")) { continue; } // getter 方法无参数 if (m.getParameterTypes().length > 0) { continue; } // Java注解只支持基本数据类型 if (!ColumnType.isPrimitiveClass(m.getReturnType())) { continue; } m_name = lowerFirst(m_name.startsWith("get") ? m_name.substring(3) : m_name.substring(2)); // 如果当前类找不到Field定义,则递归到其父类中寻找,以此进行下去 Field f; Column col; do { try { // 这里会产生后面的异常:如果字段是父类中继承过来的,则在当前类getDeclaredField会产生异常 f = clz.getDeclaredField(m_name); col = f.getAnnotation(Column.class); // 如果该字段定义了注解,则解析;如果没有定义注解,则也不会到父类中查找 if (null != col) { col_name = col.name(); col_val = m.invoke(obj, new Object[] {}); // 列名 @Column(name='') 为空,则使用属性名替代 if (null == col_name || col_name.trim().length() == 0) { col_name = f.getName(); } // 如果是主键 if (col.primaryKey()) { // 如果对象未被持久化 并且是 SEQUENCE 生成方式 if (!isPersistenced && col.generatorType() == GeneratorType.SEQUENCE) { // 对于SEQUENCE 生成方式的主键,必须指定 SEQUENCE 名称 if (null == col.sequence() || col.sequence().trim().length() == 0) { isBreak = true; throw new IllegalArgumentException( "The " + clz.getName() + "[" + f.getName() + "] Annotation @Column(isPrimaryKey=true, generatorType=GeneratorType.SEQUENCE, sequence='...'), but the sequence name is empty!"); } // sequence 方式主键的值是 seqname.NEXTVAL col_val = col.sequence() + ".NEXTVAL"; } // 创建主键字段 // 扩充了ColumnField,使用 ColumnField替代 /*p_field = new PrimaryField(); p_field.setName( col_name ); p_field.setValue( col_val ); p_field.setGeneratorType( col.generatorType() ); p_field.setType(f.getType()); persistence.addPrimaryField( p_field );*/ } // 创建字段 n_field = new ColumnField(); n_field.setName(col_name); n_field.setValue(col_val); n_field.setType(f.getType()); n_field.setPrimaryKey(col.primaryKey()); n_field.setGeneratorType(col.generatorType()); persistence.addColumnField(n_field); } isFieldExist = true; } catch (Exception e) { // 内部强制抛出异常 if (isBreak) { e.printStackTrace(); return null; } isFieldExist = false; // 如果当前类没有找到,则到其父类中查找 clz = clz.getSuperclass(); // 父类不存在或是Object基类,则结束下次递归操作 if (null == clz || "java.lang.Object".equals(clz.getName())) { isFieldExist = true; } } } while (!isFieldExist); n_field = null; } return persistence; }
public String migrateFromSingleAccount(Context paramContext, String paramString) { return Persistence.access$200(this$0, paramContext, paramString, "auto-advance", null); }
public void testOverwrite() { persistence.mutate("A", Functions.constant("A".getBytes())); assertTrue( Arrays.equals("B".getBytes(), persistence.mutate("A", Functions.constant("B".getBytes())))); assertTrue(Arrays.equals(persistence.get("A"), "B".getBytes())); }
public void testGetUnknownKey() { assertNull(persistence.get("A")); }
public void testDelete() { persistence.mutate("A", Functions.constant("A".getBytes())); assertNull(persistence.mutate("A", Functions.constant((byte[]) null))); assertNull(persistence.get("A")); }
private JpaUtil() { this.factory = Persistence.createEntityManagerFactory("checkstyle"); }
@Test public void when_An_Invalid_Pair_Is_Supplied_Then_Get_False() { boolean result = persistence.save(null, null); assertThat(result, is(not(true))); }
public void testBasicSetAndGet() { persistence.mutate("A", Functions.constant("A".getBytes())); assertTrue(Arrays.equals(persistence.get("A"), "A".getBytes())); }
/** * 根据未持久化的注解对象创建 Insert SQL 语句 * * @param bean 注解对象 * @return object[0] -- 带占位符 ? 的 Insert SQL; <br> * object[1] -- 占位符对应的参数值 */ public static Object[] createInsertSQL(Object bean) { if (bean == null) { return null; } // 采用新的解析方式,用于支持注解继承 Persistence p = parsePersistence(bean, false); if (null == p || null == p.getTableName()) { return null; } Object[] oo = new Object[2]; StringBuilder sql_buf_1 = new StringBuilder(); StringBuilder sql_buf_2 = new StringBuilder(); sql_buf_1.append("INSERT INTO "); sql_buf_1.append(p.getTableName()); sql_buf_1.append("("); sql_buf_2.append(" VALUES("); List<Object> valList = new LinkedList<Object>(); List<ColumnField> col_fields = p.getColumnFields(); // 主键列 for (ColumnField pf : col_fields) { if (!pf.isPrimaryKey()) { continue; } if (pf.getGeneratorType() == GeneratorType.SEQUENCE) { sql_buf_1.append(pf.getName()); sql_buf_1.append(", "); sql_buf_2.append(pf.getValue()); sql_buf_2.append(", "); } else if (pf.getGeneratorType() == GeneratorType.ASSIGN) { sql_buf_1.append(pf.getName()); sql_buf_1.append(", "); sql_buf_2.append("?, "); valList.add(pf.getValue()); } } // 普通列 for (ColumnField cf : col_fields) { if (cf.isPrimaryKey()) { continue; } sql_buf_1.append(cf.getName()); sql_buf_1.append(", "); sql_buf_2.append("?, "); valList.add(cf.getValue()); } String sql1 = sql_buf_1.toString(); String sql2 = sql_buf_2.toString(); if (sql1.lastIndexOf(",") != -1) { sql1 = sql1.substring(0, sql1.lastIndexOf(",")) + ")"; } if (sql2.lastIndexOf(",") != -1) { sql2 = sql2.substring(0, sql2.lastIndexOf(",")) + ")"; } oo[0] = sql1 + sql2; oo[1] = valList.toArray(); sql_buf_1 = null; sql_buf_2 = null; valList.clear(); valList = null; p.clear(); p = null; return oo; }
/** * 根据已经持久化的注解对象创建 Update SQL 语句 * * @param bean 已经持久化的注解对象 * @param updateFields 给定待更新的字段集合,如果为null,则更新全部 * @return object[0] -- 带占位符 ? 的Update SQL;<br> * object[1] -- 占位符对应的参数值 */ public static Object[] createUpdateSQL(Object bean, String[] updateFields) { if (null == bean) { return null; } // 采用新的解析方式,用于支持注解继承 Persistence p = parsePersistence(bean, true); Map<String, String> mapping = getFieldAnnotationMapping(bean.getClass()); if (null == p || null == p.getTableName()) { return null; } Object[] oo = new Object[2]; StringBuilder sql_buf_1 = new StringBuilder(); StringBuilder sql_buf_2 = new StringBuilder(); sql_buf_1.append("UPDATE "); sql_buf_1.append(p.getTableName()); sql_buf_1.append(" SET "); sql_buf_2.append(" WHERE "); List<Object> valList = new LinkedList<Object>(); List<ColumnField> col_fields = p.getColumnFields(); // 普通列 for (ColumnField cf : col_fields) { /*if( cf.isPrimaryKey() ) { continue; }*/ // 判断Bean的属性,而不是@Column对应的数据表列名 if (withinUpdateFields(mapping.get(cf.getName()), updateFields)) { sql_buf_1.append(cf.getName()); sql_buf_1.append(" = ?, "); valList.add(cf.getValue()); } } // 主键列 for (ColumnField pf : col_fields) { if (!pf.isPrimaryKey()) { continue; } sql_buf_2.append(pf.getName()); sql_buf_2.append(" = ? AND "); valList.add(pf.getValue()); } String sql1 = sql_buf_1.toString(); String sql2 = sql_buf_2.toString(); if (sql1.lastIndexOf(",") != -1) { sql1 = sql1.substring(0, sql1.lastIndexOf(",")); } if (sql2.lastIndexOf("AND") != -1) { sql2 = sql2.substring(0, sql2.lastIndexOf("AND")); } oo[0] = sql1 + sql2; oo[1] = valList.toArray(); sql_buf_1 = null; sql_buf_2 = null; valList.clear(); valList = null; p.clear(); p = null; return oo; }
/** Instantiates a new INSTANCE of Channel */ protected Channel() { this.persistence = Persistence.getInstance(); }
@Test public void when_A_Valid_Pair_Is_Supplied_Then_Get_True() { boolean result = persistence.save(KEY, VALUE); assertThat(result, is(true)); }