Only One Method Call is Shown in Output - class

I am trying to figure out how to call and output my methods correctly. However, in the output, only one method call is shown (the last one). How do I get it to output all of the method calls and not just the last one. Seems like all of the previous method calls are getting overridden and only the last one persists. I am just beginning in Java. Any help would be appreciated.
Here is the PartyDriver Class where I make 5 method calls. Only the last one is showing in the printParty method.
import java.util.ArrayList;
public class PartyDriver
{
public static void main(String[] args)
{
Party party = new Party(3, "David Beckham");
ArrayList<String> guest = new ArrayList<>();
party.addGuest("Roberto Baggio");
party.addGuest("Zinedine Zidane");
party.addGuest("Roberto Baggio");
party.addGuest("Johan Cruyff");
party.addGuest("Diego Maradona");
party.printParty();
} // end main
}//End Party Driver
Here is the Party Class with all of my methods:
import java.util.ArrayList;
public class Party
{
// instance variables that will hold your data
// private indicates they belong to this class exclusively
private int maxGuests;
private String host;
private String guest;
//Constructor
public Party(int maxGuests, String host)
{
this.maxGuests = maxGuests;
this.host = host;
}
//getter
// define type of data to be returned
public String getHost()
{
return host;
}
//setter
// setters have type void b/c they return nothing
public void setHost(String host)
{
this.host = host;
}
//*************************************
//Method to add to guest list
public void addGuest(String guest)
{
this.guest = guest;
}
//*************************************
//Method to print party
public void printParty()
{
System.out.println("Guest list for " +
this.host + "'s party is: \n\n" +
this.guest + ".\n");
} // end Print Party method
}//end class Party

No methods but PrintParty() print anything because you haven't told any methods but PrintParty() to print anything.
One way to print output to the console is to use System.out.println().
I've adjusted each of your methods to print something to the screen. I also added a guests instance variable to your Party class and made your addGuest(String guest) method modify that instance variable appropriately.
import java.util.ArrayList;
public class Party
{
// instance variables that will hold your data
// private indicates they belong to this class exclusively
private int maxGuests;
private String host;
private ArrayList<String> guests;
//Constructor
public Party(int maxGuests, String host)
{
System.out.println("Initializing party with maxGuests: '" + maxGuests + "' and host: '" + host + "'");
this.guests = new ArrayList<String>();
this.maxGuests = maxGuests;
this.host = host;
}
//getter
// define type of data to be returned
public String getHost()
{
System.out.println("Setting host to: " + host);
return host;
}
//setter
// setters have type void b/c they return nothing
public void setHost(String host)
{
System.out.println("Setting host to: " + host);
this.host = host;
}
//*************************************
//Method to add to guest list
public void addGuest(String guest)
{
if (guests.size() < maxGuests)
{
System.out.println("Adding guest: " + guest);
this.guests.add(guest);
}
else
{
System.out.println("Guest list full");
}
}
//*************************************
//Method to print party
public void printParty()
{
System.out.println("Guest list for " +
this.host + "'s party is: \n\n" +
this.guests + ".\n");
} // end Print Party method
public static void main(String[] args)
{
Party party = new Party(3, "David Beckham");
party.addGuest("Roberto Baggio");
party.addGuest("Zinedine Zidane");
party.addGuest("Roberto Baggio");
party.addGuest("Johan Cruyff");
party.addGuest("Diego Maradona");
party.printParty();
} // end main
}//end class Party

Related

How do i use the value from my main class to my other class?

So this is my main class
public class Main_Page {
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader (isr);
String type;
String ticnum;
int number;
int i=1;
int choice =0;
double distance;
double total=0;
double payment=0;
public static void main(String[] args) throws Exception{
Main_Page m=new Main_Page();
m.doMenu();
m.doBus();
m.doTrain();
}
public void doMenu() throws Exception {
do
{
System.out.println("***WELCOME***");
System.out.println("What ticket do you want to purchase?");
System.out.println("(1) Bus " + "\n(2) Train" + "\n(3) Exit");
System.out.println("Please enter your choice:");
choice=Integer.parseInt(br.readLine());
switch(choice)
{
case 1: doBus();
break;
case 2: doTrain();
break;
case 3:
Receipt re=new Receipt();
ReceiptMain rm=new ReceiptMain();
rm.setReceipt(re);
rm.getReceipt();
rm.getReceipt().print();
default: System.out.println("Invalid choice. Please try again");
}
}while(choice<=2);
}
public void doBus()throws Exception {
type="Bus";
System.out.println("Please enter distance(km):");
distance=Integer.parseInt(br.readLine());
total=distance*0.5;
payment+=total;
number+=i;
System.out.println("Total payment is:RM" +payment);
ticnum="B";
}
public void doTrain() throws Exception{
type="Train";
System.out.println("Please enter distance(km):");
distance=Integer.parseInt(br.readLine());
total=distance*0.8;
payment+=total;
number+=i;
ticnum="T";
}
}
And this is my other class
public class Receipt extends Main_Page {
public void print(){
Main_Page mp=new Main_Page();
Date d=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss");
System.out.println("******RECEIPT******");
System.out.println(d);
System.out.println("[Type] [Number] [Price]");
System.out.println(mp.type + " " + mp.number + " "
+ " " + mp.payment);
}
}
The problem that I'm having right now is, I want to use the values from my main class to my Receipt class. When I run the program, when the Receipt displays, "mp.type, mp.number and mp.payment" appears as null. But in main class, there is a value for the variables.

Open Perspective programmatically

I am trying to provide a command/ handler to switch to a specific Perspective.
I came up with the following class:
public class OpenPerspectiveHandler {
private static final Logger logger = Logger.getLogger(OpenPerspectiveHandler.class);
#Inject
private MApplication application;
#Inject
private EModelService modelService;
#Inject
private EPartService partService;
private final String perspectiveId;
public OpenPerspectiveHandler(String perspectiveId) {
super();
this.perspectiveId = perspectiveId;
}
public void changePerspective(String perspectiveId) {
Optional<MPerspective> perspective = findPerspective();
if(perspective.isPresent()) {
partService.switchPerspective(perspective.get());
} else {
logger.debug("Perspective not found (" + perspectiveId + ")");
}
}
#Execute
public void execute() {
changePerspective(perspectiveId);
}
private Optional<MPerspective> findPerspective() {
MUIElement element = modelService.find(perspectiveId, application);
if(element instanceof MPerspective) {
return Optional.of((MPerspective)element);
} else {
logger.debug("Wrong type " + element);
}
return Optional.empty();
}
#Override
public String toString() {
return "OpenPerspectiveHandler [application=" + application + ", modelService=" + modelService + ", partService=" + partService + ", perspectiveId=" + perspectiveId + "]";
}
}
Interestingly, this works only once. A workaround is to cache MPerspective once it was found and not to use modelService.find(perspectiveId, application) again.
Why does it work only once? modelService.find(perspectiveId, application) returns null after the first execution.
EDIT:
Another approach (as suggested by greg-449) is the following:
public class OpenPerspectiveHandler {
private static final Logger logger = Logger.getLogger(OpenPerspectiveHandler.class);
private final String perspectiveId;
public OpenPerspectiveHandler(String perspectiveId) {
super();
this.perspectiveId = perspectiveId;
}
#Execute
public void changePerspective(MApplication application, EModelService modelService, EPartService partService) {
Optional<MPerspective> perspective = findPerspective(application, modelService);
if(perspective.isPresent()) {
partService.switchPerspective(perspective.get());
} else {
logger.debug("Perspective not found (" + perspectiveId + ")");
}
}
private Optional<MPerspective> findPerspective(MApplication application, EModelService modelService) {
MUIElement element = modelService.find(perspectiveId, application);
if(element instanceof MPerspective) {
return Optional.of((MPerspective)element);
} else {
logger.debug("Wrong type " + element);
}
return Optional.empty();
}
}
But this approach also changes the perspective only once. modelService.find(perspectiveId, application); returns null after the first execution.
The EPartService varies depending on the context that the handler runs in. In some cases you get the Application part service which only works if there is an active window.
You can get the part service for that window using something like:
MWindow window = (MWindow)modelService.find("top window id", application);
IEclipseContext windowContext = window.getContext();
EPartService windowPartService = windowContext.get(EPartService.class);

Spring batch : FlatFileItemWriter header never called

I have a weird issue with my FlatFileItemWriter callbacks.
I have a custom ItemWriter implementing both FlatFileFooterCallback and FlatFileHeaderCallback. Consequently, I set header and footer callbacks in my FlatFileItemWriter like this :
ItemWriter Bean
#Bean
#StepScope
public ItemWriter<CityItem> writer(FlatFileItemWriter<CityProcessed> flatWriter, #Value("#{jobExecutionContext[inputFile]}") String inputFile) {
CityItemWriter itemWriter = new CityItemWriter();
flatWriter.setHeaderCallback(itemWriter);
flatWriter.setFooterCallback(itemWriter);
itemWriter.setDelegate(flatWriter);
itemWriter.setInputFileName(inputFile);
return itemWriter;
}
FlatFileItemWriter Bean
#Bean
#StepScope
public FlatFileItemWriter<CityProcessed> flatFileWriterArchive(#Value("#{jobExecutionContext[outputFileArchive]}") String outputFile) {
FlatFileItemWriter<CityProcessed> flatWriter = new FlatFileItemWriter<CityProcessed>();
FileSystemResource isr;
isr = new FileSystemResource(new File(outputFile));
flatWriter.setResource(isr);
DelimitedLineAggregator<CityProcessed> aggregator = new DelimitedLineAggregator<CityProcessed>();
aggregator.setDelimiter(";");
BeanWrapperFieldExtractor<CityProcessed> beanWrapper = new BeanWrapperFieldExtractor<CityProcessed>();
beanWrapper.setNames(new String[]{
"country", "name", "population", "popUnder25", "pop25To50", "pop50to75", "popMoreThan75"
});
aggregator.setFieldExtractor(beanWrapper);
flatWriter.setLineAggregator(aggregator);
flatWriter.setEncoding("ISO-8859-1");
return flatWriter;
}
Step Bean
#Bean
public Step stepImport(StepBuilderFactory stepBuilderFactory, ItemReader<CityFile> reader, ItemWriter<CityItem> writer, ItemProcessor<CityFile, CityItem> processor,
#Qualifier("flatFileWriterArchive") FlatFileItemWriter<CityProcessed> flatFileWriterArchive, ExecutionContextPromotionListener executionContextListener) {
return stepBuilderFactory.get("stepImport").<CityFile, CityItem> chunk(10).reader(reader(null)).processor(processor).writer(writer).stream(flatFileWriterArchive)
.listener(executionContextListener).build();
}
I have the classic content in my writeFooter, writeHeader and write methods.
ItemWriter code
public class CityItemWriter implements ItemWriter<CityItem>, FlatFileFooterCallback, FlatFileHeaderCallback, ItemStream {
private FlatFileItemWriter<CityProcessed> writer;
private static int totalUnknown = 0;
private static int totalSup10000 = 0;
private static int totalInf10000 = 0;
private String inputFileName = "-";
public void setDelegate(FlatFileItemWriter<CityProcessed> delegate) {
writer = delegate;
}
public void setInputFileName(String name) {
inputFileName = name;
}
private Predicate<String> isNullValue() {
return p -> p == null;
}
#Override
public void write(List<? extends CityItem> cities) throws Exception {
List<CityProcessed> citiesCSV = new ArrayList<>();
for (CityItem item : cities) {
String populationAsString = "";
String less25AsString = "";
String more25AsString = "";
/*
* Some processing to get total Unknown/Sup 10000/Inf 10000
* and other data
*/
// Write in CSV file
CityProcessed cre = new CityProcessed();
cre.setCountry(item.getCountry());
cre.setName(item.getName());
cre.setPopulation(populationAsString);
cre.setLess25(less25AsString);
cre.setMore25(more25AsString);
citiesCSV.add(cre);
}
writer.write(citiesCSV);
}
#Override
public void writeFooter(Writer fileWriter) throws IOException {
String newLine = "\r\n";
String totalUnknown= "Subtotal:;Unknown;" + String.valueOf(nbUnknown) + newLine;
String totalSup10000 = ";Sum Sup 10000;" + String.valueOf(nbSup10000) + newLine;
String totalInf10000 = ";Sum Inf 10000;" + String.valueOf(nbInf10000) + newLine;
String total = "Total:;;" + String.valueOf(nbSup10000 + nbInf10000 + nbUnknown) + newLine;
fileWriter.write(newLine);
fileWriter.write(totalUnknown);
fileWriter.write(totalSup10000);
fileWriter.write(totalInf10000);
fileWriter.write(total );
}
#Override
public void writeHeader(Writer fileWriter) throws IOException {
String newLine = "\r\n";
String firstLine= "FILE PROCESSED ON: ;" + new SimpleDateFormat("MM/dd/yyyy").format(new Date()) + newLine;
String secondLine= "Filename: ;" + inputFileName + newLine;
String colNames= "Country;Name;Population...;...having less than 25;...having more than 25";
fileWriter.write(firstLine);
fileWriter.write(secondLine);
fileWriter.write(newLine);
fileWriter.write(colNames);
}
#Override
public void close() throws ItemStreamException {
writer.close();
}
#Override
public void open(ExecutionContext context) throws ItemStreamException {
writer.open(context);
}
#Override
public void update(ExecutionContext context) throws ItemStreamException {
writer.update(context);
}
}
When I run my batch, I only have the data for each city (write method part) and the footer lines. If I comment the whole content of write method and footer callback, I still don't have the header lines. I tried to add a System.out.println() text in my header callback, it looks like it's never called.
Here is an example of the CSV file produced by my batch :
France;Paris;2240621;Unknown;Unknown
France;Toulouse;439553;Unknown;Unknown
Spain;Barcelona;1620943;Unknown;Unknown
Spain;Madrid;3207247;Unknown;Unknown
[...]
Subtotal:;Unknown;2
;Sum Sup 10000;81
;Sum Inf 10000;17
Total:;;100
What is weird is that my header used to work before, when I added both footer and header callbacks. I didn't change them, and I don't see what I've done in my code to "broke" my header callback... And of course, I have no save of my first code. Because I see only now that my header has disappeared (I checked my few last files, and it looks like my header is missing for some time but I didn't see it), I can't just remove my modifications to see when/why it happens.
Do you have any idea to solve this problem ?
Thanks
When using Java config as you are, it's best to return the most specific type possible (the opposite of what you're normally told to do in java programming). In this case, your writer is returning ItemWriter, but is step scoped. Because of this a proxy is created that can only see the type that your java config returns which in this case is ItemWriter and does not expose the methods on the ItemStream interface. If you return CityItemWriter, I'd expect things to work.

Sending message with external call in netty socket programming

I'm new to socket programming and Netty framework. I was trying to modify the Echo Server example so that the message is not sent from client as soon as a message is received, but a call from another thread would trigger the client send a message to the server.
The problem is, the server does not get the message unless the client sends it from readChannel or MessageReceived or channelActive which are where the server is specified with a parameter (ChannelHandlerContext). I couldn't manage to find a way to save the server channel and send a message later and repeatedly.
Here's my Client Handler code;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class EchoClientHandler extends ChannelHandlerAdapter {
ChannelHandlerContext server;
#Override
public void channelActive(ChannelHandlerContext ctx) {
this.server = ctx;
}
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// ctx.write(msg); //not
}
#Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//ctx.flush();
}
public void externalcall(String msg) throws Exception {
if(server!=null){
server.writeAndFlush("[" + "] " + msg + '\n');
}
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
ctx.close();
}
}
When Client creates the handler, it also creates a thread with a "SourceGenerator" object which gets the handler as parameter so as to call the externalcall() method.
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* Sends one message when a connection is open and echoes back any received
* data to the server. Simply put, the echo client initiates the ping-pong
* traffic between the echo client and server by sending the first message to
* the server.
*/
public class EchoClient {
private final String host;
private final int port;
public EchoClient(String host, int port, int firstMessageSize) {
this.host = host;
this.port = port;
}
public void run() throws Exception {
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
final EchoClientHandler x = new EchoClientHandler();
SourceGenerator sg = new SourceGenerator(x);
new Thread(sg).start();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(x);
}
});
// Start the client.
ChannelFuture f = b.connect(host, port).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down the event loop to terminate all threads.
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
// Print usage if no argument is specified.
if (args.length < 2 || args.length > 3) {
System.err.println(
"Usage: " + EchoClient.class.getSimpleName() +
" <host> <port> [<first message size>]");
return;
}
// Parse options.
final String host = args[0];
final int port = Integer.parseInt(args[1]);
final int firstMessageSize;
if (args.length == 3) {
firstMessageSize = Integer.parseInt(args[2]);
} else {
firstMessageSize = 256;
}
new EchoClient(host, port, firstMessageSize).run();
}
}
and the SourceGenerator class;
public class SourceGenerator implements Runnable {
public String dat;
public EchoClientHandler asd;
public SourceGenerator(EchoClientHandler x) {
asd = x;
System.out.println("initialized source generator");
dat = "";
}
#Override
public void run() {
try{
while(true){
Thread.sleep(2000);
dat += "a";
asd.externalcall(dat);
System.out.print("ha!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Thanks in advance!
If you want to write a String you need to have the StringEncoder in the ChannelPipeline.
Otherwise you can only send ByteBuf instances.

Sharing Data with the Class that does not extends Activity

I have made a TCP client for android using socket. However, the program that I have does not allow me to dynamically input the server address. Also i cannot use intent to transfer String from MainActivity because my TcpClient.java does not extends to Activity. What logic shall I implement so that I can dynamically set server address and connect to any server I wish..
MainActivity.java
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent i = new Intent(this, Preferences.class);
startActivityForResult(i, RESULT_SETTINGS);
break;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SETTINGS:
saveData();
break;
}
}
public class connectTask extends AsyncTask<String,String,TcpClient> {
#Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object and
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run(serverip, serverport);
return null;
}
}
//call it at Activity startup onStart() for example
public void loadData(){
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(MYPREFS, mode);
serverip = mySharedPreferences.getString("IP", serverip);
serverport = mySharedPreferences.getInt("Port", serverport);
}
// Call it whenever you modify the values
public void saveData()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(MYPREFS, mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("IP", serverip);
editor.putInt("Port", serverport);
editor.commit();
Toast.makeText(getBaseContext(),
"Server Settings Saved" + serverip + serverport ,
Toast.LENGTH_LONG).show();
}
}
This is not saving the data. Its showing null0 on the Toast.Also these are the variables declared for the above code
public static final String MYPREFS = "192.168.1.3";
public String serverip;
public int serverport;
Preferences.java
package com.example.homauto;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Preferences extends PreferenceActivity{
#SuppressWarnings("deprecation")
#Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
I am a newbie to programming..
Here is the website from where i took the references..Android TCP Connection tutorial
Ok, there are a couple of thing you can do in order to pass the IP and Port to the TCPClient class. For me the easiest one is to declare the run method as follows:
public void run(String srvIP, int srvPort)
{
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(srvIP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, srvPort);
You must call it like this:
mTcpClient.run("ServerIP", ServerPort);
like this: mTcpClient.run("192.168.1.25", 4444);
Other possibility is to change the create method and put those parameters there,
// You have to remove the final in these variables
public static String SERVERIP = "192.168.0.102"; //your computer IP address
public static int SERVERPORT = 4444;
public TCPClient(String srvIP, int srvPort, OnMessageReceived listener) {
SERVERIP=srvIP;
SERVERPORT=srvPort;
mMessageListener = listener;
}
and you instantiate the class like this:
mTcpClient = new TcpClient(ServerIP, ServerPort, new TcpClient.OnMessageReceived()
Now, in your application (main activity) you need to put a dialog or another activity in order to ask the user for the IP and port to connect to before you launch the TCPClient class, in your case the AsyncTask.
I'd put an action bar menu and when clicked show a dialog to ask for those values.
Also, you may save the values so that you have them for future use (in MainActivity):
// call it at Activity startup onStart() for example
public void loadData()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(Typedefs.saveConfigsFileName, mode);
serverIP = mySharedPreferences.getString("IP", serverIP);
serverPort = mySharedPreferences.getInt("Port", serverPort);
}
// Call it whenever you modify the values
public void saveData()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(Typedefs.saveConfigsFileName, mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("IP", serverIP);
editor.putInt("Port", serverPort);
editor.commit();
}