Java EE / Objectify get a list filtered by another using ofy() - list

My classes:
#Entity
#Cache
#Index
public class Log {
#Id Long id;
Ref<Site> site;
Ref<User> user;
Ref<Computer> computer;
Ref<License> license;
private String date_in;
private String date_out;
private boolean active;
}
#Entity
#Cache
#Index
public class License {
#Id Long id;
private String name;
private String startDate;
private String expDate;
private int timeStamp;
private int status;
private int offline;
private String identification;
Ref<Daemon> daemon;
private boolean active;
public enum Type {Country, Site, User, Computer, Lic};
}
I don't get why this is not working:
ofy().load().type(Log.class)
.filter("license in",
ofy().load().type(License.class).filter("name",licName))
.list();
or this too:
ofy().load().type(Log.class)
.filter("license in",
ofy().load().type(License.class).filter("name",licName).list())
.list();
My License is a reference in my Log. Can I do it using ofy() ?
Can anyone explain me?

Related

Mockito test when(repository.findById()).thenReturn(object with custom attributes)

So I was writing a couple of unit tests, some of them were made for testing missing attributes of Document. When using of when(repository.findOne(id)).thenReturn(DOCUMENT_WITHOUT_SOMETHING), those DOCUMENT_WITHOUT_SOMETHING were final objects with predefined attributes, depending on test cases.
Let's say, there could be a document without name, so when loading document by id the method was returning null with some log message. So I created a class of test data DocumentServiceTestData, where those necessary objects and attributes were declared. Is it a good approach or you suggest something more clear, without need of making new class?
I will try to write a simplified code of what I did.
Document
public class Document {
private String name;
private String applicant;
private String sign;
private boolean signed;
public boolean isSigned() {return signed;}
public String getApplicant() {return applicant;}
public String getName() {return name;}
public String getSign() {return sign;}
public void setSigned(boolean signed) {this.signed = signed;}
public void setApplicant(String applicant) {this.applicant = applicant;}
public void setName(String name) {this.name = name;}
public void setSign(String sign) {this.sign = sign;}
}
DocumentService
#Service
public class DocumentService {
private static final Logger LOG = LoggerFactory.getLogger(DocumentService.class);
private DocumentRepository documentRepository;
public Document loadDocument(Long docId) {
Document document = documentRepository.findByIdOrFail(docId);
if(document.getName() == null) {
LOG.info("There is no name for document, returning null");
return null;
}
if(document.getSign() == null) {
LOG.info("The document is not signed, returning null");
return null;
}
return document;
}
}
DocumentServiceTestData
public class DocumentServiceTestData {
public static final Long DOC_ID = 1L;
public static final String APPLICANT = "Applicant";
public static final String DOC_NAME = "Document";
public static final String SIGN = "Sign";
public static final Document DOCUMENT_WITHOUT_NAME;
public static final Document DOCUMENT_WITHOUT_SIGN;
static {
DOCUMENT_WITHOUT_NAME = makeDocument(null, APPLICANT, SIGN, true);
DOCUMENT_WITHOUT_SIGN = makeDocument(DOC_NAME, APPLICANT, null, false);
}
private static Document makeDocument(String name, String applicant, String sign, boolean signed) {
Document document = new Document();
document.setName(name);
document.setApplicant(applicant);
document.setSign(sign);
document.setSigned(signed);
return document;
}
}
DocumentServiceTest
#RunWith(MockitoJUnitRunner.class)
#Category(MockTest.class)
public class DocumentServiceUnitTest {
#InjectMocks
private DocumentService service;
#Mock
private DocumentRepository documentRepository;
#Test
public void testLoadDocument_notSigned(){
when(documentRepository.findByIdOrFail(DOC_ID)).thenReturn(DOCUMENT_WITHOUT_SIGN);
Document document = service.loadDocument(DOC_ID);
Assert.assertNull(document);
}
#Test
public void testLoadDocument_notNamed(){
when(documentRepository.findByIdOrFail(DOC_ID)).thenReturn(DOCUMENT_WITHOUT_NAME);
Document document = service.loadDocument(DOC_ID);
Assert.assertNull(document);
}
}
To sum up, I would like to know - if there is another way to test those cases, when I need to return specified objects while calling repository.findById(id).
PS: keep in mind that this is very simplified, those tests I've made were much more complex. If there is any information missing please let me know, I will try to clarify things. Thanks

I can't retrieve relationships

I have a Person node and a call relationship.I want to find a specific person and those who called him.My code are as below
#NodeEntity
public class Person extends BaseEntity{
#Property(name = "id")
private String mobile;
private String name;
private int partition;
private int StronglyConnectedComponents;
private int ConnectedComponent;
private int LabelPropagation;
private double pagerank;
private int seed_label; //在线算法结果写回字段
#Relationship(type="Call",direction=Relationship.OUTGOING)
private List<Person> contact;
//setter and getter
}
#RelationshipEntity(type = "Call")
public class Call extends BaseEntity{
#StartNode
private Person caller;
#EndNode
private Person callee;
private String BS;
private String time;
//setter and getter
}
#Repository
public interface PersonRepository extends GraphRepository<Person>{
Person findById(String id, #Depth int depth);
}
public String test() {
Person person = community.personRepository.findById("18565124452",2);
return person.toString();
}
Use test method I can retrieve the properties of the person node but the relationship property contact is null. How can I fix this?
Looks like an older Spring Data Neo4j version. But this shouldn't be a problem here. In your person class you are defining
#Relationship(type="Call",direction=Relationship.OUTGOING)
private List<Person> contact;
where it should be
#Relationship(type="Call",direction=Relationship.OUTGOING)
private List<Call> contact;
I had the same problem with null relationships. I think the only way to fetch relationships is by using cypher query language. Correct the mistake meistermeir point out. Try adding this method to your repository class.
#Query("MATCH (p:Person) WHERE ID(p)=18565124452 MATCH (p)-[call:Call*]->(p2) return p, call, p2")
Person getPersonById(long personId);
Also, I think you need to change :
#Property(name = "id")
to
#Id
#GeneratedValue
private Long id;
in order to generate unique id's every time you create new Person nodes.

JPA Entities generation using JAX-WS on Netbeans with customized Methods

What I need is to have some specific methods (toString()) on my entities in order to be able to use them on my WebService Client (so I don't have to re-write them every time I Refresh my Webservice from Glassfish).
I ask this because I noticed that the only methods that are generated on my Client are the getters and setters of my fields, even if I write toString() on the Server side of the Webservice.
I guess the question is there a way to force customized methods to be deployed to the Application Server, so that those entities can reply to a toString(), for instance, on the Client?
package entities;
import java.io.Serializable;
import javax.persistence.*;
#Entity
public class Auxiliarfiles implements Serializable {
#Column(unique=false,updatable=true,insertable=true,nullable=false,length=38,scale=0,precision=0)
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(unique=false,updatable=true,insertable=true,nullable=true,length=255,scale=0,precision=0)
#Basic
private String description;
#Column(unique=false,updatable=true,insertable=true,nullable=true,length=255,scale=0,precision=0)
#Basic
private String name;
public Auxiliarfiles(){}
public Long getId() {
return this.id;
}
public void setId (Long id) {
this.id = id;
}
public String getDescription() {
return this.description;
}
public void setDescription (String description) {
this.description = description;
}
public String getName() {
return this.name;
}
public void setName (String name) {
this.name = name;
}
public String toString() {
return this.getId() + " - " + this.getName();
}
}
Thanks in advance!

Play Framework 2.0 Access foreign key object from template

I have 2 Ebean models connected with ManyToOne connection.
#Entity
public class Interview extends Model {
#Id
Long id;
#ManyToOne(cascade = CascadeType.MERGE)
public User user;
....
}
And
#Entity
public class User extends Model {
#Id
public Long id;
#Email
#Required
#Column(unique=true)
public String email;
#Required
public String name;
public String department;
public String phone;
....
}
When trying to access the User class fields from Scala template through the Interview instance I only have access to the id field, but others return empty string.
Here is the template:
#(interviewsList[Interview])
....
<table>
.....
#for(i <- interviewsList) {
<tr>
<td>#i.user.name</td> // EMPTY, while changing to #i.user.id returns an id
<td>#i.date.format("dd MMM yyyy")</td>
</tr>
}
</table>
Is there any way to access other fields without using Finder?

WCF DataContract With List of RegExs Won't Serialize Properly

I have a class that looks something like this:
[DataContract]
public class InboundMailbox
{
public const char EmailSeparator = ';';
[DataMember]
public string POP3Host { get; set; }
[DataMember]
public string EmailId { get; set; }
[DataMember]
public string WebServiceURL { get; set; }
[DataMember]
public List<Regex> Allowed { get; set; }
[DataMember]
public List<Regex> Disallowed { get; set; }
}
If Allowed and Disallowed are empty then it serializes just fine across my WCF service. As soon as one of those lists contains a value, I get this in a CommunicationException:
The socket connection was aborted. This could be caused by an error
processing your message or a receive timeout being exceeded by the
remote host, or an underlying network resource issue. Local socket
timeout was '00:00:29.9899990'.
Why is it giving me a hard time about serializing those two properties? Thanks in advance.
The Regex class implements the ISerializable interface, which means that it's serialized as a property bag (dictionary of string/object). Looking at the implementation of ISerializable.GetObjectData for the Regex class in Reflector, it shows that it serializes both the pattern (string) and the options (of type RegexOptions). Since the type is ISerializable, WCF doesn't know about RegexOptions, so it will fail to serialize this type.
One simple solution is to simply "tell" WCF that this is a known type, so the serialization will work (an easy place to declare it is using the [KnownType] attribute in the InboundMailbox class (see below). Another option would be to have the data member as the regex pattern instead of the Regex itself (and possibly the options as well).
public class StackOverflow_7909261
{
[DataContract]
[KnownType(typeof(RegexOptions))]
public class InboundMailbox
{
public const char EmailSeparator = ';';
[DataMember]
public string POP3Host { get; set; }
[DataMember]
public string EmailId { get; set; }
[DataMember]
public string WebServiceURL { get; set; }
[DataMember]
public List<Regex> Allowed { get; set; }
[DataMember]
public List<Regex> Disallowed { get; set; }
}
public static void Test()
{
MemoryStream ms = new MemoryStream();
InboundMailbox obj = new InboundMailbox
{
POP3Host = "popHost",
EmailId = "email",
WebServiceURL = "http://web.service",
Allowed = new List<Regex>
{
new Regex("abcdef", RegexOptions.IgnoreCase),
},
Disallowed = null,
};
DataContractSerializer dcs = new DataContractSerializer(typeof(InboundMailbox));
try
{
dcs.WriteObject(ms, obj);
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
BTW, you'd find out the error if you had enabled tracing on the server side; it would have an exception saying that the type RegexOptions wasn't expected.