how iterate over Object arrays with java reflection - java

I want to iterate over Object[] within a class with Reflection
this is my class :
public class Lab {
public Browser[] browser;
}
class Browser {
String url;
}
I want to reach browser[] from the Lab class at index 3 and check value of url

You can achieve that with something like the following snippet:
public boolean urlEquals(Lab lab, String other){
try{
Field browsersField = Lab.class.getDeclaredField("browsers");
Object browsers = browsersField.get(lab);
Object browser = Array.get(browsers, 3);
Field urlField = Browser.class.getDeclaredField("url");
urlField.setAccessible(true);
Object url = urlField.get(browser);
return url.equals(other);
} catch(Exception e){ // probably catch specific exceptions than all
throw new IllegalStateException(e);
}
}

Maybe in this way:
public class Lab
{
public Browser[] browser;
public static void main(String[] args)
{
Lab myLabInstance = new Lab();
myLabInstance.browser = new Browser[] { new Browser(), new Browser(), new Browser(), new Browser(), };
for (Field field : Lab.class.getDeclaredFields())
{
System.out.println(field.getName());
if (field.getName().equalsIgnoreCase("browser"))
{
field.setAccessible(true);
Browser[] browsers = (Browser[]) field.get(myLabInstance);
System.out.println(browsers[3].url.equals("myvalue"));
}
}}}
class Browser
{
public String url = "hallo";
}

Related

add array into array

I have data of tracks & tracklinks like folowing:
trackname - abc
links - www.abc.com
www.abc1.com
www.abc2.com
trackname - xyz
links - www.xyz.com
www.xyz1.com
www.xyz2.com
I want to make array with in array in Java. so final array would be:
trackdata = {
[0] {
[trackname] = 'abc',
[tracklinks] = {
[0] = "www.abc.com";
[1] = "www.abc1.com";
[2] = "www.abc2.com";
}
},
[1] {
[trackname] = 'xyz',
[tracklinks] = {
[0] = "www.xyz.com";
[1] = "www.xyz1.com";
[2] = "www.xyz2.com";
}
}
I have tried to make this using ArrayList, Map but not succeed.
Map<String,String> map = new HashMap<>();
map.put("trackname", "abc");
ArrayList<String> myLinks= new ArrayList<>();
myLinks.add("www.abc.com");
myLinks.add("www.abc1.com");
myLinks.add("www.abc2.com");
map.put("tracklinks", myLinks);
please help me here.
Consider using a multimap, a map whose values are list objects:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Starter {
public static void main(String[] args) {
Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> myLinks= new ArrayList<>();
myLinks.add("www.abc.com");
myLinks.add("www.abc1.com");
myLinks.add("www.abc2.com");
map.put("abc", myLinks);
System.out.println(map); // {abc=[www.abc.com, www.abc1.com, www.abc2.com]}
}
}
You should create a class and then access the properties like you want.
class TrackData {
private String trackme;
private List<String> trackLink;
public String getTrackme() {return trackme;}
public void setTrackme(String trackme) {this.trackme = trackme;}
public List<String> getTrackLink() {return trackLink;}
public void setTrackLink(List<String> trackLink) {this.trackLink = trackLink;}
}
To access it:
#Test
void arrayInArray_Test1() {
List<TrackData> trackData = new ArrayList<>();
trackData.add(new TrackData(){{
setTrackme("abc");
setTrackLink(new ArrayList<String>(){{
add("www.abc.com");
add("www.abc1.com");
add("www.abc2.com");
}});
}});
trackData.add(new TrackData(){{
setTrackme("xyz");
setTrackLink(new ArrayList<String>(){{
add("www.xyz.com");
add("www.xyz1.com");
add("www.xyz2.com");
}});
}});
System.out.println(trackData);
}
If you are using a newer Java version, you can create a record instead of a class.
You can achieve as follows
public class TrackTest {
public static void main(String[] args) {
List<Tracks> trackList = new ArrayList<>();
Tracks track1 = new Tracks("abc");
track1.getTrackLinks().add("www.abc.com");
track1.getTrackLinks().add("www.abc1.com");
track1.getTrackLinks().add("www.abc2.com");
Tracks track2 = new Tracks("xyz");
track2.getTrackLinks().add("www.xyz.com");
track2.getTrackLinks().add("www.xyz1.com");
track2.getTrackLinks().add("www.xyz2.com");
trackList.add(track1);
trackList.add(track2);
System.out.println(trackList);
}
static class Tracks{
private String trackName;
private List<String> trackLinks;
public Tracks(String trackName) {
this.trackName = trackName;
this.trackLinks = new ArrayList<>();
}
public Tracks(String trackName, List<String> trackLinks) {
this.trackName = trackName;
this.trackLinks = trackLinks;
}
public String getTrackName() {
return trackName;
}
public List<String> getTrackLinks() {
return trackLinks;
}
#Override
public String toString() {
return "Tracks [trackName=" + trackName + ", trackLinks=" + trackLinks + "]";
}
}
}
Let me know, if you want other approach.
how are u?
Why u dont do this.
Create class named URL, for example.
public class Url(){
//atributes
String domain;
String url;
//Contructor
public class URL(String domain, String url){
this.domain = domain;
this.url = url;
}
}
In ur main.class, u can create one Arraylist to saves ur instaces of URL.
public static void newURL(){
String domain, url;
Scanner keyboard = new Scanner(System.in);
//ask domain, i will use an example.
System.out.println("What is domain of URL?");
domain = keyboard.nextLine();
System.out.println("What is url?");
url = keyboard.nextLine;
//now, u have atributes of new url
URL url = new URL(domain,url);
}
What its ur objective? It's important question.
If is for simple control in a little program, u can do this

Dynamically load from a properties file in java

I have a config.properties files with names like this:
names=john,jane
Then I have a class that access that file and loads the names. And I have another class that get a name from somewhere and if that name is in the config.properties prints "SUCCESS". The problem is that if I add names to the config.properties, I have to run again the program, it doesn´t load dynamically. What is the alternative to this?
public class PropertiesFile {
private static final char OPENFILES_CONFIG_DELIMITER = ',';
private static final String OPENFILES_CONFIG = "config.properties";
private static org.apache.commons.configuration2.Configuration config;
static {
try {
Parameters params = new Parameters();
FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.properties()
.setFileName(OPENFILES_CONFIG)
.setListDelimiterHandler(new DefaultListDelimiterHandler(OPENFILES_CONFIG_DELIMITER)));
config = builder.getConfiguration(); }
catch (ConfigurationException cE) {
//...
}
}
public static Set<String> load() {
String[] thingsToExecute = config.getStringArray("names");
return new HashSet<String>(Arrays.asList(thingsToExecute));
}
}
public class OpenFiles {
private static Set<String> toExecute;
public static void main(String[] args) {
updateToExecute();
connect();
}
private static void connect() {
//code that obatins JSONObject
if (obj4.has("name")) {
String personName = obj4.get("name").toString();
updateToExecute();
if (toExecute.contains(personName)) {
System.out.println("SUCCESS");
} else {
System.out.println(personName+"is not in the list");
}
}
}
private static void updateToExecute() {
toExecute = PropertiesFile.load();
}
}

On parsing gson.toJson(obj) giving null

wWhen I am passing object of local-inner-class ShipAddress to toJson() method of Gson class this is returning null on parsing it.
public class CrusialDateRest {
public String getShippingAddressesDetails() {
Gson gson = new GsonBuilder().create();
try {
Collection<ImplAddress> savedAddressBeans = new ArrayList<ImplAddress>();
Collection<CtFlexField> countryFields = new ArrayList<CtFlexField>();
Collection<CtFlexField> debitorFields = new ArrayList<CtFlexField>();
class ShipAddress{
Collection<ImplAddress> savedAddressBean = new ArrayList<ImplAddress>();
Collection<CtFlexField> countryField = new ArrayList<CtFlexField>();
Collection<CtFlexField> debitorField = new ArrayList<CtFlexField>();
ShipAddress( Collection<ImplAddress> savedAddressBeans, Collection<CtFlexField> countryFields,Collection<CtFlexField> debitorFields){
savedAddressBean=savedAddressBeans;
countryField=countryFields;
debitorField=debitorFields;
}
}
String addrId= XmlParser.getNodeValue(address, Statics.BUYFLOW_NAMESPACE, "AddressId");
String addrStreet1 = XmlParser.getNodeValue(address, Statics.BUYFLOW_NAMESPACE, "AddrStreet1");
String addrStreet2 = XmlParser.getNodeValue(address, Statics.BUYFLOW_NAMESPACE, "AddrStreet2");
String addrStreet3 = XmlParser.getNodeValue(address, Statics.BUYFLOW_NAMESPACE, "AddrStreet3");
ImplAddress impladdress = new ImplAddress();
impladdress.setAddressId(addrId);
impladdress.setAddrStreet1(addrStreet1);
impladdress.setAddrStreet2(addrStreet2);
impladdress.setAddrStreet3(addrStreet3);
savedAddressBeans.add(impladdress);
}
CtFlexField[] flexField = flexFields.getFlexField();
for (CtFlexField flex : flexField) {
if(flex.getBundle().equalsIgnoreCase("Countries")){
countryFields.add(flex);
}
else if(flex.getBundle().equalsIgnoreCase("CommonBundle")){
debitorFields.add(flex);
}
}
jsonResponse = gson.toJson(new ShipAddress(savedAddressBeans,countryFields,debitorFields));
OUT.debug("jsonResponse--"+jsonResponse);
} catch (Exception e) {
OUT.error("rest method getShippingAddresses error", e);
}
return jsonResponse;
}
}
Should I make inner class outside method?
Or is this a serialization issue?
It's most likely a visibility issue.
Either move ShipAddress into its own class file, or make it a public static inner class.
Note that public static classes cannot be declared inside of methods, you would have to move the class out of getShippingAddressDetails()method.

Creating stub for dependence class's under test

Good day, everyone! I have a little question about testing and generating a stub for dependence through reflection. So let's assume I have a class named UnderTest:
class UnderTest{
/*field*/
SomeLogic someLogic;
/*method, that i testing*/
List<MyObject> getCalculatedObjects(params) {/*logic,based on result getSomeStuff of someLogic*/ }
}
class SomeLogic {
List<String> getSomeStuff(String param) { /*Some complex and slow code, actually don't want test this code, and want to use some reflection invocation handler*/ }
}
For me it's important to not change legacy code, which doesn't design for testing. And i don't have any reason, except testing to make SomeLogic as an interface and so on.
I can't remember how to handle method invocation of someLogic using reflection. But google search isn't helping me.
Class MainAPI is... main api of my module. NetworkProvider long open stream operation, that's why i want to stub it, on my local files. But don't using directly reference on NetworkProvider. Again sorry for my English.
public class MainAPI {
private final XPath xPath;
private final ItemParser itemParser;
private final ListItemsParser listItemsParser;
private final DateParser dateParser;
private final HtmlCleanUp htmlCleanUp;
private final NetworkProvider networkProvider;
public MainAPI(XPath xPath, ItemParser itemParser, ListItemsParser listItemsParser, DateParser dateParser, HtmlCleanUp htmlCleanUp, NetworkProvider networkProvider) {
this.xPath = xPath;
this.itemParser = itemParser;
this.listItemsParser = listItemsParser;
this.dateParser = dateParser;
this.htmlCleanUp = htmlCleanUp;
this.networkProvider = networkProvider;
}
public MainAPI() throws XPathExpressionException, IOException {
dateParser = new DateParser();
xPath = XPathFactory.newInstance().newXPath();
networkProvider = new NetworkProvider();
listItemsParser = new ListItemsParser(xPath, dateParser, item -> true);
itemParser = new ItemParser(xPath, dateParser, networkProvider);
htmlCleanUp = new HtmlCleanUpByCleaner();
}
public List<Item> getItemsFromSessionParsing(SessionParsing sessionParsing) {
listItemsParser.setCondition(sessionParsing.getFilter());
List<Item> result = new ArrayList<>();
Document cleanDocument;
InputStream inputStream;
for (int currentPage = sessionParsing.getStartPage(); currentPage <= sessionParsing.getLastPage(); currentPage++) {
try {
inputStream = networkProvider.openStream(sessionParsing.getUrlAddressByPageNumber(currentPage));
} catch (MalformedURLException e) {
e.printStackTrace();
break;
}
cleanDocument = htmlCleanUp.getCleanDocument(inputStream);
List<Item> list = null;
try {
list = listItemsParser.getList(cleanDocument);
} catch (XPathExpressionException e) {
e.printStackTrace();
break;
}
for (Item item : list) {
inputStream = null;
try {
inputStream = networkProvider.openStream("http://www.avito.ru" + item.getUrl());
} catch (MalformedURLException e) {
e.printStackTrace();
break;
}
cleanDocument = htmlCleanUp.getCleanDocument(inputStream);
try {
item.setDescription(itemParser.getDescription(cleanDocument));
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
result.addAll(list);
}
return result;
}
}
public class NetworkProvider {
private final ListCycleWrapper<Proxy> proxyList;
public NetworkProvider(List<Proxy> proxyList) {
this.proxyList = new ListCycleWrapper<>(proxyList);
}
public NetworkProvider() throws XPathExpressionException, IOException {
this(new ProxySiteParser().getProxyList(new HtmlCleanUpByCleaner().getCleanDocument(new URL("http://www.google-proxy.net").openStream())));
}
public int getSizeOfProxy() {
return proxyList.size();
}
public InputStream openStream(String urlAddress) throws MalformedURLException {
URL url = new URL(urlAddress);
while (!proxyList.isEmpty()) {
URLConnection con = null;
try {
con = url.openConnection(proxyList.getNext());
con.setConnectTimeout(6000);
con.setReadTimeout(6000);
return con.getInputStream();
} catch (IOException e) {
proxyList.remove();
}
}
return null;
}
}
All the dependencies of your class to tests are injectable using its constructor, so there shouldn't be any problem to stub these dependencies and injecting the stubs. You don't even need reflection. For example, using Mockito:
NetworkProvider stubbedNetworkProvider = mock(NetworkProvider.class);
MainAPI mainApi = new MainAPI(..., stubbedNetworkProvider);
You can also write a stub by yourself if you want:
NetworkProvider stubbedNetworkProvider = new NetworkProvider(Collections.emptyList()) {
// TODO override the methods to stub
};
MainAPI mainApi = new MainAPI(..., stubbedNetworkProvider);

equivalent to python's shelve module in Java

Is there any module in Java equivalent to python's shelve module? I need this to achieve dictionary like taxonomic data access. Dictionary-like taxonomic data access is a powerful way to save Python objects in a persistently easy access database format. I need something for the same purpose but in Java.
I also needed this, so I wrote one. A bit late, but maybe it'll help.
It doesn't implement the close() method, but just use sync() since it only hold the file open when actually writing it.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
public class Shelf extends HashMap<String, Object> {
private static final long serialVersionUID = 7127639025670585367L;
private final File file;
public static Shelf open(File file) {
Shelf shelf = null;
try {
if (file.exists()) {
final FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
shelf = (Shelf) ois.readObject();
ois.close();
fis.close();
} else {
shelf = new Shelf(file);
shelf.sync();
}
} catch (Exception e) {
// TODO: handle errors
}
return shelf;
}
// Shelf objects can only be created or opened by the Shelf.open method
private Shelf(File file) {
this.file = file;
sync();
}
public void sync() {
try {
final FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this);
oos.close();
fos.close();
} catch (Exception e) {
// TODO: handle errors
}
}
// Simple Test Case
public static void main(String[] args) {
Shelf shelf = Shelf.open(new File("test.obj"));
if (shelf.containsKey("test")) {
System.out.println(shelf.get("test"));
} else {
System.out.println("Creating test string. Run the program again.");
shelf.put("test", "Hello Shelf!");
shelf.sync();
}
}
}
You could use a serialisation library like Jackson which serialises POJOs to JSON.
An example from the tutorial:
Jackson's org.codehaus.jackson.map.ObjectMapper "just works" for
mapping JSON data into plain old Java objects ("POJOs"). For example,
given JSON data
{
"name" : { "first" : "Joe", "last" : "Sixpack" },
"gender" : "MALE",
"verified" : false,
"userImage" : "Rm9vYmFyIQ=="
}
It takes two lines of Java to turn it into a User instance:
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);
Where the User class looks something like this (from an entry on Tatu's blog):
public class User {
public enum Gender { MALE, FEMALE };
public static class Name {
private String _first, _last;
public String getFirst() { return _first; }
public String getLast() { return _last; }
public void setFirst(String s) { _first = s; }
public void setLast(String s) { _last = s; }
}
private Gender _gender;
private Name _name;
private boolean _isVerified;
private byte[] _userImage;
public Name getName() { return _name; }
public boolean isVerified() { return _isVerified; }
public Gender getGender() { return _gender; }
public byte[] getUserImage() { return _userImage; }
public void setName(Name n) { _name = n; }
public void setVerified(boolean b) { _isVerified = b; }
public void setGender(Gender g) { _gender = g; }
public void setUserImage(byte[] b) { _userImage = b; }
}

Categories