I was trying to do a simple implementation of the command patter in java. However, I am getting the following error:
java.lang.ClassNotFoundException: AddCommand
Exception in thread "main" java.lang.NullPointerException
at com.programming.sample.TransactionCommand.execute(TestTransactionCommand.java:64)
at com.programming.sample.CommandManager.runCommands(TestTransactionCommand.java:33)
at com.programming.sample.TestTransactionCommand.main(TestTransactionCommand.java:124)
Code:
package com.programming.sample;
//TestTransactionCommand.java
import java.util.*;
final class CommandReceiver {
private int[] c;
private CommandArgument a;
private CommandReceiver(){
c = new int[2];
}
private static CommandReceiver cr = new CommandReceiver();
public static CommandReceiver getHandle() {
return cr;
}
public void setCommandArgument(CommandArgument a) {
this.a = a;
}
public void methAdd() {
c = a.getArguments();
System.out.println("The result is " + (c[0]+c[1]));
}
public void methSubtract() {
c = a.getArguments();
System.out.println("The result is " + (c[0]-c[1]));
}
}
class CommandManager {
private Command myCommand;
public CommandManager(Command myCommand) {
this.myCommand = myCommand ;
}
public void runCommands( ) {
myCommand.execute();
}
}
class TransactionCommand implements Command {
private CommandReceiver commandreceiver;
private Vector commandnamelist,commandargumentlist;
private String commandname;
private CommandArgument commandargument;
private Command command;
public TransactionCommand () {
this(null,null);
}
public TransactionCommand ( Vector commandnamelist, Vector
commandargumentlist){
this.commandnamelist = commandnamelist;
this.commandargumentlist = commandargumentlist;
commandreceiver = CommandReceiver.getHandle();
}
public void execute( ) {
for (int i = 0; i < commandnamelist.size(); i++) {
commandname = (String)(commandnamelist.get(i));
commandargument = (CommandArgument)((commandargumentlist.get(i)));
commandreceiver.setCommandArgument(commandargument);
String classname = commandname + "Command";
try {
Class cls = Class.forName(classname);
command = (Command) cls.newInstance();
}
catch (Throwable e) {
System.err.println(e);
}
command.execute();
}
}
}
class AddCommand extends TransactionCommand {
private CommandReceiver cr;
public AddCommand () {
cr = CommandReceiver.getHandle();
}
public void execute( ) {
cr.methAdd();
}
}
class SubtractCommand extends TransactionCommand {
private CommandReceiver cr;
public SubtractCommand () {
cr = CommandReceiver.getHandle();
}
public void execute( ) {
cr.methSubtract();
}
}
class CommandArgument {
private int[] args;
CommandArgument() {
args = new int[2];
}
public int[] getArguments() {
return args;
}
public void setArgument(int i1, int i2) {
args[0] = i1; args[1] = i2;
}
}
public class TestTransactionCommand {
private Vector clist,alist;
public TestTransactionCommand() {
clist = new Vector();
alist = new Vector();
}
public void clearBuffer(Vector c, Vector a) {
clist.removeAll(c);
alist.removeAll(a);
}
public Vector getClist() {
return clist;
}
public Vector getAlist() {
return alist;
}
public static void main(String[] args) {
CommandArgument ca,ca2;
TestTransactionCommand t = new TestTransactionCommand();
ca = new CommandArgument();
ca.setArgument(2,8);
Vector myclist = t.getClist();
Vector myalist = t.getAlist();
myclist.addElement("Add");
myalist.addElement(ca);
TransactionCommand tc = new TransactionCommand(myclist,myalist);
CommandManager cm = new CommandManager(tc);
cm.runCommands();
t.clearBuffer(myclist,myalist);
ca2 = new CommandArgument();
ca2.setArgument(5,7);
myclist = t.getClist();
myalist = t.getAlist();
myclist.addElement("Subtract");
myalist.addElement(ca2);
myclist.addElement("Add");
myalist.addElement(ca2);
TransactionCommand tc2 = new TransactionCommand(myclist,myalist);
CommandManager cm2 = new CommandManager(tc2);
cm2.runCommands();
}
}
I guess, this is where it's failing.
try {
Class cls = Class.forName(classname);
command = (Command) cls.newInstance();
}
catch (Throwable e) {
System.err.println(e);
}
command.execute();
Obviously, the class AddCommand wasn't found in the classpath, so it resulted in the ClassNotFoundException, which you ignored with just System.err.println(e); and then trying to invoke command.execute();. The object command isn't initialized to an instance.
Perhaps, providing the full class name, like, com.programming.sample.AddCommand, would fix it.
When you create the classname, the string contains only AddCommand. The class' actual name is com.programming.sample.AddCommand.
I can't compile your code - there is no Command interface.
With simple
interface Command {
public void execute();
}
your code compiles fine just with warning:
Note: D:\dev\puzzles\TestTransactionCommand.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Related
I am trying to write an unbounded ping pipeline that takes output from a ping command and parses it to determine some statistics about the RTT (avg/min/max) and for now, just print the results.
I have already written an unbounded ping source that outputs each line as it comes in. The results are windowed every second for every 5 seconds of pings. The windowed data is fed to a Combine.globally call to statefully process the string outputs. The problem is that the accumulators are never merged and the output is never extracted. This means that the pipeline never continues past this point. What am I doing wrong here?
public class TestPingIPs {
public static void main(String[] args)
{
PipelineOptions options = PipelineOptionsFactory.create();
Pipeline pipeline = Pipeline.create(options);
String destination = "8.8.8.8";
PCollection<PingResult> res =
/*
Run the unbounded ping command. Only the lines where the result of the ping command are returned.
No statistics or first startup lines are returned here.
*/
pipeline.apply("Ping command",
PingCmd.read()
.withPingArguments(PingCmd.PingArguments.create(destination, -1)))
/*
Window the ping command strings into 5 second sliding windows produced every 1 second
*/
.apply("Window strings",
Window.into(SlidingWindows.of(Duration.standardSeconds(5))
.every(Duration.standardSeconds(1))))
/*
Parse and aggregate the strings into a PingResult object using stateful processing.
*/
.apply("Combine the pings",
Combine.globally(new ProcessPings()).withoutDefaults())
/*
Test our output to see what we get here
*/
.apply("Test output",
ParDo.of(new DoFn<PingResult, PingResult>() {
#ProcessElement
public void processElement(ProcessContext c)
{
System.out.println(c.element().getAvgRTT());
System.out.println(c.element().getPacketLoss());
c.output(c.element());
}
}));
pipeline.run().waitUntilFinish();
}
static class ProcessPings extends Combine.CombineFn<String, RttStats, PingResult> {
private long getRTTFromLine(String line){
long rtt = Long.parseLong(line.split("time=")[1].split("ms")[0]);
return rtt;
}
#Override
public RttStats createAccumulator()
{
return new RttStats();
}
#Override
public RttStats addInput(RttStats mutableAccumulator, String input)
{
mutableAccumulator.incTotal();
if (input.contains("unreachable")) {
_unreachableCount.inc();
mutableAccumulator.incPacketLoss();
}
else if (input.contains("General failure")) {
_transmitFailureCount.inc();
mutableAccumulator.incPacketLoss();
}
else if (input.contains("timed out")) {
_timeoutCount.inc();
mutableAccumulator.incPacketLoss();
}
else if (input.contains("could not find")) {
_unknownHostCount.inc();
mutableAccumulator.incPacketLoss();
}
else {
_successfulCount.inc();
mutableAccumulator.add(getRTTFromLine(input));
}
return mutableAccumulator;
}
#Override
public RttStats mergeAccumulators(Iterable<RttStats> accumulators)
{
Iterator<RttStats> iter = accumulators.iterator();
if (!iter.hasNext()){
return createAccumulator();
}
RttStats running = iter.next();
while (iter.hasNext()){
RttStats next = iter.next();
running.addAll(next.getVals());
running.addLostPackets(next.getLostPackets());
}
return running;
}
#Override
public PingResult extractOutput(RttStats stats)
{
stats.calculate();
boolean connected = stats.getPacketLoss() != 1;
return new PingResult(connected, stats.getAvg(), stats.getMin(), stats.getMax(), stats.getPacketLoss());
}
private final Counter _successfulCount = Metrics.counter(ProcessPings.class, "Successful pings");
private final Counter _unknownHostCount = Metrics.counter(ProcessPings.class, "Unknown hosts");
private final Counter _transmitFailureCount = Metrics.counter(ProcessPings.class, "Transmit failures");
private final Counter _timeoutCount = Metrics.counter(ProcessPings.class, "Timeouts");
private final Counter _unreachableCount = Metrics.counter(ProcessPings.class, "Unreachable host");
}
I would guess that there are some issues with the CombineFn that I wrote, but I can't seem to figure out what's going wrong here! I tried following the example here, but there's still something I must be missing.
EDIT: I added the ping command implementation below. This is running on a Direct Runner while I test.
PingCmd.java:
public class PingCmd {
public static Read read(){
if (System.getProperty("os.name").startsWith("Windows")) {
return WindowsPingCmd.read();
}
else{
return null;
}
}
WindowsPingCmd.java:
public class WindowsPingCmd extends PingCmd {
private WindowsPingCmd()
{
}
public static PingCmd.Read read()
{
return new WindowsRead.Builder().build();
}
static class PingCheckpointMark implements UnboundedSource.CheckpointMark, Serializable {
#VisibleForTesting
Instant oldestMessageTimestamp = Instant.now();
#VisibleForTesting
transient List<String> outputs = new ArrayList<>();
public PingCheckpointMark()
{
}
public void add(String message, Instant timestamp)
{
if (timestamp.isBefore(oldestMessageTimestamp)) {
oldestMessageTimestamp = timestamp;
}
outputs.add(message);
}
#Override
public void finalizeCheckpoint()
{
oldestMessageTimestamp = Instant.now();
outputs.clear();
}
// set an empty list to messages when deserialize
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException
{
stream.defaultReadObject();
outputs = new ArrayList<>();
}
#Override
public boolean equals(#Nullable Object other)
{
if (other instanceof PingCheckpointMark) {
PingCheckpointMark that = (PingCheckpointMark) other;
return Objects.equals(this.oldestMessageTimestamp, that.oldestMessageTimestamp)
&& Objects.deepEquals(this.outputs, that.outputs);
}
else {
return false;
}
}
}
#VisibleForTesting
static class UnboundedPingSource extends UnboundedSource<String, PingCheckpointMark> {
private final WindowsRead spec;
public UnboundedPingSource(WindowsRead spec)
{
this.spec = spec;
}
#Override
public UnboundedReader<String> createReader(
PipelineOptions options, PingCheckpointMark checkpointMark)
{
return new UnboundedPingReader(this, checkpointMark);
}
#Override
public List<UnboundedPingSource> split(int desiredNumSplits, PipelineOptions options)
{
// Don't really need to ever split the ping source, so we should just have one per destination
return Collections.singletonList(new UnboundedPingSource(spec));
}
#Override
public void populateDisplayData(DisplayData.Builder builder)
{
spec.populateDisplayData(builder);
}
#Override
public Coder<PingCheckpointMark> getCheckpointMarkCoder()
{
return SerializableCoder.of(PingCheckpointMark.class);
}
#Override
public Coder<String> getOutputCoder()
{
return StringUtf8Coder.of();
}
}
#VisibleForTesting
static class UnboundedPingReader extends UnboundedSource.UnboundedReader<String> {
private final UnboundedPingSource source;
private String current;
private Instant currentTimestamp;
private final PingCheckpointMark checkpointMark;
private BufferedReader processOutput;
private Process process;
private boolean finishedPings;
private int maxCount = 5;
private static AtomicInteger currCount = new AtomicInteger(0);
public UnboundedPingReader(UnboundedPingSource source, PingCheckpointMark checkpointMark)
{
this.finishedPings = false;
this.source = source;
this.current = null;
if (checkpointMark != null) {
this.checkpointMark = checkpointMark;
}
else {
this.checkpointMark = new PingCheckpointMark();
}
}
#Override
public boolean start() throws IOException
{
WindowsRead spec = source.spec;
String cmd = createCommand(spec.pingConfiguration().getPingCount(), spec.pingConfiguration().getDestination());
try {
ProcessBuilder builder = new ProcessBuilder(cmd.split(" "));
builder.redirectErrorStream(true);
process = builder.start();
processOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));
return advance();
} catch (Exception e) {
throw new IOException(e);
}
}
private String createCommand(int count, String dest){
StringBuilder builder = new StringBuilder("ping");
String countParam = "";
if (count <= 0){
countParam = "-t";
}
else{
countParam += "-n " + count;
}
return builder.append(" ").append(countParam).append(" ").append(dest).toString();
}
#Override
public boolean advance() throws IOException
{
String line = processOutput.readLine();
// Ignore empty/null lines
if (line == null || line.isEmpty()) {
line = processOutput.readLine();
}
// Ignore the 'Pinging <dest> with 32 bytes of data' line
if (line.contains("Pinging " + source.spec.pingConfiguration().getDestination())) {
line = processOutput.readLine();
}
// If the pings have finished, ignore
if (finishedPings) {
return false;
}
// If this is the start of the statistics, the pings are done and we can just exit
if (line.contains("statistics")) {
finishedPings = true;
}
current = line;
currentTimestamp = Instant.now();
checkpointMark.add(current, currentTimestamp);
if (currCount.incrementAndGet() == maxCount){
currCount.set(0);
return false;
}
return true;
}
#Override
public void close() throws IOException
{
if (process != null) {
process.destroy();
if (process.isAlive()) {
process.destroyForcibly();
}
}
}
#Override
public Instant getWatermark()
{
return checkpointMark.oldestMessageTimestamp;
}
#Override
public UnboundedSource.CheckpointMark getCheckpointMark()
{
return checkpointMark;
}
#Override
public String getCurrent()
{
if (current == null) {
throw new NoSuchElementException();
}
return current;
}
#Override
public Instant getCurrentTimestamp()
{
if (current == null) {
throw new NoSuchElementException();
}
return currentTimestamp;
}
#Override
public UnboundedPingSource getCurrentSource()
{
return source;
}
}
public static class WindowsRead extends PingCmd.Read {
private final PingArguments pingConfig;
private WindowsRead(PingArguments pingConfig)
{
this.pingConfig = pingConfig;
}
public Builder builder()
{
return new WindowsRead.Builder(this);
}
PingArguments pingConfiguration()
{
return pingConfig;
}
public WindowsRead withPingArguments(PingArguments configuration)
{
checkArgument(configuration != null, "configuration can not be null");
return builder().setPingArguments(configuration).build();
}
#Override
public PCollection<String> expand(PBegin input)
{
org.apache.beam.sdk.io.Read.Unbounded<String> unbounded =
org.apache.beam.sdk.io.Read.from(new UnboundedPingSource(this));
return input.getPipeline().apply(unbounded);
}
#Override
public void populateDisplayData(DisplayData.Builder builder)
{
super.populateDisplayData(builder);
pingConfiguration().populateDisplayData(builder);
}
static class Builder {
private PingArguments config;
Builder()
{
}
private Builder(WindowsRead source)
{
this.config = source.pingConfiguration();
}
WindowsRead.Builder setPingArguments(PingArguments config)
{
this.config = config;
return this;
}
WindowsRead build()
{
return new WindowsRead(this.config);
}
}
#Override
public int hashCode()
{
return Objects.hash(pingConfig);
}
}
One thing I notice in your code is that advance() always returns True. The watermark only advances on bundle completion, and I think it's runner-dependent whether a runner will ever complete a bundle if advance ever never returns False. You could try returning False after a bounded amount of time/number of pings.
You could also consider re-writing this as an SDF.
I'm having problems to resolve an issue. First I have an abstract class inheriting from RecursiveTask:
public abstract class GeneratorTaskBase<T, U extends RecursiveTask<T>> extends RecursiveTask<T> {
#Override
protected T compute() {
LOG.debug("Computing: start={}, end={}", start, end);
if (end - start <= THRESHOLD) {
try {
return process();
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
final int mid = start + (end - start) / 2;
final U leftTask = getTask(start, mid);
final U rightTask = getTask(mid, end);
leftTask.fork();
rightTask.fork();
final T leftResult = leftTask.join();
final T rightResult = rightTask.join();
return getResult(leftResult, rightResult);
}
}
protected abstract T getResult(T leftResult, T rightResult);
protected abstract T process() throws Exception;
protected abstract U getTask(final int start, final int end);
protected abstract String generate();
}
A subclass
public class SqlGenerator extends GeneratorTaskBase<String, SqlGenerator> {
#Override
public String generate() {
this.end = this.files.size();
return this.invoke();
}
#Override
protected SqlGenerator getTask(final int start, final int end) {
return new SqlGenerator(this.path).files(files).start(start).end(end);
}
}
I'm making the call for the task like this:
public final class CsvAsSqlDataProcessor implements
DataProcessor<String, FileInput>
#Override
public void process(FileInput input) {
final String fileName = input.source().getName();
final String directory = input.getDirectory();
LOG.debug("directory: {}", directory);
try {
final CSVReader reader = new CSVReader(new FileReader(directory
.concat(File.separator).concat(fileName)),
SEMICOLON_DELIMETER);
final List<String[]> rows = reader.readAll();
reader.close();
fullInsertStatement = new InsertSqlGenerator(rows, input.source())
.generate();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
When I run it I'm getting the exception:
Exception in thread "main" java.lang.ClassCastException: java.lang.Thread cannot be cast to java.util.concurrent.ForkJoinWorkerThread
at java.util.concurrent.ForkJoinTask.fork(ForkJoinTask.java:622)
at com.bosch.mome.importer.batch.export.sql.GeneratorTaskBase.compute(GeneratorTaskBase.java:40)
at java.util.concurrent.RecursiveTask.exec(RecursiveTask.java:93)
at java.util.concurrent.ForkJoinTask.doInvoke(ForkJoinTask.java:377)
at java.util.concurrent.ForkJoinTask.invoke(ForkJoinTask.java:654)
at com.bosch.mome.importer.batch.export.sql.SqlGenerator.generate(SqlGenerator.java:69)
Can anybody give a hint about what I'm doing wrong?
I solved like this:
#Override
public String generate() {
this.end = this.files.size();
ForkJoinPool pool = new ForkJoinPool();
pool.execute(this);
return this.join();
}
I am new to programming and I am having an issue with my program that should return this output:
Portfolio #00001, ASD = 42.50, DFAS = 45.00, CAC = 22.20, BDM = 52.50
Portfolio #00002, ASD = 42.50, DFAS = 45.00, CAC = 22.20, BDM = 52.50
Portfolio #00001, ASD = 43.35, DFAS = 45.90, CAC = 22.64, BDM = 53.55
Portfolio #00002, ASD = 43.35, DFAS = 45.90, CAC = 22.64, BDM = 53.55
Portfolio #00001, ASD = 41.18, DFAS = 43.61, CAC = 21.51, BDM = 50.87
Portfolio #00002, ASD = 41.18, DFAS = 43.61, CAC = 21.51, BDM = 50.87
Portfolio #00001, ASD = 43.65, DFAS = 46.22, CAC = 22.80, BDM = 53.92
Portfolio #00002, ASD = 43.65, DFAS = 46.22, CAC = 22.80, BDM = 53.92
Currently, my program is not returning anything. Could someone please help?
Here are the classes :
DisplayElement Interface :
public interface DisplayElement {
public void display();
}
Observer Interface :
public interface Observer {
public void update (Map<String,Double> priceMap);
}
You need to register your protfolios after their creation, and before calling setPrices(), as required by the observer pattern: Your program should be like :
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
interface DisplayElement {
void display();
}
interface Observer {
void update (Map<String,Double> priceMap);
}
class PricesDisplay implements Observer, DisplayElement {
private String ticker;
private double price;
private Subject PriceData;
Map<String,Double> priceMap;
PricesDisplay(Subject PriceData) {
this.PriceData = PriceData;
}
PricesDisplay(String ticker, Subject PriceData) {
this.ticker = ticker;
this.PriceData = PriceData;
}
public void update(Map<String,Double> priceMap) {
this.priceMap = priceMap;
display();
}
public void display() {
for (Map.Entry<String, Double> entry : priceMap.entrySet()) {
System.out.printf("\nPortfolio #%s, " + "%s = " + "%.2f, ",
ticker, entry.getKey(), entry.getValue());
}
}
}
interface Subject{
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
void measurementsChanged();
void setPrices(Map<String,Double> priceMap);
}
class PriceData implements Subject {
private ArrayList observers;
PriceData priceData;
private Map<String,Double> priceMap = new HashMap<String,Double>();
PriceData() {
observers = new ArrayList();
}
public void registerObserver(Observer o) {
observers.add(o);
}
public void removeObserver(Observer o) {
int i = observers.indexOf(o);
if (i >= 0) {
observers.remove(i);
}
}
public void notifyObservers() {
for (int i = 0; i < observers.size(); i++) {
Observer observer = (Observer)observers.get(i);
observer.update(priceMap);
}
}
public void measurementsChanged() {
notifyObservers();
}
public void setPrices(Map<String,Double> priceMap) {
this.priceMap = priceMap;
measurementsChanged();
}
}
class Test {
private static Map<String,Double> priceMap = new HashMap<String,Double>();
private static PriceData priceData = new PriceData();
public static void main(String[] args) {
// establish two portfolios as listeners for priceData.
// for now, we assume that both portfolios contain the same
// collection of investments.
PricesDisplay firstPortfolio =
new PricesDisplay("00001", priceData);
PricesDisplay secondPortfolio =
new PricesDisplay("00002", priceData);
priceData.registerObserver(firstPortfolio);
priceData.registerObserver(secondPortfolio);
generateInitialPrices();
updatePrices(.02);
updatePrices(-.05);
updatePrices(.06);
}
static void generateInitialPrices()
{
priceMap.put("ASD", 42.50);
priceMap.put("BDM", 52.50);
priceMap.put("CAC", 22.20);
priceMap.put("DFAS", 45.00);
priceData.setPrices(priceMap);
}
static void updatePrices(double changePercent)
{
for( String key : priceMap.keySet())
{
double v = priceMap.get(key) * (1.0 + changePercent);
priceMap.put(key, v);
}
priceData.setPrices(priceMap);
}
}
setPrices should be :
public <map> void setPrices(Map<> priceMap) {
this.priceMap = priceMap; // <-- missing line
measurementsChanged();
}
I have got the following code Simmulation.java, but when I tried compiling it, it is coming up with an error saying,
error: constructor CashewPallet in class CashewPallet cannot be applied to give types;
CashewPallet c1 = new CashewPallet();
Required: String,int, found: no arguments
Reason: Actual and formal arguments differ in length
I know what this error means, and when I tried to fix the line to CashewPallet c1 = new CashewPallet(String, int); and again CashewPallet c1 = new CashewPallet(nutType, id); but either didn't work! AND now I am not sure how can this be solved.
I am new to this, any help is much appreciated.
Many Thanks in advance!
Please bear with me.
EDIT : Thank you for the answers everyone! It has worked now and compiled successfully BUT when I executed it, it is coming up with error: ArrayIndexOutOfBoundsException :0 at Simmulation.main(Simmulation.java:201) Any help in fixing it Please?
THANK YOU!
This is Simmulation.java file
import java.io.File;
import java.util.LinkedList;
import java.util.Queue;
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class Simmulation implements Operation {
Queue<CashewPallet> inputQueue=new LinkedList<CashewPallet>();
Stack<CashewPallet> stBay1=new Stack<CashewPallet>();
Stack<CashewPallet> stBay2=new Stack<CashewPallet>();
FileOutputStream fout4;
PrintWriter pw;
static int tick=0;
CashewPallet c1;
String temp;
Scanner sc;
public Simmulation(String fn)
{
int index=0;
String nutType="";
int id=0;
Scanner s2 ;
try
{
sc = new Scanner(new File(fn));
fout4=new FileOutputStream("nuts.txt");
pw=new PrintWriter(fout4,true);
String eol = System.getProperty("line.separator");
while(sc.hasNextLine())
{
tick++;
s2 = new Scanner(sc.nextLine());
if(s2.hasNext())
{
while ( s2.hasNext())
{
String s = s2.next();
if(index==0)
{
nutType=s;
}
else
{
id=Integer.parseInt(s);
}
index++;
}
System.out.println("Nuttype "+nutType+" Id is "+id+"tick "+tick);
if((nutType.equalsIgnoreCase("A")||nutType.equalsIgnoreCase("P")|| nutType.equalsIgnoreCase("C")|| nutType.equalsIgnoreCase("W")) && id!=0)
inputQueue.add(new CashewPallet(nutType.toUpperCase(),id));
System.out.println("Size of Queue "+inputQueue.size());
int k=0;
if(!inputQueue.isEmpty())
{
while(inputQueue.size()>k)
{
// stBay1.push(inputQueue.poll());
process(inputQueue.poll());
k++;
}
// System.out.println("Size of input "+inputQueue.size() +" Size of stay "+stBay1.size());
}
}
else
{
fout4.write(" ".getBytes());
}
index=0;
if(!stBay2.isEmpty())
{
while(!stBay2.isEmpty())
{
c1=stBay2.pop();
temp=tick+" "+c1.getNutType()+" "+c1.getId()+eol;
fout4.write(temp.getBytes());
}
// System.out.println("Nut final "+ stBay2.peek().getNutType());
}
else
{
temp=tick+eol;
fout4.write(temp.getBytes());
}
}
}
catch(Exception e)
{
System.out.println("Exception "+e);
}
closeStream();
}
public CashewPallet process( CashewPallet c)
{
//CashewPallet c=new CashewPallet();
int k=0;
//while(stBay.size()>k)
//{
//c=stBay.pop();
String operation=c.getNutType();
if(c.getPriority()==1)
{
shelling(c);
washing(c);
packing(c);
//stBay2.push(c);
}
else
{
switch(operation)
{
case "A": shelling(c);
washing(c);
packing(c);
break;
case "C": washing(c);
packing(c);
break;
case "W" : washing(c);
shelling(c);
packing(c);
break;
}
}
return c;
}
public void closeStream()
{
try
{
fout4.close();
}
catch(Exception e)
{
}
}
public boolean shelling(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Shelling for "+c.getNutType());
}
return true;
}
public boolean washing(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Washing for "+c.getNutType());
}
return true;
}
public boolean packing(CashewPallet c)
{
//for(int i=0;i<20; i++)
{
System.out.println("Performing Packing for "+c.getNutType());
}
stBay2.push(c);
return true;
}
public static void main(String args[])
{
new Simmulation(args[0]);
}
This is CashewPallet.java file
public class CashewPallet {
private String nutType;
private int id;
private int priority;
private int opTick;
public int getOpTick() {
return opTick;
}
public void setOpTick(int opTick) {
this.opTick = opTick;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public CashewPallet(String nutType, int id) {
this.nutType = nutType;
this.id = id;
if(this.nutType.equalsIgnoreCase("p"))
{
priority=1;
}
else
{
priority=0;
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNutType() {
return nutType;
}
public void setNutType(String nutType) {
this.nutType = nutType;
}
When you use CashewPallet's constructor, you need to supply actual values for the arguments. The arguments are String nutType and int id, which means you need to supply a String that will go into nutType and an int that will go into id. For example:
CashewPallet c1 = new CashewPallet("Pecan", 42);
The constructor in CashewPallet requires a String and an int; you didn't provide them:
public CashewPallet(String nutType, int id)
You called it like this:
CashewPallet c1 = new CashewPallet();
Change it to something like:
CashewPallet c1 = new CashewPallet("Peanut",1337);
EDIT:
You're getting an ArrayIndexOutOfBoundsException on this line:
new Simmulation(args[0]);
That's in your args[0]. If that's out of bounds, then that means that you don't have command line arguments.
You should call it with command line arguments (or specifically one command line argument).
java Simmulation myarg
In this case your argument is the name of your file.
public class ObjectToProxy
{
List<ObjectToProxy> potentiallyCircularReference;
}
public class SubClass
{
private ObjectToProxy aField;
Set<ObjectToProxy> aSetOfObjectsToProxy;
}
public class CrazyObject
{
Map<Integer, ObjectToProxy> proxiedObjects;
List<SubClass> manySubClasses;
}
public class ComplexObject
{
List<CrazyObject> crazyObjects;
private final ObjectToProxy storedAsAField;
}
I have a complex object graph. Lets say it looks a little like the one above (even though it is much deeper in the real system). I would like, after being given ComplexObject, to be able to traverse the object graph and replace all ObjectToProxys with a proxying object.
Is this doable?
The reason for this is that we have some pretty big nasty objects which we partially load on the servers side (legacy, you're my friend!). We have a semi-working solution that uses proxying on the client side to go through and loads the full object when needed.
edit I would like to replace every instance of ObjectProxy connected to a ComplexObject.
public static class ProxyObject extends ObjectToProxy
{
private final ObjectToProxy objectToProxy;
public ProxyObject(ObjectToProxy objectToProxy)
{
this.objectToProxy = objectToProxy;
}
#Override
public String toString()
{
return "ProxyObject";
}
}
public static class ObjectToProxy
{
List<ObjectToProxy> potentiallyCircularReference;
public ObjectToProxy()
{
potentiallyCircularReference = new ArrayList<>();
potentiallyCircularReference.add(this);
}
#Override
public String toString()
{
return "ObjectToProxy";
}
}
public static class SubClass
{
ObjectToProxy aField;
Set<ObjectToProxy> aSetOfObjectsToProxy;
}
public static class CrazyObject
{
Map<Integer, ObjectToProxy> proxiedObjects;
List<SubClass> manySubClasses;
public CrazyObject()
{
proxiedObjects = new HashMap<>();
proxiedObjects.put(1, new ObjectToProxy());
}
}
public static class ComplexObject
{
List<CrazyObject> crazyObjects;
final ObjectToProxy storedAsAField;
public ComplexObject()
{
this.storedAsAField = new ObjectToProxy();
crazyObjects = new ArrayList<>();
crazyObjects.add(new CrazyObject());
}
#Override
public String toString()
{
return "myField: " + storedAsAField.toString();
}
}
public static void main(String[] args) throws Exception
{
ComplexObject obj = new ComplexObject();
Set<Object> visitedObjects = Sets.newIdentityHashSet();
Queue<Object> objectsToVisit = new LinkedList<>();
visitedObjects.add(obj);
objectsToVisit.add(obj);
while (!objectsToVisit.isEmpty())
{
handleFields(objectsToVisit.poll(), visitedObjects, objectsToVisit);
}
System.out.println(obj.toString());
}
private static void handleFields(Object obj, Set<Object> visitedObjects, Queue<Object> objectsToVisit) throws Exception
{
List<Field> fields = getAllFields(obj);
for (Field field : fields)
{
field.setAccessible(true);
Object fieldValue = field.get(obj);
if (fieldValue != null && !visitedObjects.contains(fieldValue))
{
if (fieldValue instanceof Object[])
{
visitedObjects.add(fieldValue);
Object[] array = (Object[])fieldValue;
for (Object arrayObj : array)
{
if (arrayObj != null && !objectsToVisit.contains(arrayObj))
{
visitedObjects.add(arrayObj);
if (!DontLookAt.contains(arrayObj.getClass()))
objectsToVisit.add(arrayObj);
}
}
}
else
{
if (!DontLookAt.contains(fieldValue.getClass()))
objectsToVisit.add(fieldValue);
}
if (fieldValue.getClass().equals(ObjectToProxy.class))
{
field.set(obj, new ProxyObject((ObjectToProxy)fieldValue));
}
else if (fieldValue instanceof ObjectToProxy[])
{
ObjectToProxy[] array = (ObjectToProxy[])fieldValue;
for (int i = 0; i < array.length; i++)
{
if (array[i] != null)
array[i] = new ProxyObject(array[i]);
}
}
}
}
}
private static final Set<Class> DontLookAt = getDontLookAtSet();
private static Set<Class> getDontLookAtSet()
{
Set<Class> set = new HashSet<>();
set.add(Long.class);
set.add(Boolean.class);
set.add(Integer.class);
set.add(String.class);
set.add(Byte.class);
set.add(Double.class);
set.add(Float.class);
set.add(Class.class);
return set;
}
private static List<Field> getAllFields(Object obj) throws Exception
{
List<Field> output = new ArrayList<>();
Class klazz = obj.getClass();
while (!klazz.equals(Object.class))
{
Field[] fields = klazz.getDeclaredFields();
output.addAll(Arrays.asList(fields));
klazz = klazz.getSuperclass();
}
return output;
}
For anyone wondering, The above simulates and does what I'm after. I'm sure it isn't perfect, but it is good enough for my purposes.