Serialize class which extends from HashMap Java - serialization

I don't know why an HashMap instance is serializable and an instance of a class which extends HashMap isn't serializable.
So, this code works:
HashMap<String,String> map=new HashMap<String,String>();
...
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(map);
objOut.close();
And this doesn't work:
public class MyMap extends HashMap<String,String>{}
...
MyMap map=new MyMap();
...
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(map);
objOut.close();

Solved. It was because an innerclass is serializable if has static modifier.

Related

velocity Implementing nested variable resolution

I want to generate controller layer code through velocity.
I generate a mapping method:
#ResponseBody
#PostMapping(value = "\\${peacetrue.${moduleName}.urls.add}")
public ${ModuleName}VO add(${ModuleName}Add params) {
logger.info("add record[{}]", params);
return ${moduleName}Service.add(params);
}
and then I got exception:
{DomainName}Controller.java.vm[line 18, column 39]
Was expecting one of:
"[" ...
"|" ...
"}" ...
"}" ...
Then I wrote a unit test:
#Test
public void translate() {
Velocity.init();
Map<String, Object> singletonMap = Collections.singletonMap("foo", "bar");
StringWriter stringWriter = new StringWriter();
Velocity.evaluate(new VelocityContext(singletonMap), stringWriter, "log", "$foo");
Assert.assertEquals("bar", stringWriter.toString());
stringWriter = new StringWriter();
Velocity.evaluate(new VelocityContext(singletonMap), stringWriter, "log", "\\${com.${foo}.name}");
Assert.assertEquals("${com.bar.name}", stringWriter.toString());
}
So what should i do?
You can use the #evaluate() directive like this (at least since v1.7):
#PostMapping("#evaluate("\$peacetrue.${moduleName}.urls.add")")
or (for prior versions) like this:
#PostMapping("#set($d='$')#evaluate("${d}peacetrue.${moduleName}.urls.add")")
Or if the EscapeTool is present in the context :
#PostMapping("#evaluate("${esc.dollar}peacetrue.${moduleName}.urls.add")")
Or if $peacetrue has a standard getter for the module (like .getFoo() or get('foo') as a Map) :
#PostMapping("$peacetrue.get($moduleName).urls.add")
it can be achieved with implementation 'org.apache.velocity.tools:velocity-tools-generic:3.0'
#Test
public void translate() {
VelocityEngine engine = new VelocityEngine();
engine.init();
Map<String, Object> singletonMap = Collections.singletonMap("foo", "bar");
StringWriter stringWriter = new StringWriter();
Velocity.evaluate(new VelocityContext(singletonMap), stringWriter, "log", "$foo");
Assert.assertEquals("bar", stringWriter.toString());
stringWriter = new StringWriter();
ToolManager manager = new ToolManager(true, true);
manager.setVelocityEngine(engine);
manager.configure(getEasyFactoryConfiguration());
ToolContext context = manager.createContext();
context.put("foo","bar");
Velocity.evaluate(context, stringWriter, "log", "${esc.d}{com.${foo}.name}");
Assert.assertEquals("${com.bar.name}", stringWriter.toString());
}
private EasyFactoryConfiguration getEasyFactoryConfiguration() {
EasyFactoryConfiguration config = new EasyFactoryConfiguration();
config.toolbox("application").tool(EscapeTool.class);
return config;
}

ArrayList [] set = new ArrayList[n];

What is this ??
ArrayList [] set = new ArrayList[n];
Implementation of arraylist is:
ArrayList Integer> al = new ArrayList Integer> ();
The first what you had defined
ArrayList [] set = new ArrayList[n];
This is an array of ArrayList. As we know that ArrayList is a class. So the first statement defines the array of ArrayList class.
The second example is
ArrayList Integer> al = new ArrayList Integer> ();
Here you are creating the object of ArrayList. So here you are creating an object of ArrayList class and will be adding values in it.
Below is an example that contains the use of both
public class Testing {
public static void main(String[] args) {
ArrayList[] set = new ArrayList[10];
ArrayList<String> list = new ArrayList<String>();
list.add("RHV");
list.add("Zen");
set[0] = list;
System.out.println(set[0]);
}
}

Distributed Cache in Pig UDF

Here is my code to Implement a UDF using Distributed Cache Using Pig.
public class Regex extends EvalFunc<Integer> {
static HashMap<String, String> map = new HashMap<String, String>();
public List<String> getCacheFiles() {
Path lookup_file = new Path(
"hdfs://localhost.localdomain:8020/user/cloudera/top");
List<String> list = new ArrayList<String>(1);
list.add(lookup_file + "#id_lookup");
return list;
}
public void VectorizeData() throws IOException {
FileReader fr = new FileReader("./id_lookup");
BufferedReader brd = new BufferedReader(fr);
String line;
while ((line = brd.readLine()) != null) {
String str[] = line.split("#");
map.put(str[0], str[1]);
}
fr.close();
}
#Override
public Integer exec(Tuple input) throws IOException {
// TODO Auto-generated method stub
return map.size();
}
}
Given Below is my Distributed Cache Input File (hdfs://localhost.localdomain:8020/user/cloudera/top)
Impetigo|Streptococcus pyogenes#Impetigo
indeterminate leprosy|Uncharacteristic leprosy#indeterminate leprosy
Output I get is
(0)
(0)
(0)
(0)
(0)
This means that my hashmap is empty.
How do i fill my hashmap using Distributed Cache?.
This was because VectorizeData() was not called in the executable.

castor marshaller suppress xsi

I read a post written by you about:
Marshaller marshaller = new Marshaller(w);
marshaller.setSuppressXSIType(true);
The problem is that I'm using that method but the result didn't changed.
My code is :
Marshaller m = new Marshaller();
m.setSuppressXSIType(true);
m.setSuppressNamespaces(true);
m.setSupressXMLDeclaration(true);
m.setMarshalExtendedType(false);
m.marshal(obj, file);
But what I obtained is still the xmlns:xsi=.. and the xsi:type=.. inside the xml tag.
Am I doing something wrong? I'm using castor xml 1.3.2.
if you create the marshaller with the string writer then the problem goes away.
StringWriter st = new StringWriter();
Marshaller marshaller = new Marshaller(st);
However, if you do the below it wont work.
Marshaller marshaller = new Marshaller();
marshaller.setValidation(true);
marshaller.setSuppressXSIType(true);
marshaller.setSuppressNamespaces(true);
marshaller.setSupressXMLDeclaration(true);
marshaller.setMapping(mapping);
marshaller.marshal(order,st);
That's what I've done as well and it worked for me. Here is the example, hope it helps:
MarshallerTest.java:
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.ValidationException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
public class MarshallerTest {
public static void main(String[] args) throws IOException, MappingException, MarshalException, ValidationException {
Mapping mapping = new Mapping();
mapping.loadMapping(MarshallerTest.class.getResource("/mapping.xml"));
StringWriter sw = new StringWriter();
Marshaller marshaller = new Marshaller(sw);
marshaller.setMapping(mapping);
marshaller.setSuppressNamespaces(true);
marshaller.setSuppressXSIType(true);
Person alex = new Person();
alex.setName("alex");
alex.setHobbies(Arrays.asList(new String[]{"fishing", "hiking"}));
marshaller.marshal(alex);
System.out.println(sw.toString());
}
}
Person.java:
public class Person {
private String name;
private List<String> hobbies;
// ...getters and setters
}
castor.properties
org.exolab.castor.indent=true
output:
<?xml version="1.0" encoding="UTF-8"?>
<person>
<hobbies>fishing</hobbies>
<hobbies>hiking</hobbies>
<name>alex</name>
</person>

Mock RouteData in RhinoMocks-MVC3

How to Mock RouteData in RhinoMock?
I have to Mock this.
(RouteData.Values["id"].Tostring()!=null)
Thank you
Given that RouteData is of type IRouteData you can mock it like this:
[Test]
public void TestMockingConcreteClass()
{
MockRepository mockRepository = new MockRepository();
RouteData routeData = mockRepository.Stub<RouteData>();
routeData.Stub(r => r.Values["id"]).Return("XXX");
mockRepository.ReplayAll();
Assert.That(routeData.Values["id"].ToString(), Is.EqualTo("XXX"));
}
After lots of googling I got this to :
Declared at the Class Level
HttpContextBase httpContextMock;
ControllerBase controllerMock;
In the Constructor
mockRepository = new MockRepository();
httpContextMock = mockRepository.DynamicMock<HttpContextBase>();
controllerMock = mockRepository.DynamicMock<ControllerBase>();
In The Test Method:
var routeData = new RouteData();
routeData.Values.Add("id", "Value");
absenceController.ControllerContext = new ControllerContext(httpContextMock, routeData, controllerMock);
``