/** @since 3.1 */ @Override public <T extends Persistent> T localObject(T objectFromAnotherContext) { if (objectFromAnotherContext == null) { throw new NullPointerException("Null object argument"); } ObjectId id = objectFromAnotherContext.getObjectId(); // first look for the ID in the local GraphManager synchronized (getGraphManager()) { T localObject = (T) getGraphManager().getNode(id); if (localObject != null) { return localObject; } // create a hollow object, optimistically assuming that the ID we // got from // 'objectFromAnotherContext' is a valid ID either in the parent // context or in // the DB. This essentially defers possible FaultFailureExceptions. ClassDescriptor descriptor = getEntityResolver().getClassDescriptor(id.getEntityName()); Persistent persistent = (Persistent) descriptor.createObject(); persistent.setObjectContext(this); persistent.setObjectId(id); persistent.setPersistenceState(PersistenceState.HOLLOW); getGraphManager().registerNode(id, persistent); return (T) persistent; } }
/** * ATTENTION: This function is duplicated in the Web Of Trust plugin, please backport any changes. */ private void databaseIntegrityTest() { Logger.normal(this, "Testing database integrity..."); synchronized (mIdentityManager) { synchronized (mMessageManager) { synchronized (mTaskManager) { final Query q = db.query(); q.constrain(Persistent.class); for (final Persistent p : new Persistent.InitializingObjectSet<Persistent>(this, q)) { try { p.databaseIntegrityTest(); } catch (Exception e) { try { Logger.error(this, "Integrity test failed for " + p, e); } catch (Exception toStringException) { Logger.error( this, "Integrity test failed for object and toString also failed, toString-Exception below", toStringException); Logger.error(this, "Original integrity test failure below", e); } } } } } } Logger.normal(this, "Database integrity test finished."); }
public static void SetFieldValue(Persistent obj, Field field, NodeReference node) { String fieldName = field.getName(); try { if (Persistent.class.isInstance(field.get(obj))) { Persistent fieldAsPersistentObject = (Persistent) field.get(obj); if (fieldAsPersistentObject != null) { fieldAsPersistentObject.Save(); node.set(fieldAsPersistentObject.Id, obj.Id, fieldName); return; } } Long Id = obj.Id; Object fieldValue = field.get(obj); if (fieldValue instanceof java.lang.String) { node.set(fieldValue.toString(), Id, fieldName); } else if (fieldValue instanceof java.lang.Long) { long longValue = field.getLong(obj); node.set(longValue, Id, fieldName); } else if (fieldValue instanceof java.util.Date) { Date dateValue = (Date) fieldValue; node.set(DateHelper.DateToString(dateValue), obj.Id, fieldName); } } catch (Exception e) { e.printStackTrace(); } }
/** Get the singleton instance. */ public static synchronized CacheValidator getInstance() { if (instance == null) { instance = new CacheValidator(); Persistent.addShutdownHook(instance); } return (instance); }
public void process(PhotoImage img, Collection<String> errs) throws Exception { ImageServer is = Persistent.getImageServer(); is.getThumbnail(img); for (PhotoDimensions dim : sizes) { is.getImage(img, dim); } }
public void process(PhotoImage img, Collection<String> errs) throws Exception { byte[] pi = Persistent.getImageServer().getImage(img, null); PhotoParser.Result res = PhotoParser.getInstance().parseImage(pi); String storedMd5 = img.getMd5(); assert storedMd5 != null : "No MD5 for image " + img.getId(); if (!storedMd5.equals(res.getMd5())) { errs.add("MD5 is incorrect for img " + img.getId()); } }
/** * Saves a snapshot of an image to the users directory * * @param image the image to be saved * @param user the user to save the image to */ public static void SaveProfilePicture(Image image, User user) { String userDir = new File(Persistent.getProfileFilePath(user.getUserId())).getParent(); File file = new File(userDir + "/profile.png"); try { ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file); } catch (IOException e) { // file path doesn't exist // System.out.println("Couldn't save picture. filePath not found"); } }
/** * Saves the user profile to a JSON file * * @param user user to be saved */ public static void SaveUser(User user) { String profileString = gson.toJson(user); try { FileWriter writer = new FileWriter(Persistent.getProfileFilePath(user.getUserId())); writer.write(profileString); writer.close(); } catch (IOException e) { // file path doesn't exists // The file path has been set using a file chooser so we will never reach this // e.printStackTrace(); } }
/** * If ObjEntity qualifier is set, asks it to inject initial value to an object. Also performs all * Persistent initialization operations */ protected void injectInitialValue(Object obj) { // must follow this exact order of property initialization per CAY-653, // i.e. have // the id and the context in place BEFORE setPersistence is called Persistent object = (Persistent) obj; object.setObjectContext(this); object.setPersistenceState(PersistenceState.NEW); GraphManager graphManager = getGraphManager(); synchronized (graphManager) { graphManager.registerNode(object.getObjectId(), object); graphManager.nodeCreated(object.getObjectId()); } ObjEntity entity; try { entity = getEntityResolver().getObjEntity(object.getClass()); } catch (CayenneRuntimeException ex) { // ObjEntity cannot be fetched, ignored entity = null; } if (entity != null) { if (entity.getDeclaredQualifier() instanceof ValueInjector) { ((ValueInjector) entity.getDeclaredQualifier()).injectValue(object); } } // invoke callbacks getEntityResolver().getCallbackRegistry().performCallbacks(LifecycleEvent.POST_ADD, object); }
public void process(PhotoImage img, Collection<String> errs) throws Exception { ImageServer is = Persistent.getImageServer(); if (is instanceof ImageServerImpl) { ImageServerImpl isi = (ImageServerImpl) is; byte[] fromDB = isi.getImage(img, null, false); byte[] fromCache = isi.getImage(img, null, true); if (!Arrays.equals(fromDB, fromCache)) { errs.add("Didn't get the same result from cache and DB for " + img.getId()); } } else { errs.add("Can't validate " + img.getId() + " because server is not ImageServerImpl"); } }
/** * ATTENTION: This function is duplicated in the Web Of Trust plugin, please backport any changes. */ private void closeDatabase() { if (db == null) { Logger.warning(this, "Terminated already."); return; } synchronized (Persistent.transactionLock(db)) { try { System.gc(); db.rollback(); System.gc(); db.close(); db = null; } catch (RuntimeException e) { Logger.error(this, "Error while closing database", e); } } }
// 循环处理每个需要处理的程序对象 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { // 定义一个文件输出流,用于生成额外的文件 PrintStream ps = null; try { // 遍历每个被@Persistent修饰的class文件 for (Element t : roundEnv.getElementsAnnotatedWith(Persistent.class)) { // 获取正在处理的类名 Name clazzName = t.getSimpleName(); // 获取类定义前的@Persistent Annotation Persistent per = t.getAnnotation(Persistent.class); // 创建文件输出流 ps = new PrintStream(new FileOutputStream(clazzName + ".hbm.xml")); // 执行输出 ps.println("<?xml version=\"1.0\"?>"); ps.println("<!DOCTYPE hibernate-mapping PUBLIC"); ps.println(" \"-//Hibernate/Hibernate " + "Mapping DTD 3.0//EN\""); ps.println(" \"http://www.hibernate.org/dtd/" + "hibernate-mapping-3.0.dtd\">"); ps.println("<hibernate-mapping>"); ps.print(" <class name=\"" + t); // 输出per的table()的值 ps.println("\" table=\"" + per.table() + "\">"); for (Element f : t.getEnclosedElements()) { // 只处理成员变量上的Annotation if (f.getKind() == ElementKind.FIELD) // ① { // 获取成员变量定义前的@Id Annotation Id id = f.getAnnotation(Id.class); // ② // 当@Id Annotation存在时输出<id.../>元素 if (id != null) { ps.println( " <id name=\"" + f.getSimpleName() + "\" column=\"" + id.column() + "\" type=\"" + id.type() + "\">"); ps.println(" <generator class=\"" + id.generator() + "\"/>"); ps.println(" </id>"); } // 获取成员变量定义前的@Property Annotation Property p = f.getAnnotation(Property.class); // ③ // 当@Property Annotation存在时输出<property.../>元素 if (p != null) { ps.println( " <property name=\"" + f.getSimpleName() + "\" column=\"" + p.column() + "\" type=\"" + p.type() + "\"/>"); } } } ps.println(" </class>"); ps.println("</hibernate-mapping>"); } } catch (Exception ex) { ex.printStackTrace(); } finally { if (ps != null) { try { ps.close(); } catch (Exception ex) { ex.printStackTrace(); } } } return true; }
@Override public void prepareForAccess(Persistent object, String property, boolean lazyFaulting) { if (object.getPersistenceState() == PersistenceState.HOLLOW) { ObjectId oid = object.getObjectId(); List<?> objects = performQuery(new ObjectIdQuery(oid, false, ObjectIdQuery.CACHE)); if (objects.size() == 0) { throw new FaultFailureException( "Error resolving fault, no matching row exists in the database for ObjectId: " + oid); } else if (objects.size() > 1) { throw new FaultFailureException( "Error resolving fault, more than one row exists in the database for ObjectId: " + oid); } // 5/28/2013 - Commented out this block to allow for modifying // objects in the postLoad callback // sanity check... // if (object.getPersistenceState() != PersistenceState.COMMITTED) { // // String state = // PersistenceState.persistenceStateName(object.getPersistenceState()); // // // TODO: andrus 4/13/2006, modified and deleted states are // // possible due to // // a race condition, should we handle them here? // throw new // FaultFailureException("Error resolving fault for ObjectId: " + // oid + " and state (" + state // + // "). Possible cause - matching row is missing from the database."); // } } // resolve relationship fault if (lazyFaulting && property != null) { ClassDescriptor classDescriptor = getEntityResolver().getClassDescriptor(object.getObjectId().getEntityName()); PropertyDescriptor propertyDescriptor = classDescriptor.getProperty(property); // If we don't have a property descriptor, there's not much we can // do. // Let the caller know that the specified property could not be // found and list // all of the properties that could be so the caller knows what can // be used. if (propertyDescriptor == null) { final StringBuilder errorMessage = new StringBuilder(); errorMessage.append( String.format( "Property '%s' is not declared for entity '%s'.", property, object.getObjectId().getEntityName())); errorMessage.append(" Declared properties are: "); // Grab each of the declared properties. final List<String> properties = new ArrayList<String>(); classDescriptor.visitProperties( new PropertyVisitor() { @Override public boolean visitAttribute(final AttributeProperty property) { properties.add(property.getName()); return true; } @Override public boolean visitToOne(final ToOneProperty property) { properties.add(property.getName()); return true; } @Override public boolean visitToMany(final ToManyProperty property) { properties.add(property.getName()); return true; } }); // Now add the declared property names to the error message. boolean first = true; for (String declaredProperty : properties) { if (first) { errorMessage.append(String.format("'%s'", declaredProperty)); first = false; } else { errorMessage.append(String.format(", '%s'", declaredProperty)); } } errorMessage.append("."); throw new CayenneRuntimeException(errorMessage.toString()); } // this should trigger fault resolving propertyDescriptor.readProperty(object); } }
/** * Creates an identity from an identity introduction, stores it in the database and returns the * new identity. If the identity already exists, the existing identity is returned. * * <p>You have to synchronize on the WebOfTrust object when using this function! TODO: Remove this * requirement and re-query the parameter OwnIdentity puzzleOwner from the database after we are * synchronized. * * @param xmlInputStream An InputStream which must not return more than {@link * MAX_INTRODUCTION_BYTE_SIZE} bytes. * @throws InvalidParameterException If the XML format is unknown or if the puzzle owner does not * allow introduction anymore. * @throws IOException * @throws SAXException */ public Identity importIntroduction(OwnIdentity puzzleOwner, InputStream xmlInputStream) throws InvalidParameterException, SAXException, IOException { xmlInputStream = new OneBytePerReadInputStream( xmlInputStream); // Workaround for Java bug, see the stream class for explanation // May not be accurate by definition of available(). So the JavaDoc requires the callers to obey // the size limit, this is a double-check. if (xmlInputStream.available() > MAX_INTRODUCTION_BYTE_SIZE) throw new IllegalArgumentException( "XML contains too many bytes: " + xmlInputStream.available()); FreenetURI identityURI; Identity newIdentity; Document xmlDoc; synchronized ( mDocumentBuilder) { // TODO: Figure out whether the DocumentBuilder is maybe synchronized // anyway xmlDoc = mDocumentBuilder.parse(xmlInputStream); } Element introductionElement = (Element) xmlDoc.getElementsByTagName("IdentityIntroduction").item(0); if (Integer.parseInt(introductionElement.getAttribute("Version")) > XML_FORMAT_VERSION) throw new InvalidParameterException( "Version " + introductionElement.getAttribute("Version") + " > " + XML_FORMAT_VERSION); Element identityElement = (Element) introductionElement.getElementsByTagName("Identity").item(0); identityURI = new FreenetURI(identityElement.getAttribute("URI")); final IdentityFetcher identityFetcher = mWoT.getIdentityFetcher(); synchronized (mWoT) { synchronized (identityFetcher) { if (!puzzleOwner.hasContext(IntroductionPuzzle.INTRODUCTION_CONTEXT)) throw new InvalidParameterException( "Trying to import an identity identroduction for an own identity which does not allow introduction."); synchronized (Persistent.transactionLock(mDB)) { try { try { newIdentity = mWoT.getIdentityByURI(identityURI); if (logMINOR) Logger.minor( this, "Imported introduction for an already existing identity: " + newIdentity); } catch (UnknownIdentityException e) { newIdentity = new Identity(mWoT, identityURI, null, false); // We do NOT call setEdition(): An attacker might solve puzzles pretending to be // someone else and publish bogus edition numbers for // that identity by that. The identity constructor only takes the edition number as // edition hint, this is the proper behavior. // TODO: As soon as we have code for signing XML with an identity SSK we could sign // the introduction XML and therefore prevent that // attack. // newIdentity.setEdition(identityURI.getEdition()); newIdentity.storeWithoutCommit(); if (logMINOR) Logger.minor(this, "Imported introduction for an unknown identity: " + newIdentity); } try { mWoT.getTrust(puzzleOwner, newIdentity); /* Double check ... */ if (logMINOR) Logger.minor(this, "The identity is already trusted."); } catch (NotTrustedException ex) { // 0 trust will not allow the import of other new identities for the new identity // because the trust list import code will only create // new identities if the score of an identity is > 0, not if it is equal to 0. mWoT.setTrustWithoutCommit( puzzleOwner, newIdentity, (byte) 0, "Trust received by solving a captcha."); } // setTrustWithoutCommit() does this for us. // identityFetcher.storeStartFetchCommandWithoutCommit(newIdentity.getID()); newIdentity.checkedCommit(this); } catch (RuntimeException error) { Persistent.checkedRollbackAndThrow(mDB, this, error); // Satisfy the compiler - without this the return at the end of the function would // complain about the uninitialized newIdentity variable throw error; } } } } return newIdentity; }
/** * Imports a identity XML file into the given web of trust. This includes: - The identity itself * and its attributes - The trust list of the identity, if it has published one in the XML. * * @param xmlInputStream The input stream containing the XML. */ public void importIdentity(FreenetURI identityURI, InputStream xmlInputStream) { try { // Catch import problems so we can mark the edition as parsing failed // We first parse the XML without synchronization, then do the synchronized import into the // WebOfTrust final ParsedIdentityXML xmlData = parseIdentityXML(xmlInputStream); synchronized (mWoT) { synchronized (mWoT.getIdentityFetcher()) { final Identity identity = mWoT.getIdentityByURI(identityURI); Logger.normal(this, "Importing parsed XML for " + identity); long newEdition = identityURI.getEdition(); if (identity.getEdition() > newEdition) { if (logDEBUG) Logger.debug( this, "Fetched an older edition: current == " + identity.getEdition() + "; fetched == " + identityURI.getEdition()); return; } else if (identity.getEdition() == newEdition) { if (identity.getCurrentEditionFetchState() == FetchState.Fetched) { if (logDEBUG) Logger.debug( this, "Fetched current edition which is marked as fetched already, not importing: " + identityURI); return; } else if (identity.getCurrentEditionFetchState() == FetchState.ParsingFailed) { Logger.normal( this, "Re-fetched current-edition which was marked as parsing failed: " + identityURI); } } // We throw parse errors AFTER checking the edition number: If this XML was outdated // anyway, we don't have to throw. if (xmlData.parseError != null) throw xmlData.parseError; synchronized (Persistent.transactionLock(mDB)) { try { // Transaction rollback block identity.setEdition( newEdition); // The identity constructor only takes the edition number as a hint, // so we must store it explicitly. boolean didPublishTrustListPreviously = identity.doesPublishTrustList(); identity.setPublishTrustList(xmlData.identityPublishesTrustList); try { identity.setNickname(xmlData.identityName); } catch (Exception e) { /* Nickname changes are not allowed, ignore them... */ Logger.warning(this, "setNickname() failed.", e); } try { /* Failure of context importing should not make an identity disappear, therefore we catch exceptions. */ identity.setContexts(xmlData.identityContexts); } catch (Exception e) { Logger.warning(this, "setContexts() failed.", e); } try { /* Failure of property importing should not make an identity disappear, therefore we catch exceptions. */ identity.setProperties(xmlData.identityProperties); } catch (Exception e) { Logger.warning(this, "setProperties() failed", e); } mWoT .beginTrustListImport(); // We delete the old list if !identityPublishesTrustList // and it did publish one earlier => we always call this. if (xmlData.identityPublishesTrustList) { // We import the trust list of an identity if it's score is equal to 0, but we only // create new identities or import edition hints // if the score is greater than 0. Solving a captcha therefore only allows you to // create one single identity. boolean positiveScore = false; boolean hasCapacity = false; // TODO: getBestScore/getBestCapacity should always yield a positive result because // we store a positive score object for an OwnIdentity // upon creation. The only case where it could not exist might be // restoreOwnIdentity() ... check that. If it is created there as well, // remove the additional check here. if (identity instanceof OwnIdentity) { // Importing of OwnIdentities is always allowed positiveScore = true; hasCapacity = true; } else { try { positiveScore = mWoT.getBestScore(identity) > 0; hasCapacity = mWoT.getBestCapacity(identity) > 0; } catch (NotInTrustTreeException e) { } } HashSet<String> identitiesWithUpdatedEditionHint = null; if (positiveScore) { identitiesWithUpdatedEditionHint = new HashSet<String>(xmlData.identityTrustList.size() * 2); } for (final ParsedIdentityXML.TrustListEntry trustListEntry : xmlData.identityTrustList) { final FreenetURI trusteeURI = trustListEntry.mTrusteeURI; final byte trustValue = trustListEntry.mTrustValue; final String trustComment = trustListEntry.mTrustComment; Identity trustee = null; try { trustee = mWoT.getIdentityByURI(trusteeURI); if (positiveScore) { if (trustee.setNewEditionHint(trusteeURI.getEdition())) { identitiesWithUpdatedEditionHint.add(trustee.getID()); trustee.storeWithoutCommit(); } } } catch (UnknownIdentityException e) { if (hasCapacity) { /* We only create trustees if the truster has capacity to rate them. */ try { trustee = new Identity(mWoT, trusteeURI, null, false); trustee.storeWithoutCommit(); } catch (MalformedURLException urlEx) { // Logging the exception does NOT log the actual malformed URL so we do it // manually. Logger.warning( this, "Received malformed identity URL: " + trusteeURI, urlEx); throw urlEx; } } } if (trustee != null) mWoT.setTrustWithoutCommit(identity, trustee, trustValue, trustComment); } for (Trust trust : mWoT.getGivenTrustsOfDifferentEdition(identity, identityURI.getEdition())) { mWoT.removeTrustWithoutCommit(trust); } IdentityFetcher identityFetcher = mWoT.getIdentityFetcher(); if (positiveScore) { for (String id : identitiesWithUpdatedEditionHint) identityFetcher.storeUpdateEditionHintCommandWithoutCommit(id); // We do not have to store fetch commands for new identities here, // setTrustWithoutCommit does it. } } else if (!xmlData.identityPublishesTrustList && didPublishTrustListPreviously && !(identity instanceof OwnIdentity)) { // If it does not publish a trust list anymore, we delete all trust values it has // given. for (Trust trust : mWoT.getGivenTrusts(identity)) mWoT.removeTrustWithoutCommit(trust); } mWoT.finishTrustListImport(); identity.onFetched(); // Marks the identity as parsed successfully identity.storeAndCommit(); } catch (Exception e) { mWoT.abortTrustListImport(e, Logger.LogLevel.WARNING); // Does the rollback throw e; } // try } // synchronized(Persistent.transactionLock(db)) Logger.normal(this, "Finished XML import for " + identity); } // synchronized(mWoT) } // synchronized(mWoT.getIdentityFetcher()) } // try catch (Exception e) { synchronized (mWoT) { synchronized (mWoT.getIdentityFetcher()) { try { final Identity identity = mWoT.getIdentityByURI(identityURI); final long newEdition = identityURI.getEdition(); if (identity.getEdition() <= newEdition) { Logger.normal(this, "Marking edition as parsing failed: " + identityURI); try { identity.setEdition(newEdition); } catch (InvalidParameterException e1) { // Would only happen if newEdition < current edition. // We have validated the opposite. throw new RuntimeException(e1); } identity.onParsingFailed(); identity.storeAndCommit(); } else { Logger.normal( this, "Not marking edition as parsing failed, we have already fetched a new one (" + identity.getEdition() + "):" + identityURI); } Logger.normal(this, "Parsing identity XML failed gracefully for " + identityURI, e); } catch (UnknownIdentityException uie) { Logger.error(this, "Fetched an unknown identity: " + identityURI); } } } } }