List, Array, Stack Queue? - list

I am very new to this programming stuff. I am currently taking Data Structures in Java. I have an assignment where I have to replicate a given Subway system. I am supposed to do it in 3 classes (Station, Route and Subway). Could someone please direct me in the right direction in regards to starting this project? Below are my instructions. Thank you very much.
Implement a class called Station that contains information about a particular station. This class should allow to set at least the name of the station. Each station is unique within the subway system.
Implement a class called Route that stores information about a particular route. This Route class should allow to add stations/remove stations from the route. A route has a name.
Implement a class called Subway. This Subway class should allow to add and delete Route objects.
Implement the following subway system in your application.
Now, develop a method in the Subway class that given two stations passed as parameters that belongs to a Subway object, it returns a list of stations that the user will traverse to go from one station to the other. Assume that there are no loops in the system. The method signature is as follows:
public List getRouteBetweenStations(Station a, Station b)
Here's where I am and I'm not even sure it's correct
public class **Station**
{
String station;
private final String STATION1 = "140";
private final String STATION2 = "134";
private final String STATION3 = "Unicentro";
private final String STATION4 = "100";
private final String STATION5 = "30";
private final String STATION6 = "R";
private final String STATION7 = "Marsella";
private final String STATION8 = "Mu";
private final String STATION9 = "Bosa";
private final String STATION10 = "Germania";
private final String STATION11= "19";
private final String STATION12 = "Sabana";
private final String STATION13 = "Espec";
private final String STATION14 = "F";
private final String STATION15 = "Gu";
private final String STATION16 = "Santiago";
private final String STATION17 = "SENA";
private final String STATION18 = "Timiza";
public void setStation(String stops)
{
station = stops;
}
}
import java.util.ArrayList;
import java.util.List;
public class **Route**
{
List<String> route1 = new ArrayList<>();
List<String> route2 = new ArrayList<>();
List<String> route3 = new ArrayList<>();
List<String> route4 = new ArrayList<>();
List<String> route5 = new ArrayList<>();
route1.add ("140"); (**here I am getting an error here telling me that "package route1 does not exist**)
Again, any help you can give me is greatly appreciated

The subway should contain routes and routes should contain stations. When you see contains or add and delete in programming execises this most often implies you will need a list to for the classes.
What is the reason for the string constants in your Station class?

Related

Can't read variables from application.properties

I am making a Spring application in which I'm sending data to kinesis. I have the accessKey and secretKey stored in application.properties. In the service implementation class I am using these variables but im getting an error that access key cannot be null.
The ProducerServiceImpl class:
public class ProducerServiceImpl extends ProducerService {
private static final Logger LOG = LoggerFactory.getLogger(ProducerServiceImpl.class);
#Value(value = "${aws.stream_name}")
private String streamName;
#Value(value = "${aws.region}")
private String awsRegion;
#Value(value = "${aws.access_key}")
private String awsAccessKey;
#Value(value = "${aws.secret_key}")
private String awsSecretKey;
private KinesisProducer kinesisProducer = null;
public ProducerServiceImpl() {
this.kinesisProducer = getKinesisProducer();
}
private KinesisProducer getKinesisProducer() {
if (kinesisProducer == null) {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
KinesisProducerConfiguration config = new KinesisProducerConfiguration();
config.setRegion(awsRegion);
config.setCredentialsProvider(new AWSStaticCredentialsProvider(awsCreds));
config.setMaxConnections(1);
config.setRequestTimeout(6000); // 6 seconds
config.setRecordMaxBufferedTime(5000); // 5 seconds
kinesisProducer = new KinesisProducer(config);
}
return kinesisProducer;
}
I think the reason is that because after the function, the constructor is called first, the variables are not being assigned the value from #Value.
If you're using the #Value annotation on fields, Spring will use field injection. This means that it first needs to create an instance of ProducerServiceImpl (by calling your constructor), and then it will use reflection to initialize those fields annotated with #Value.
So, since your constructor is invoked before the values are injected, they will be null.
There are two basic solutions, one is to use constructor injection:
public class ProducerServiceImpl extends ProducerService {
// ... Fields
// Pass #Value as constructor parameters
public ProducerServiceImpl(#Value(value = "${aws.access_key}") String awsAccessKey) {
// Set the fields before calling getKinesisProducer()
// If you only need the fields to create the producer, you could also just pass them as arguments to the getKinesisProducer() function
this.awsAccessKey = awsAccessKey;
this.kinesisProducer = getKinesisProducer();
}
// ...
}
The other solution is to wait until Spring has initialized the bean. This can be done by moving the logic to a method annotated with #PostConstruct:
public class ProducerServiceImpl extends ProducerService {
// ... Fields
// Replace the constructor by a method annotated with #PostConstruct
#PostConstruct
public void initializeKinesisProducer() {
this.kinesisProducer = getKinesisProducer();
}
// ...
}
However, the prefered solution is to move the entire KinesisProducer setup to a Spring configuration class, and provide it as a bean. Since all Spring beans are singletons, you can get rid of that initialization code. For example:
// Create a new #Configuration class
#Configuration
public class KinesisConfiguration {
// Create a #Bean method to construct your KinesisProducer
#Bean
// Pass all #Value's as parameters
public KinesisProducer kinesisProducer(#Value("${aws.access_key} String awsAccessKey) {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsAccessKey, awsSecretKey); KinesisProducerConfiguration config = new KinesisProducerConfiguration();
config.setRegion(awsRegion);
config.setCredentialsProvider(new AWSStaticCredentialsProvider(awsCreds));
config.setMaxConnections(1);
config.setRequestTimeout(6000); // 6 seconds
config.setRecordMaxBufferedTime(5000); // 5 seconds
return new KinesisProducer(config);
}
}
Now you can delete all that code in your service and use:
public class ProducerServiceImpl extends ProducerService {
// Inject your KinesisProducer, either through field injection or constructor injection
#Autowired
private KinesisProducer kinesisProducer;
}
I would suggest moving your #Value configuration properties to another class using #ConfigurationProperties and inject that in your constructor.

Getting Relationship properties using spring data neo4j node repository

If we have a Company Node like this which is linked to another Node (Location) using OWNS relationship.
#NodeEntity ("Company")
public class Company {
#Id
#Property
private String companyId;
#Property
private String partyId;
#Relationship (type = "OWNS", direction = Relationship . OUTGOING )
private Set<Location> ownedLocations;
}
OWNS relationship
#RelationshipEntity (type = "OWNS")
public class Owns {
#Property
private String ownsProperty;
#StartNode
private Company company;
#EndNode
private Location location;
}
Here is the Repository
#Repository
public interface CompanyRepository extends Neo4jRepository<Company, String> {
#Query ("match (c:Company)-[x:OWNS]-(y) where c.partyId = $0 return c,x,y")
Stream<Company> getCompaniesWithRelationsByPartyId(final String partyId);
}
So when i run this query i am getting only Company and Location entities but no OWNS ownsProperty. How to get relationship properties using above repository?
NOTE: I don't want to use #QueryResult
enter code here
You have to define the Owns relationship entity as the type for the relationship in the Company like this
#Relationship (type = "OWNS", direction = Relationship . OUTGOING )
private Set<Owns> ownedLocations;

Unable to make general purpose query, without Domain entity

I am new to springbootneo4j. I have difficulties making general purpose queries. I want to be able to make any kind of query and get result without domain entity.
I am making a query like this in repository class:
#Query("MATCH (p:Employee) RETURN ID(p) as id, p.name as name, p.salary as salary ")
that is not working, but the following query is working:
#Query("MATCH (p:Employee) RETURN p ")
My domain entity class is something like this:
#NodeEntity
public class Employee {
#Id
#GeneratedValue
private Long id;
private String name;
private int salary;
#Relationship(type = "IS_BOSSOF", direction = Relationship.UNDIRECTED) Set<Employee> reporties = new HashSet<>();
public Employee() {}
// some more code
}
Create a command is like this:
(laksmi:Employee{name:"Laksmi",salary:200}),(ashwini:Employee{name:"AshwiniV",salary:300}), (harish:Employee{name:"Harish",salary:400}), (jay)-[:IS_BOSSOF]->(mukesh), (xyz)-[:IS_BOSSOF]->(mukesh), (harish)-[:IS_BOSSOF]->(ashwini),
Whenever you are distributing properties you need to use #QueryResult annotation on your class
SDN

Designing Model with foreign key

I am building an ORM by using Unit or Work and Repository using Dapper. I have searched the internet on this problem and no luck.
I have the following tables:
As you can see, Instance has Entity inside. I have 2 approaches:
Approach 1:
public class Entity
{
public int Id {get;set;}
public string Name {get;set;}
}
public class Instance
{
public int Id {get;set;}
public Entity Entity {get;set;}
public string Name {get;set;}
}
How can I get value for Entity with this approach?
Approach 2 (according to this link):
public class Entity
{
public int Id {get;set;}
public string Name {get;set;}
}
public class Instance
{
public int Id {get;set;}
public int EntityId {get;set;}
public string Name {get;set;}
}
Which design is better for use?
You can use QueryMultiple if you want to fetch the data from two different tables and fill it up in two different POCO classes. Following is copied from here:
string sql = "SELECT * FROM Invoice WHERE InvoiceID = #InvoiceID; SELECT * FROM InvoiceItem WHERE InvoiceID = #InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
using (var multi = connection.QueryMultiple(sql, new {InvoiceID = 1}))
{
var invoice = multi.Read<Invoice>().First();
var invoiceItems = multi.Read<InvoiceItem>().ToList();
}
}
Both the models you mentioned in your code can be handled with this approach.
As an alternative approach, you can combine your two POCOs in one or you can use inheritance as well. But, looking at your data model, I do not think this is applicable to this particular case.
Which design is better for use?
Up to you. Whatever suits your project needs keeping down the unnecessary complexities is good for you.

Sitecore Glass data model inheritence

I am using the Glass Mapper on a Sitecore instance where I have a basic data template structure of
Base
BaseWithList
BaseWithExtraContent
BaseWithExtraContentAndCallToActionLink
I have added model classes in my project to follow this structure too. My class names match my template names.
[SitecoreType(TemplateId = "{5D19BD92-799E-4DC1-9A4E-1DDE3AD68DAD}", AutoMap = true)]
public class Base
{
public virtual string Title {get;set;}
public virtual string Content {get;set;}
}
[SitecoreType(TemplateId = "{0491E3D6-EBAA-4E21-B255-80F0607B176D}", AutoMap = true)]
public class BaseWithExtraContent : Base
{
public virtual string ExtraContent {get;set;}
}
[SitecoreType(TemplateId = "{95563412-7A08-46A3-98CB-ABC4796D57D4}", AutoMap = true)]
public class BaseWithExtraContentAndCallToActionLink : BaseWithExtraContent
{
public virtual string CallToActionLink {get;set;}
}
These data models are used from another class that has a list of base type, I want to be able to store any derived type in here so I added attributes as detailed in this tutorial
[SitecoreType(AutoMap = true)]
public class HomePage
{
[SitecoreChildren(InferType = true)]
[SitecoreField(FieldName = "Widgets")]
public virtual IEnumerable<Base> Widgets { get; set; }
}
According to the tutorial this should work. However the list of widget just contains class of the base type.
I then found a later tutorial that said that if you have separated out the models to a different assemblies than the one Glass is installed in you have to add an AttributeConfigurationLoader pointing to the assembly your models are in. The base and derived types are all in the same assembly so I wasn't sure this would solve the issue, but I tried it anyway.
My custom loader config looks like this:
public static class GlassMapperScCustom
{
public static void CastleConfig(IWindsorContainer container)
{
var config = new Config {UseWindsorContructor = true};
container.Install(new SitecoreInstaller(config));
}
public static IConfigurationLoader[] GlassLoaders()
{
var attributes = new AttributeConfigurationLoader("Project.Data");
return new IConfigurationLoader[] {attributes};
}
public static void PostLoad(){
//Remove the comments to activate CodeFist
/* CODE FIRST START
var dbs = Sitecore.Configuration.Factory.GetDatabases();
foreach (var db in dbs)
{
var provider = db.GetDataProviders().FirstOrDefault(x => x is GlassDataProvider) as GlassDataProvider;
if (provider != null)
{
using (new SecurityDisabler())
{
provider.Initialise(db);
}
}
}
* CODE FIRST END
*/
}
}
Upon doing the custom loader config I now get an "Ambiguous match found" exception. I have checked to see if there are any other non Glass attributes set in the classes in that assembly and there aren't.
Any ideas? I guess there are 2 questions.
Why does using the inferred type attribute not load the correct types and only the base types?
Why when I attempt to solve this by adding a custom attribute loader do I get the exception?
Widgets property has two attributes - it's either mapped to the children elements of the item, or a field, can't be both.