How to write this Java Class in C# Class format - java

How to write this Java Class in C# Class format
public final class JsonParserResolver {
// PlacesApiJsonParser is an Interface
public static final PlacesApiJsonParser JSON_PARSER;
static {
boolean hasGson;
try {
Class.forName("com.google.gson.Gson");
hasGson = true;
} catch (ClassNotFoundException e) {
hasGson = false;
}
JSON_PARSER = hasGson ? new GsonPlacesApiJsonParser() : new
AndroidPlacesApiJsonParser();
}
private JsonParserResolver() {
throw new RuntimeException("No instances");
}
}
The class static member is resolving stuff automatically on Class instantiation. This is a very useful
Hold your horses this is where I am, I get a little stuck on the JSON_PARSER
namespace WorkSampleBookSearch
{
public final class JsonParserResolver
{
public static final PlacesApiJsonParser JSON_PARSER;
static {
boolean hasGson;
JSON_PARSER = hasGson? new GsonPlacesApiJsonParser() : new AndroidPlacesApiJsonParser();
}
private JsonParserResolver()
{
throw new RuntimeException("No instances");
}
}
}

Related

Unable to serialize instance variable of a non-serializable superclass from the serializable subclass

New to this topic and right now I'm stuck at a brick wall. I have 2 classes, parent class: Controller.java and subclass: GreenhouseControls.java. I need to serialize a GreenhouseControls object but also an instance variable (eventList) from its superclass Controller.java.
My serialization happens when an inner class of GreenhouseControls.java throws a custom ControllerException, which is caught in the main method. Before terminating the program, the GreenhouseControls object should be saved (including the field from its superclass).
Why is a NotSerializableException thrown by the inner class WindowMalfunction of GreenhouseControls? Anyone have any ideas, as I am seriously stuck?
What I tried is the following:
Implement serializable on Controller.java. This is because if the superclass is serializable, then subclass is automatically serializable, however this throws java.io.NotSerializableException: GreenhouseControls$WindowMalfunction, (WindowMalfunction is the inner class that throws the initial exception to begin the serialization processs).
Implement serializable on GreenhouseControls.java and implement custom serialization by overriding writeObject() and readObject() to save the field from the superclass. This approach yet again throws the same exception as the approach 1.
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(super.eventList);
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
Object obj = in.readObject();
List<Event> x = cast(obj);
super.eventList = x;
}
Controller.java
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class Controller {
// THIS IS THE VARIABLE I NEED TO SAVE
protected List<Event> eventList = new ArrayList<Event>();
public void addEvent(Event c) {
eventList.add(c);
}
public void run() throws ControllerException {
while (eventList.size() > 0)
// Make a copy so you're not modifying the list
// while you're selecting the elements in it:
for (Event e : new ArrayList<Event>(eventList))
if (e.ready()) {
System.out.println(e);
e.action();
eventList.remove(e);
}
}
public static void shutDown() { }
}
GreenhouseControls.java class (note I have removed the inner classes and other code from it and only left related info)
public class GreenhouseControls extends Controller implements Serializable {
private int errorcode = 0;
public class WindowMalfunction extends Event {
public WindowMalfunction(long delayTime) {
super(delayTime);
}
public void action() throws ControllerException {
windowok = false;
throw new ControllerException("Window malfunction");
}
public String toString() {
return "Window malfunction";
}
}
public class PowerOut extends Event {
public PowerOut(long delayTime) {
super(delayTime);
}
public void action() throws ControllerException {
poweron = false;
throw new ControllerException("Power out");
}
public String toString() {
return "Power out";
}
}
// Various other inner classes that extend event exist
public static void serializeObject(GreenhouseControls gc) {
FileOutputStream fileOut;
ObjectOutputStream out;
try {
fileOut = new FileOutputStream("dump.out");
out = new ObjectOutputStream(fileOut);
out.writeObject(gc);
System.out.println("WERRROR code: " + gc.getError());
out.close();
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(super.eventList);
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
Object obj = in.readObject();
List<Event> x = cast(obj);
super.eventList = x;
}
#SuppressWarnings("unchecked")
public static <T extends List<?>> T cast(Object obj) {
return (T) obj;
}
public int getError() {
return errorcode;
}
public Fixable getFixable(int errorcode) {
switch (errorcode) {
case 1:
return new FixWindow();
case 2:
return new PowerOn();
default:
return null;
}
}
public static void main(String[] args) {
GreenhouseControls gc = null;
try {
String option = args[0];
String filename = args[1];
if (!(option.equals("-f")) && !(option.equals("-d"))) {
System.out.println("Invalid option");
printUsage();
}
// gc = new GreenhouseControls();
if (option.equals("-f")) {
gc = new GreenhouseControls();
gc.addEvent(gc.new Restart(0, filename));
}
gc.run();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid number of parameters");
printUsage();
} catch (ControllerException e) {
String errormsg;
if (e.getMessage().equals("Window malfunction")) {
gc.errorcode = 1;
errormsg = "Window malfunction event occurred Error code: " + gc.errorcode;
} else {
gc.errorcode = 2;
errormsg = "Power out event occurred Error code: " + gc.errorcode;
}
logError(errormsg);
serializeObject(gc);
gc.displayEventList();
shutDown();
}
}
}
Event.java
public abstract class Event {
private long eventTime;
protected final long delayTime;
public Event(long delayTime) {
this.delayTime = delayTime;
start();
}
public void start() { // Allows restarting
eventTime = System.currentTimeMillis() + delayTime;
}
public boolean ready() {
return System.currentTimeMillis() >= eventTime;
}
public abstract void action() throws ControllerException;
Event has to be Serializable too.
Change
public abstract class Event {
to
public abstract class Event implements Serializable {

Java generics api architecture

I'm implementing a strategy pattern for exceptions handling
public class GlobalExceptionHandler {
private interface Strategy<T extends Exception> {
ErrorResponse extract(T e);
}
private static class ResponseStatusStrategy implements Strategy<ResponseStatusException> {
#Override
public ErrorResponse extract(ResponseStatusException e) {
return ErrorResponse.builder()
.status(e.getStatus())
.message(e.getReason())
.description(e.getReason())
.build();
}
}
private static class IllegalStateStrategy implements Strategy<IllegalStateException> {
#Override
public ErrorResponse extract(IllegalStateException e) {
return ErrorResponse.builder()
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.message(e.getMessage())
.description("")
.build();
}
}
....
I call this API like this:
Exception ex = ....; // function param
if (ex instanceof ResponseStatusException) {
errorResponse = new ResponseStatusStrategy().extract((ResponseStatusException) ex);
} else if (ex instanceof IllegalStateException) {
errorResponse = new IllegalStateStrategy().extract((IllegalStateException) ex);
} else {
errorResponse = new EmptyStrategy().extract(ex);
}
Is there a more efficient and beautiful way to implement this? Idea gets me hint that I even didn't use interface method: "method extract(T e) is never used".
It would be great to have API like this:
Strategy<???> strategy;
if (ex instanceof ResponseStatusException) {
strategy = new ResponseStatusStrategy();
} else if (ex instanceof IllegalStateException) {
strategy = new IllegalStateStrategy();
} else {
strategy = new EmptyStrategy();
}
errorResponse = strategy.extract(ex);
You are trying to solve an object creational problem. You want a particular Strategy class object based on the StatusException class. Create a new class with a factory pattern to return you the correct object. Here is some dummy code inspired from your code.
private interface Factory {
Strategy buildStrategy(Exception e);
}
private static class FactoryImpl implements Factory {
public Strategy buildStrategy(Exception e) {
if (e instanceof IOException) {
return new Strategy1();
} else {
return new EmptyStrategy();
}
}
}
private interface Strategy<T extends Exception> {
String extract();
}
private static class Strategy1 implements Strategy<IOException> {
#Override public String extract() {
return "Strategy1";
}
}
private static class EmptyStrategy implements Strategy<NamingException> {
#Override public String extract() {
return "EmptyStrategy";
}
}
public static void main(String[] args) {
var f = new FactoryImpl();
System.out.println(f.buildStrategy(new IOException()).extract());
System.out.println(f.buildStrategy(new NamingException()).extract());
}

Java constructor cannot be applied to given types

After having gone through this question I'm still unable to build the following file:
public class ContextImpl implements Context {
private static final Logger logger = LoggerFactory.getLogger(ContextImpl.class);
private static final Map<String, TransportFactory> transportFactories = new HashMap<>();
private static final Map<String, SerializerFactory> serializerFactories = new HashMap<>();
ContextImpl() { }
ContextImpl(boolean isSecureContext) {
registerSerializerFactory(new CDRSerializerFactory());
if(isSecureContext) {
registerTransportFactory(new TcpBlockTransportFactory(/*secure = */true));
registerTransportFactory(new HttpTransportFactory(/*secure = */true));
} else {
registerTransportFactory(new TcpBlockTransportFactory(/*secure = */false));
registerTransportFactory(new HttpTransportFactory(/*secure = */false));
}
}
private static SerializerFactory getSerializerFactoryByName(String serializerName) {
synchronized (serializerFactories) {
return serializerFactories.get(serializerName);
}
}
private static TransportFactory getTransportFactoryByName(String transportName) {
synchronized (transportFactories) {
return transportFactories.get(transportName);
}
}
public static TransportFactory getTransportFactoryByURI(String uri) throws URISyntaxException {
return getTransportFactoryByURI(new URI(uri));
}
}
where the constructor of the above class is invoked as:
public static Context createContext() {
return new ContextImpl();
}
and the methods being called inside the constructor are:
private static void registerTransportFactory(TransportFactory transportFactory) {
if (transportFactory == null) {
throw new NullPointerException("transportFactory");
}
final String transportName = transportFactory.getName();
if (transportName == null) {
throw new NullPointerException("transportName");
}
synchronized (transportFactories) {
transportFactories.put(transportName, transportFactory);
}
}
public static void registerSerializerFactory(String serializerName, SerializerFactory serializerFactory) {
if (serializerName == null) {
throw new NullPointerException("serializerName");
}
if (serializerFactory == null) {
throw new NullPointerException("serializerFactory");
}
synchronized (serializerFactories) {
serializerFactories.put(serializerName, serializerFactory);
}
}
The error message returned is:
Error:(29, 16) java: constructor ContextImpl in class org.fiware.kiara.impl.ContextImpl cannot be applied to given types;
required: boolean
found: no arguments
reason: actual and formal argument lists differ in length
Why is this error returned since the implicit constructor is called?

call the same method name from instances different type

I have some libraries from external company, I want to use this API. I try to implement calling this API, my logic should call the same method name. I have duplicate codes, I want to avoid to do this. I'm beginner and subjects like interfaces, polymorphism are little bit difficult to me.
public void modPeople(Object person)
{
if (person instanceof com.company.persontype1)
{
com.company.persontype1 fireman = (com.company.persontype1) person;
String name = fireman.getName();
if (name!=null ) {
...
fireman.set_name();
fireman.save();
}
permissions = fireman.get_Permissions();
...
permissions = fixperm (permissions);
fireman.set_Permissions();
};
if (person instanceof com.company.persontype2)
{
com.company.persontype2 nurse = (com.company.persontype2) person;
String name = nurse.getName();
if (name!=null ) {
...
nurse.set_name();
nurse.save();
}
permissions = nurse.get_Permissions();
...
permissions = fixperm (permissions);
nurse.set_Permissions();
};
}
First of all I should mention that the methodology which you requested in your question is called "Duck Typing". Generally this technology is possible in Java (see below the example) but it's not widely used in Java. There could be performance hits etc. It would be much better to introduce a proper inheritance/interface level instead.
Also the provided example don't deal with exceptions properly etc. It's just a quick and quite dirty "demostration of the technology". Feel free to adapt it for your needs.
It's Java7 (for multi-catch clauses, you may refactor this with ease).
ISomeIterface.java (it contains all common methods implemented by classes which are used in your "bad code"):
package org.test;
public interface ISomeInterface {
public String getName();
public void setName(String _name);
public void save();
// specify other common methods
}
ReflectCaller.java:
package org.test1;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import org.test.ISomeInterface;
public class ReflectCaller {
private final Method[] methods = ISomeInterface.class.getDeclaredMethods();
private final Map<Class<?>, Method[]> maps = new HashMap<Class<?>, Method[]>();
public void inspectClass(Class<?> _clazz) throws NoSuchMethodException, SecurityException {
final Method[] ms = new Method[methods.length];
int i = 0;
for(final Method m: methods) {
ms[i] = _clazz.getMethod(m.getName(), m.getParameterTypes());
i++;
}
maps.put(_clazz, ms);
}
public ISomeInterface wrapper(Object _obj) {
final Method[] ms = maps.get(_obj.getClass());
// To be replaced by guava's Preconditions.checkState()
if (ms == null)
throw new NoSuchElementException(String.format("Class %s is unregistered", _obj.getClass().getName()));
return new SomeInterfaceImpl(_obj, ms);
}
private static class SomeInterfaceImpl implements ISomeInterface {
private final Object obj;
private final Method[] ms;
public SomeInterfaceImpl(Object _obj, Method[] _ms) {
ms = _ms;
obj = _obj;
}
#Override
public String getName() {
try {
return (String) ms[0].invoke(obj);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
#Override
public void setName(String _name) {
try {
ms[1].invoke(obj, _name);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
#Override
public void save() {
try {
ms[2].invoke(obj);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
}
And test class ReflectTest.java. Notice that classes ReflectTest.Test and ReflectTest.Test2 has the same methods as ISomeInterface but don't implement it, they are completely independent from that interface and from each other.
package org.test2;
import org.test.ISomeInterface;
import org.test1.ReflectCaller;
public class ReflectTest {
private final ReflectCaller rc;
ReflectTest(Class ... _classes) throws NoSuchMethodException, SecurityException {
rc = new ReflectCaller();
for(final Class c: _classes)
rc.inspectClass(c);
}
void callSequence(Object _o) {
// this function demonstrates the sequence of method calls for an object which has "compliant" methods
ISomeInterface tw = rc.wrapper(_o);
tw.setName("boo");
System.out.printf("getName() = %s\n", tw.getName());
tw.save();
}
public static class Test {
public String getName() {
System.out.printf("%s.getName()\n", getClass().getName());
return "boo";
}
public void setName(String _name) {
System.out.printf("%s.setName(%s)\n", getClass().getName(), _name);
}
public void save() {
System.out.printf("%s.save()\n", getClass().getName());
}
}
public static class Test2 {
public String getName() {
System.out.printf("%s.getName()\n", getClass().getName());
return "boo2";
}
public void setName(String _name) {
System.out.printf("%s.setName(%s)\n", getClass().getName(), _name);
}
public void save() {
System.out.printf("%s.save()\n", getClass().getName());
}
}
public static void main(String[] args) {
ReflectTest rt;
try {
rt = new ReflectTest(Test.class, Test2.class);
} catch (NoSuchMethodException | SecurityException e) {
System.out.println(e);
System.exit(2);
return;
}
rt.callSequence(new Test());
rt.callSequence(new Test2());
}
}

Converting String to BigDecimal in GWT

In my GWT web application I have a textbox that holds a price.
How can one convert that String to a BigDecimal?
The easiest way is to create new text box widget that inherits ValueBox.
If you do it this way, you won't have to convert any string values manually. the ValueBox takes care of it all.
To get the BigDecimal value entered you can just go:
BigDecimal value = myTextBox.getValue();
Your BigDecimalBox.java:
public class BigDecimalBox extends ValueBox<BigDecimal> {
public BigDecimalBox() {
super(Document.get().createTextInputElement(), BigDecimalRenderer.instance(),
BigDecimalParser.instance());
}
}
Then your BigDecimalRenderer.java
public class BigDecimalRenderer extends AbstractRenderer<BigDecimal> {
private static BigDecimalRenderer INSTANCE;
public static Renderer<BigDecimal> instance() {
if (INSTANCE == null) {
INSTANCE = new BigDecimalRenderer();
}
return INSTANCE;
}
protected BigDecimalRenderer() {
}
public String render(BigDecimal object) {
if (null == object) {
return "";
}
return NumberFormat.getDecimalFormat().format(object);
}
}
And your BigDecimalParser.java
package com.google.gwt.text.client;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.text.shared.Parser;
import java.text.ParseException;
public class BigDecimalParser implements Parser<BigDecimal> {
private static BigDecimalParser INSTANCE;
public static Parser<BigDecimal> instance() {
if (INSTANCE == null) {
INSTANCE = new BigDecimalParser();
}
return INSTANCE;
}
protected BigDecimalParser() {
}
public BigDecimal parse(CharSequence object) throws ParseException {
if ("".equals(object.toString())) {
return null;
}
try {
return new BigDecimal(object.toString());
} catch (NumberFormatException e) {
throw new ParseException(e.getMessage(), 0);
}
}
}
Take a look at GWT-Math.

Categories