SequenceInputStream is not taking enumeration argument - java

I am new to java technology.So i was going through SequenceInputStreamI tried below code,but i am not able to find the exact problem, kindly some one help
public class SequenceInput {
public static void main(String[] args) throws IOException {
Enumeration e=new MyEnum();
SequenceInputStream sin=new SequenceInputStream(e);
DataInputStream din=new DataInputStream(sin);
String s="";
while(null !=s) {
s=din.readLine();
if(null !=s) {
System.out.println(s);
}
}
din.close();
// new Vector().elements();
}
//Enumeration Class
public class MyEnum implements Enumeration{
InputStream in[];
int i=0;
public MyEnum(){
try {
in=new InputStream[] {new FileInputStream("src/a1.txt"),new FileInputStream("src/a2.txt"),new FileInputStream("src/a3.txt"),new FileInputStream("src/a4.txt")};
}
catch(Exception e) {
}
}
#Override
public boolean hasMoreElements() {
if(in.length<=4) {
return true;
}
else
return false;
}
#Override
public Object nextElement() {
return in[i++];
}
}
}
In this line Enumeration e=new MyEnum(); it is showing
- No enclosing instance of type SequenceInput is accessible. Must qualify the
allocation with an enclosing instance of type SequenceInput (e.g. x.new A() where x is an
instance of SequenceInput).
I am not getting the exact problem.
Else i have used new Vector().add() and it was working fine with sequenceInputStream. Wanted to know about above code..Where am i making mistake.
Thanks in advance.

To access your class without needed an enclosing instance, you have to make it static
public static class MyEnum implements Enumeration {
...
}

Check this
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Enumeration;
public class SequenceInput {
public static void main(String[] args) throws IOException {
Enumeration e=new MyEnum();
SequenceInputStream sin=new SequenceInputStream(e);
DataInputStream din=new DataInputStream(sin);
String s="";
while(null !=s) {
s=din.readLine();
if(null !=s) {
System.out.println(s);
}
}
din.close();
// new Vector().elements();
}
//Enumeration Class
public static class MyEnum implements Enumeration{
InputStream in[];
int i=0;
public MyEnum(){
try {
in=new InputStream[] {new FileInputStream("src/a1.txt"),new FileInputStream("src/a2.txt"),new FileInputStream("src/a3.txt"),new FileInputStream("src/a4.txt")};
}
catch(Exception e) {
}
}
#Override
public boolean hasMoreElements() {
if(in.length<=4) {
return true;
}
else
return false;
}
#Override
public Object nextElement() {
return in[i++];
}
}
}

Related

How to retrieve the serialized object from Hazelcast's Imap?

The below code is for putting a kryo serialised object into an Hazelcast's Imap instance followed by retrieving. On retrieving the object it throws an error named:
com.hazelcast.nio.serialization.HazelcastSerializationException: com.esotericsoftware.kryo.KryoException: java.io.EOFException: Unexpected end of ZLIB input stream
My code is given below.
package hazelcast2;
import java.util.Scanner;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.config.Config;
import com.hazelcast.config.InMemoryFormat;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.SerializerConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.core.ISet;
public class zlibtry {
public static Config config;
public static ClientConfig cfg;
public static HazelcastInstance hz;
public static IMap<String,MyDataObject> mapItemCount;
public static void main(String[] args) throws Exception{
// Scanner obj = new Scanner(System.in);
config= new Config();
config.setProperty("hazelcast.elastic.memory.enabled" , "true");
config.setProperty("hazelcast.elastic.memory.total.size", "60G");
config.setProperty("hazelcast.elastic.memory.chunk.size","2");
MapConfig mapConfig = new MapConfig();
mapConfig.setInMemoryFormat( InMemoryFormat.OBJECT );
//config.getNetworkConfig().setPort(5701);
//config.getNetworkConfig().setPublicAddress("127.0.0.1");
config.setProperty("address","127.0.0.1");
SerializerConfig productSerializer = new SerializerConfig()
.setTypeClass(MyDataObject.class).setImplementation(new ProductKryoSerializer(true));
config.getSerializationConfig().addSerializerConfig(productSerializer);
hz=Hazelcast.newHazelcastInstance(config);
mapItemCount=hz.getMap("objectMap");
MyDataObject obj = new MyDataObject();
ISet<Integer> iset = hz.getSet("zlibset2");
iset.add(1);
obj.setMyList(iset);
mapItemCount.put("1", obj);
System.out.println(mapItemCount.get("1").getMyList().toString());
}
}
The below code is for productKyroSerializer:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.StreamSerializer;
public class ProductKryoSerializer implements StreamSerializer {
private final boolean compress;
private static final ThreadLocal<Kryo> kryoThreadLocal
= new ThreadLocal<Kryo>() {
#Override
protected Kryo initialValue() {
Kryo kryo = new Kryo();
kryo.register(MyDataObject.class);
return kryo;
}
};
public ProductKryoSerializer(boolean compress) {
this.compress = compress;
}
public int getTypeId() {
return 2;
}
public void write(ObjectDataOutput objectDataOutput, MyDataObject product)
throws IOException {
Kryo kryo = kryoThreadLocal.get();
if (compress) {
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(16384);
DeflaterOutputStream deflaterOutputStream =
new DeflaterOutputStream(byteArrayOutputStream);
Output output = new Output(deflaterOutputStream);
kryo.writeObject(output, product);
output.close();
byte[] bytes = byteArrayOutputStream.toByteArray();
objectDataOutput.write(bytes);
} else {
Output output = new Output((OutputStream) objectDataOutput);
kryo.writeObject(output, product);
output.flush();
}
}
public MyDataObject read(ObjectDataInput objectDataInput)
throws IOException {
InputStream in = (InputStream) objectDataInput;
if (compress) {
in = new InflaterInputStream(in);
}
Input input = new Input(in);
Kryo kryo = kryoThreadLocal.get();
return kryo.readObject(input, MyDataObject.class);
}
public void destroy() {
}
// #Override
// public Object read(ObjectDataInput arg0) throws IOException {
// // TODO Auto-generated method stub
// return null;
// }
public void write(ObjectDataOutput arg0, Object arg1) throws IOException {
// TODO Auto-generated method stub
}
}
And moreover, I think there should be some proper method to retrieve the object after deserialisation.
You can see the "objectMap" hazelcast's IMap instance and I have updated some code in hazelcast.xml:
<map name="objectMap">
<in-memory-format>OBJECT</in-memory-format>
</map>
<map name="cachedMap">
<in-memory-format>CACHED</in-memory-format>
</map>
<map name="binaryMap">
<in-memory-format>BINARY</in-memory-format>
</map>
and the code for myDataObject is
import com.hazelcast.core.IList;
import com.hazelcast.core.ISet;
public class MyDataObject {
ISet<Integer> myList;
public ISet<Integer> getMyList() {
return myList;
}
public void setMyList(ISet<Integer> myList) {
this.myList = myList;
}
}
ISet is not serializable and cannot be serialized directly as a field inside of a class. See the following snippet for a possible solution.
public class MyDataObject
implements KryoSerializable, HazelcastInstanceAware {
private ISet<Integer> myList;
private String myListName;
public ISet<Integer> getMyList() {
return myList;
}
public void setMyList(ISet<Integer> myList) {
this.myList = myList;
this.myListName = myList.getName();
}
public void write (Kryo kryo, Output output) {
output.writeString(myListName);
}
public void read (Kryo kryo, Input input) {
this.myListName = input.readString();
}
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
this.myList = hazelcastInstance.getSet(myListName);
}
}
I guess that should work (at least kind of ;-)) just wrote it in the browser.

A class that extends HashMap when adding new variable can't be write to json

ResultContentExt extends HashMap and has it's own variable testInt.
In main method, I write the ResultContentExt been to json.but can't write the variable
testInt to json.
I also rewrite writeObject method in ResultContentExt, which seems not be called...
package test.open.serial;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class ResultContentExt extends HashMap<String, Object> implements
Serializable {
private static final long serialVersionUID = 628377769976336650L;
public ResultContentExt() {
}
private int testInt;
public int getTestInt() {
return testInt;
}
public void setTestInt(int testInt) {
this.testInt = testInt;
}
public List<String> getRef_hot_status() {
return (List<String>) this.get("ref_hot_status");
}
#Override
public String toString() {
return "ResultContentExt [ref_hot_status=" + this.getRef_hot_status()
+ "]" + "ref_new_status=" + this.getRef_new_status()
+ this.getTestInt();
}
public void setRef_hot_status(List<String> ref_hot_status) {
if (ref_hot_status != null) {
this.put("ref_hot_status", ref_hot_status);
} else {
this.put("ref_hot_status", new LinkedList<Map<String, Integer>>());
}
}
public void setRef_new_status(List ref_new_status) {
if (ref_new_status != null) {
this.put("ref_new_status", ref_new_status);
} else {
this.put("ref_new_status", new LinkedList<Map<String, Integer>>());
}
}
public List<String> getRef_new_status() {
return (List<String>) this.get("ref_new_status");
}
public void writeObject(ObjectOutputStream s) throws IOException {
System.out.println("ResultContentExt begin...");
s.defaultWriteObject();
System.out.println("ResultContentExt end");
}
}
the result is {"ref_new_status":["bbbb","cccc"],"ref_hot_status":["aaa","侠盗飞"]}
why the testInt can't be write to json.
the main class
public class SearilazizeTest implements Serializable{
private static final long serialVersionUID = 5767426158258564918L;
private static Logger logger = Logger.getLogger(SearilazizeTest.class);
public static void main(String[] args){
try {
jsonObjectTrans();
} catch (Exception e) {
logger.error("", e);
}
}
public static void jsonObjectTrans(){
ResultContentExt rce = new ResultContentExt();
List<String> refHostStatus = new ArrayList<String>();
refHostStatus.add("aaa");
refHostStatus.add("侠盗飞");
rce.setRef_hot_status(refHostStatus);
List<String> refNewStatus = new ArrayList<String>();
refNewStatus.add("bbbb");
refNewStatus.add("cccc");
rce.setRef_new_status(refNewStatus);
rce.setTestInt(22);
System.out.println(rce.getTestInt());
JSONObject jsonArray = JSONObject.fromObject(rce);
System.out.println(jsonArray);
ResultContentExt packageVersionMaps = new ResultContentExt();
try {
JSONObject jsonObject = JSONObject.fromObject(jsonArray);
packageVersionMaps = (ResultContentExt) JSONObject.toBean(jsonObject,ResultContentExt.class);
} catch (Exception e) {
logger.error("", e);
}
System.out.println(packageVersionMaps);
}}

How to generically implement calling methods stored in a HashMap?

I want to route certain chars to methods, so that when the char is typed in the command-line the method is then executed.
Based on the answer How to call a method stored in a HashMap, I'm mapping these chars to methods by using the "Command" design-pattern.
However I want to generically implement this, so it seems that I need to implement reflection in order to use the Method class as a parameter. My attempt is getting a NullPointerException on the field private Method method in my anonymous class...
Here is my code:
import java.lang.reflect.Method;
public interface InvokesMethod {
public void invokeMethod() throws Exception;
public void setMethod(Method method);
} // end of interface
import java.util.HashMap;
import java.lang.reflect.Method;
public class Terminal {
public HashMap<Character, InvokesMethod> commands;
public Terminal() {
this.commands = new HashMap<Character, InvokesMethod>();
try {
this.setCommand('p',
this.getClass().getDeclaredMethod("printHelloWorld"));
} catch (Exception e) {
e.printStackTrace();
}
}
private void printHelloWorld() {
System.out.println("Hello World!");
}
private void setCommand(char letter, Method method) {
this.commands.put(letter, new InvokesMethod() {
// NullPointerException starts here in the stack-trace:
private Method method;
#Override
public void invokeMethod() throws Exception {
method.invoke(null);
}
#Override
public void setMethod(Method method) {
this.method = method;
}
}).setMethod(method);
}
public void executeCommand(char letter) throws Exception {
this.commands.get(letter).invokeMethod();
}
} // end of class
public class Main() {
public static void main(String[] args) {
Terminal commandLine = new Terminal();
try {
commandLine.executeCommand('p');
} catch (Exception e) {
e.printStackTrace();
}
}
} // end of class
Regards to your code you didn't initiate method. Bear in mind that execute with null you must call public static method:
Your other issue , you didn't initiated interface properly. Here is working example:
InvokesMethodItf
public interface InvokesMethodItf {
public void invokeMethod() throws Exception;
public void setMethod(Method method);
}
InvokesMethod
public class InvokesMethod implements InvokesMethodItf{
private Method method;
#Override
public void invokeMethod() throws Exception {
method.invoke(null);
}
#Override
public void setMethod(Method method) {
this.method = method;
}
}
Terminal
public class Terminal {
public HashMap<Character, InvokesMethodItf> commands;
public Terminal() {
this.commands = new HashMap<Character, InvokesMethodItf>();
try {
this.setCommand('p',
this.getClass().getDeclaredMethod("printHelloWorld"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void printHelloWorld() {// method.invoke(null) looking for "static" method
System.out.println("Hello World!");
}
private void setCommand(char letter, Method method) {
InvokesMethodItf inv = new InvokesMethod();
inv.setMethod(method);
this.commands.put(letter, inv);
}
public void executeCommand(char letter) throws Exception {
this.commands.get(letter).invokeMethod();
}
}
Main
public class Main {
public static void main(String[] args) {
Terminal commandLine = new Terminal();
try {
commandLine.executeCommand('p');
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Hello World!
Thanks to #Maxim's original suggestion here, I have an alternate solution by setting the methods as Strings in the HashMap instead --
import java.util.HashMap;
import java.lang.reflect.Method;
public class Terminal {
private HashMap<Character, String> commands;
public Terminal() {
this.commands = new HashMap<Character, String>();
this.commands.put('p', "printHelloWorld");
}
private void printHelloWorld() {
System.out.println("Hello World!");
}
public void executeCommand(char letter) throws Exception {
Method method = getClass().getDeclaredMethod(this.commands.get(letter));
method.invoke(this);
}
public class Main {
public static void main(String[] args) {
Terminal commandLine = new Terminal();
try {
commandLine.executeCommand('p');
} catch (Exception e) {
e.printStackTrace();
}
}
} // end of class
Output:
Hello World!
Now to figure out how to pass parameters to the reflected methods...

Concurrent-safe singleton with initialization parameter in java

I want to make a singleton class Phone, so that it can be initializable (with number) and also concurrent-safe. So, here is what I came with:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class PhoneTest {
public static void main(String... args){
System.out.println(Phone.getInstance().getNumber());
}
static final class Phone {
private final String number;
private final static Phone instance;
static {
instance = new Phone(PhonePropertyReader.readPhoneNumber());
}
private Phone(String number) {
this.number = number;
}
public static Phone getInstance() {
if (instance == null) throw
new IllegalStateException("instance was not initialized");
return instance;
}
public String getNumber() {
return number;
}
}
static final class PhonePropertyReader {
static String readPhoneNumber() {
File file = new File("phone.properties");
String phone = "";
System.out.println(file.getAbsolutePath());
if (!file.exists()) {
return phone = "555-0-101";
}
try {
BufferedReader r = new BufferedReader(new FileReader(file));
phone = r.readLine().split("=")[1].trim();
r.close();
} catch (IOException e) {
}
return phone;
}
}
}
also I have a file phone.properties containing
phone=12345
Is it a good solution? Is it concurrent safe?
I believe that Enum still the best way to implement thread-safe singletons in java.
I would discourage you to use singletons (Check this other question)
Otherwise, your code is thread-safe since the only affectation you do is in a static {} area which is, by definition, thread safe.
Btw, why not incorporate your readPhoneNumber() method directly in your phone class ?

Can I get all methods of a class?

Suppose that I have a .class file, can I get all the methods included in that class ?
Straight from the source: http://java.sun.com/developer/technicalArticles/ALT/Reflection/
Then I modified it to be self contained, not requiring anything from the command line. ;-)
import java.lang.reflect.*;
/**
Compile with this:
C:\Documents and Settings\glow\My Documents\j>javac DumpMethods.java
Run like this, and results follow
C:\Documents and Settings\glow\My Documents\j>java DumpMethods
public void DumpMethods.foo()
public int DumpMethods.bar()
public java.lang.String DumpMethods.baz()
public static void DumpMethods.main(java.lang.String[])
*/
public class DumpMethods {
public void foo() { }
public int bar() { return 12; }
public String baz() { return ""; }
public static void main(String args[]) {
try {
Class thisClass = DumpMethods.class;
Method[] methods = thisClass.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
System.out.println(methods[i].toString());
}
} catch (Throwable e) {
System.err.println(e);
}
}
}
To know about all methods use this statement in console:
javap -cp jar-file.jar packagename.classname
or
javap class-file.class packagename.classname
or for example:
javap java.lang.StringBuffer
You can use the Reflection API
package tPoint;
import java.io.File;
import java.lang.reflect.Method;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class ReadClasses {
public static void main(String[] args) {
try {
Class c = Class.forName("tPoint" + ".Sample");
Object obj = c.newInstance();
Document doc =
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new File("src/datasource.xml"));
Method[] m = c.getDeclaredMethods();
for (Method e : m) {
String mName = e.getName();
if (mName.startsWith("set")) {
System.out.println(mName);
e.invoke(obj, new
String(doc.getElementsByTagName(mName).item(0).getTextContent()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Categories

Resources