I need help with this piece of code. I need to write a test just like testfindOverviewByStatus() example in the code below but I need to write it for 2 pieces of data and 0 pieces. testfindOverviewByStatus() is a test for if there is only one piece of data in the list. I tried writing the two different tests I need at the end of the code but was unsuccessful in doing so. Can anyone help me?
package com.primatics.greensight.dashboard.controller;
import static org.junit.Assert.assertEquals;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.primatics.greensight.dashboard.UnitTest;
import com.primatics.greensight.dashboard.model.Overview;
import com.primatics.greensight.dashboard.repositories.ScenarioDashboardRepository;
import com.primatics.greensight.dashboard.repositories.impl.ScenarioDashboardRepositoryImpl;
import com.primatics.greensight.dashboard.services.ScenarioDashboardService;
import com.primatics.greensight.dashboard.services.impl.ScenarioDashboardServiceImpl;
#RunWith(SpringRunner.class)
#SpringBootTest(classes = ScenarioDashboardServiceImpl.class)
#AutoConfigureMockMvc
#EnableAutoConfiguration
#Category(UnitTest.class)
public class ScenarioDashboardServiceImplUnitTest {
#Configuration
static class AccountServiceTestContextConfiguration {
#Bean
public ScenarioDashboardRepositoryImpl scenarioDashboardService() {
return new ScenarioDashboardRepositoryImpl();
}
#Bean
public ScenarioDashboardRepository scenarioDashboardtRepository() {
return Mockito.mock(ScenarioDashboardRepositoryImpl.class);
}
}
#Mock
private ScenarioDashboardService scenarioDashboardService;
#Before
public void doSetUp() {
List<Overview> scenarioListTest = new ArrayList<Overview>();
String name = "first_scenario-test";
ISO8601DateFormat df = new ISO8601DateFormat();
Date estimationDate = null;
try {
estimationDate = df.parse("2017-01-28T22:25:51Z");
} catch (ParseException e) {
e.printStackTrace();
}
Date creationDate = null;
try {
creationDate = df.parse("2017-02-28T22:25:51Z");
} catch (ParseException e) {
e.printStackTrace();
}
Double balance = 131750000.0;
Double individualReviewImpairment = 1000.00;
Map<String, Double> baseline = new HashMap<String, Double>();
baseline.put("complete", 1000.0);
Map<String, Double> macroAdjustment = new HashMap<String, Double>();
macroAdjustment.put("complete", 2000.0);
Map<String, Double> qualitativeAdjustment = new HashMap<String, Double>();
qualitativeAdjustment.put("complete", 3000.0);
Date positionDate = null;
try {
positionDate = df.parse("2017-01-28T22:25:51Z");
} catch (ParseException e) {
e.printStackTrace();
}
Date lossHistoryDate = null;
try {
lossHistoryDate = df.parse("2017-01-28T22:25:51Z");
} catch (ParseException e) {
e.printStackTrace();
}
String status = "active";
Map<String, Integer> period = new HashMap<String, Integer>();
period.put("Q1", 2017);
boolean publish = true;
Overview ac = new Overview(4, name, estimationDate, creationDate, balance, individualReviewImpairment, baseline,
macroAdjustment, qualitativeAdjustment, positionDate, lossHistoryDate, status, period, publish);
scenarioListTest.add(ac);
Mockito.when(scenarioDashboardService.getOverviewByStatus("active")).thenReturn(scenarioListTest);
}
#Before
public void getTwoOverviews() {
List<Overview> scenarioListTest2 = new ArrayList<Overview>();
String name = "first_scenario-test";
ISO8601DateFormat df = new ISO8601DateFormat();
Date estimationDate = null;
try {
estimationDate = df.parse("2017-01-28T22:25:51Z");
} catch (ParseException e) {
e.printStackTrace();
}
Date creationDate = null;
try {
creationDate = df.parse("2017-02-28T22:25:51Z");
} catch (ParseException e) {
e.printStackTrace();
}
Double balance = 131750000.0;
Double individualReviewImpairment = 1000.00;
Map<String, Double> baseline = new HashMap<String, Double>();
baseline.put("complete", 1000.0);
Map<String, Double> macroAdjustment = new HashMap<String, Double>();
macroAdjustment.put("complete", 2000.0);
Map<String, Double> qualitativeAdjustment = new HashMap<String, Double>();
qualitativeAdjustment.put("complete", 3000.0);
Date positionDate = null;
try {
positionDate = df.parse("2017-01-28T22:25:51Z");
} catch (ParseException e) {
e.printStackTrace();
}
Date lossHistoryDate = null;
try {
lossHistoryDate = df.parse("2017-01-28T22:25:51Z");
} catch (ParseException e) {
e.printStackTrace();
}
String status = "active";
Map<String, Integer> period = new HashMap<String, Integer>();
period.put("Q1", 2017);
boolean publish = true;
Overview ac = new Overview(4, name, estimationDate, creationDate, balance, individualReviewImpairment, baseline,
macroAdjustment, qualitativeAdjustment, positionDate, lossHistoryDate, status, period, publish);
scenarioListTest2.add(ac);
Mockito.when(scenarioDashboardService.getOverviewByStatus("active")).thenReturn(scenarioListTest2);
}
#Test
public void testfindOverviewByStatus() {
List<Overview> scenarioListTest = scenarioDashboardService.getOverviewByStatus("active");
assertEquals(1, scenarioListTest.size());
String scenarioName = scenarioListTest.get(0).getScenarioName();
assertEquals("first_scenario-test", scenarioName);
}
#Test
public void testfindOverviewByStatusTwo() {
List<Overview> scenarioList = scenarioDashboardService.getOverviewByStatus("active");
assertEquals(2, scenarioList.size());
String scenarioName = scenarioList.get(0).getScenarioName();
String scenarioName2 = scenarioList.get(1).getScenarioName();
assertEquals("first_scenario-test", scenarioName);
assertEquals("second_scenario-test", scenarioName2);
}
#Test
public void testfindOverviewByStatusNull() {
List<Overview> scenarioListNull = scenarioDashboardService.getOverviewByStatus("active");
assertEquals(0, scenarioListNull.size());
}
}
The problem is with the layout of your test. You have multiple #Before methods which all mock scenarioDashboardService.getOverviewByStatus("active")
The simplest way to get your tests working would be to remove the #Before annotations and instead invoke them methods in the #Test method.
So for example:
public void getTwoOverviews() {
//Contents of method
}
#Test
public void testfindOverviewByStatusTwo() {
//Setup
getTwoOverviews();
List<Overview> scenarioList = scenarioDashboardService.getOverviewByStatus("active");
assertEquals(2, scenarioList.size());
String scenarioName = scenarioList.get(0).getScenarioName();
String scenarioName2 = scenarioList.get(1).getScenarioName();
assertEquals("first_scenario-test", scenarioName);
assertEquals("second_scenario-test", scenarioName2);
}
As I mentioned this would be the simplest way but in the long run there most likely is a better way to layout your test class.
In situations where Mockito is already a dependency you might find it easier to use a custom argument matcher for this:
private class isListOfSize extends ArgumentMatcher<List<Overview>> {
int size;
isListOfSize(int size) {
this.size = size;
}
#Override
public boolean matches(Object list) {
return ((List) list).size() == size;
}
}
Usage:
assertThat(scenarioList, argThat(new isListOfSize(2)))
Related
I have a JSON file that looks like this:
{
"calendar": {
"dateToDayId": {
"2016-07-14": 290356,
"2016-08-26": 380486,
"2016-09-07": 417244,
"2016-08-15": 354271,
"2016-07-25": 311762
},
"dishIdToMealId": {
"1228578": 474602,
"1228585": 474602,
"1228586": 474602,
...... // more fields
}
I'm trying to read the <date, number> pairs under dateToDayId into a HashMap<Date, Long> in java. First I created a JsonInfo class which holds a Calendar class object. The Calendar class object in turns holds all the classes including DateToDayId, DishToMealId and so on. My DateToDayId class looks like this (I'm using Jackson to parse JSON file):
package jsonfields;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import deserializers.CustomDateDeserializer;
import java.util.Date;
import java.util.TreeMap;
public class DateToDayId {
#JsonDeserialize(using = CustomDateDeserializer.class)
private TreeMap <Date, Long> dateToDayMappings;
public TreeMap<Date, Long> getDateToDayMappings() {
return dateToDayMappings;
}
public void setDateToDayMappings(TreeMap<Date, Long> dateToDayMappings) {
this.dateToDayMappings = dateToDayMappings;
}
#Override
public String toString() {
return "DateToDayId{" +
"dateToDayMappings=" + dateToDayMappings +
'}';
}
}
My Main class looks like this:
import java.io.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("path\\to\\file\\test.json"));
JsonInfo jsonInfo = objectMapper.readValue(inputStreamReader, JsonInfo.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I run it, I get the following exception:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "2016-07-14" (class jsonfields.DateToDayId), not marked as ignorable (one known property: "dateToDayMappings"])
at [Source: (InputStreamReader); line: 1, column: 48] (through reference chain: JsonInfo["calendar"]->jsonfields.Calendar["dateToDayId"]->jsonfields.DateToDayId["2016-07-14"])
How can I fix this?
Your class mapping is wrong. You need to have map with variable name dateToDayId in Calendar. Below modified code should work for your need.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.TreeMap;
public class JSONMapTest {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("C:\\ws\\test\\test.json"));
JsonInfo jsonInfo = objectMapper.readValue(inputStreamReader, JsonInfo.class);
System.out.println(jsonInfo);
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class JsonInfo{
Calendar calendar;
public Calendar getCalendar() {
return calendar;
}
public void setCalendar(Calendar calendar) {
this.calendar = calendar;
}
}
class Calendar {
private TreeMap <Date, Long> dateToDayId;
public TreeMap<Date, Long> getDateToDayId() {
return dateToDayId;
}
public void setDateToDayId(TreeMap<Date, Long> dateToDayId) {
this.dateToDayId = dateToDayId;
}
#Override
public String toString() {
return "DateToDayId{" +
"dateToDayMappings=" + dateToDayId +
'}';
}
}
This is my Class to fetch the list of OHLC (open, high, low, close) also the volume and date. i have separated each one of the arraylist for each stocksymbol. i have used my local API to fetch the data. To perform all these calculation i have used ta4j library for JAVA.
package com.infodev.util;
import com.google.gson.Gson;
import com.infodev.Model.Data;
import com.infodev.Model.Find;
import com.infodev.Pojo.RequestForTechnicalCalculation;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.springframework.http.*;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
public class ApiTestData {
static Logger logger = Logger.getLogger(ApiTestData.class);
private static Data[] a;
public ApiTestData(RequestForTechnicalCalculation requestForTechnicalCalculation) throws Exception {
//setting request body
JSONObject jsonObject = new JSONObject();
jsonObject.put("sectorId", requestForTechnicalCalculation.getSectorId());
//setting request headers
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
//setting httpEntity as the request for server post request
HttpEntity<?> httpEntity = new HttpEntity<>(jsonObject.toString(), httpHeaders);
//installing restTemplate
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
ResponseEntity<Find> returnedObject = restTemplate.exchange("http://localhost:8081/pull365", HttpMethod.POST, httpEntity, Find.class);
a = returnedObject.getBody().getData();
logger.info("ApiData " + new Gson().toJson(a));
}
public int getDataSize() {
return a.length;
}
public BigDecimal[] getOpen(int index) {
return a[index].getOpen();
}
public BigDecimal[] getHigh(int index) {
return a[index].getHigh();
}
public BigDecimal[] getLow(int index) {
return a[index].getLow();
}
public BigDecimal[] getClose(int index) {
return a[index].getClose();
}
public BigDecimal[] getVolume(int index) {
return a[index].getVolume();
}
public String[] getDates(int index) {
return a[index].getDates();
}
public String getSymbols(int index) {
logger.info("stock name " +new Gson().toJson(a[index].getStockName()));
return a[index].getStockName();
}
}
This one is my calculation part to get the values of RSI. I have calculated another indicators also which is exactly correct according to my manual calculation of indicators but the problem seems to be in the calculation of RSI.
package com.infodev.Services.Indicators;
import com.infodev.Pojo.RequestForTechnicalCalculation;
import com.infodev.util.ApiTestData;
import eu.verdelhan.ta4j.Decimal;
import eu.verdelhan.ta4j.Tick;
import eu.verdelhan.ta4j.TimeSeries;
import eu.verdelhan.ta4j.indicators.candles.LowerShadowIndicator;
import eu.verdelhan.ta4j.indicators.helpers.*;
import eu.verdelhan.ta4j.indicators.oscillators.CMOIndicator;
import eu.verdelhan.ta4j.indicators.oscillators.PPOIndicator;
import eu.verdelhan.ta4j.indicators.oscillators.StochasticOscillatorDIndicator;
import eu.verdelhan.ta4j.indicators.oscillators.StochasticOscillatorKIndicator;
import eu.verdelhan.ta4j.indicators.simple.*;
import eu.verdelhan.ta4j.indicators.statistics.*;
import eu.verdelhan.ta4j.indicators.trackers.*;
import eu.verdelhan.ta4j.indicators.trackers.bollinger.BollingerBandWidthIndicator;
import eu.verdelhan.ta4j.indicators.trackers.bollinger.BollingerBandsLowerIndicator;
import eu.verdelhan.ta4j.indicators.trackers.bollinger.BollingerBandsMiddleIndicator;
import eu.verdelhan.ta4j.indicators.trackers.bollinger.BollingerBandsUpperIndicator;
import eu.verdelhan.ta4j.indicators.volatility.MassIndexIndicator;
import eu.verdelhan.ta4j.indicators.volume.ChaikinMoneyFlowIndicator;
import eu.verdelhan.ta4j.indicators.volume.OnBalanceVolumeIndicator;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.springframework.stereotype.Service;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
#Service
public class IndicatorServiceImpl implements IndicatorService {
static Logger logger = Logger.getLogger(IndicatorServiceImpl.class);
private static DecimalFormat df = new DecimalFormat("###,###.##");
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
List<Tick> ticks;
List<Tick> tickList;
TimeSeries series;
ClosePriceIndicator closePrice;
SMAIndicator shortSma;
SMAIndicator longSma;
EMAIndicator shortEma;
RSIIndicator rsi;
MACDIndicator macd;
BollingerBandsMiddleIndicator bbm;
BollingerBandsLowerIndicator bbl;
BollingerBandsUpperIndicator bbh;
BollingerBandWidthIndicator bbw;
ApiTestData apiData;
String symbol;
String[] date;
BigDecimal[] volume;
BigDecimal[] close;
BigDecimal[] low;
BigDecimal[] high;
BigDecimal[] open;
#Override
public List<Map<Object, Object>> getIndicators(RequestForTechnicalCalculation requestForTechnicalCalculation) {
System.out.println("service state");
List<Map<Object, Object>> finalList = new ArrayList<>();
try {
apiData = new ApiTestData(requestForTechnicalCalculation);
logger.info("----" + apiData.getDataSize());
for (int i = 0; i < apiData.getDataSize(); i++) {
logger.info("----" + i);
// getting the symbol from the api
symbol = apiData.getSymbols(i);
date = apiData.getDates(i);
volume = apiData.getVolume(i);
close = apiData.getClose(i);
low = apiData.getLow(i);
high = apiData.getHigh(i);
open = apiData.getOpen(i);
if (date.length == 0 || volume.length == 0 || close.length == 0 ||
low.length == 0 || high.length == 0 || open.length == 0) {
finalList.add(makeEmptyObject());
} else {
makeCalculation(i);
finalList.add(makeIndicatorObject());
}
}
//return finalList;
} catch (Exception e) {
e.printStackTrace();
finalList.add(makeEmptyObject());
}
return finalList;
}
private void makeCalculation(int ii) throws ParseException {
//instating tick to change the ohlc to Tick class array
ticks = new ArrayList<>();
logger.info("----" + ticks.size());
for (int i = 0; i < close.length; i++) {
this.ticks.add(new Tick(new DateTime(DATE_FORMAT.parse(date[i])), open[i].doubleValue(), high[i].doubleValue()
, low[i].doubleValue(), close[i].doubleValue(), volume[i].doubleValue()));
}
//converting the array to the list of tick
//generating the time Series of the sample data
series = new TimeSeries(apiData.getSymbols(ii), ticks);
if (series == null) {
throw new IllegalArgumentException("Series cannot be null");
} else {
//close price indicator
closePrice = new ClosePriceIndicator(this.series);
logger.info("ClosePrice: " + closePrice.getValue(series.getEnd()));
// Simple moving averages
shortSma = new SMAIndicator(closePrice, 5);
logger.info("shortSMA: " + shortSma.getValue(series.getEnd()));
longSma = new SMAIndicator(closePrice, 20);
logger.info("longSMA: " + longSma.getValue(series.getEnd()));
// Exponential moving averages
shortEma = new EMAIndicator(closePrice, 5);
logger.info("shortEMA: " + shortEma.getValue(series.getEnd()));
longEma = new EMAIndicator(closePrice, 20);
logger.info("longEMA: " + longEma.getValue(series.getEnd()));
rsi = new RSIIndicator(closePrice, 14);
series.getLastTick().addTrade(100, rsi.getValue(series.getEnd()).toDouble());
//newTick.addTrade(100, rsi.getValue(series.getEnd()).toDouble());
logger.info("RsiIndicator: " + rsi.getValue(series.getEnd()));
// Standard deviation
sd = new StandardDeviationIndicator(closePrice, 20);
logger.info("StandardDeviationIndicator: " + sd.getValue(series.getEnd()));
//macd indicator
macd = new MACDIndicator(closePrice, 12, 26);
logger.info("MACD indicator: " + macd.getValue(series.getEnd()));
//bollingerbandsmiddle indicator
bbm = new BollingerBandsMiddleIndicator(longSma);
logger.info("Bollinger Bands Middle Indicator :" + bbm.getValue(series.getEnd()));
bbl = new BollingerBandsLowerIndicator(bbm, sd);
logger.info("Bollinger bands lower indicator :" + bbl.getValue(series.getEnd()));
bbh = new BollingerBandsUpperIndicator(bbm, sd);
logger.info("Bollinger bands upper indicator :" + bbh.getValue(series.getEnd()));
bbw = new BollingerBandWidthIndicator(bbh, bbm, bbl);
logger.info("Bollinger band width :" + bbw.getValue(series.getEnd()));
StringBuilder sb = new StringBuilder("timestamp,close,typical,variation,sma8,sma20,ema8,ema20,ppo,roc,rsi,williamsr,atr,sd\n");
/**
* Adding indicators values
*/
final int nbTick = series.getTickCount();
for (int i = 0; i < nbTick; i++) {
sb.append(series.getTick(i).getEndTime()).append(',')
.append(closePrice.getValue(i)).append(',')
.append(typicalPrice.getValue(i)).append(',')
.append(priceVariation.getValue(i)).append(',')
.append(shortSma.getValue(i)).append(',')
.append(longSma.getValue(i)).append(',')
.append(shortEma.getValue(i)).append(',')
.append(longEma.getValue(i)).append(',')
.append(ppo.getValue(i)).append(',')
.append(roc.getValue(i)).append(',')
.append(rsi.getValue(i)).append(',')
.append(williamsR.getValue(i)).append(',')
.append(atr.getValue(i)).append(',')
.append(sd.getValue(i)).append('\n');
}
/**
* Writing CSV file
*/
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("C:\\Users\\Administrator\\Desktop\\fafa\\indicators.csv"));
writer.write(sb.toString());
} catch (IOException ioe) {
System.out.println(ioe);
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException ioe) {
}
}
}
}
private Map<Object, Object> makeIndicatorObject() {
// Map for indicator values.
try {
logger.info("map state of make indicator");
Map<Object, Object> indicators = new LinkedHashMap<>();
indicators.put("symbol", symbol);
indicators.put("ClosePrice", formatBigDecimal(closePrice.getValue(series.getEnd()).toDouble()));
indicators.put("ShortSMA", formatBigDecimal(shortSma.getValue(series.getEnd()).toDouble()));
indicators.put("LongSMA", formatBigDecimal(longSma.getValue(series.getEnd()).toDouble()));
indicators.put("ShortEMA", formatBigDecimal(shortEma.getValue(series.getEnd()).toDouble()));
indicators.put("LongEMA", formatBigDecimal(longEma.getValue(series.getEnd()).toDouble()));
indicators.put("RSI", formatBigDecimal(rsi.getValue(series.getEnd()).toDouble()));
indicators.put("SD", formatBigDecimal(sd.getValue(series.getEnd()).toDouble()));
indicators.put("MACD", formatBigDecimal(macd.getValue(series.getEnd()).toDouble()));
indicators.put("BBM", formatBigDecimal(bbm.getValue(series.getEnd()).toDouble()));
indicators.put("BBL", formatBigDecimal(bbl.getValue(series.getEnd()).toDouble()));
indicators.put("BBH", formatBigDecimal(bbh.getValue(series.getEnd()).toDouble()));
indicators.put("BBW", formatBigDecimal(bbw.getValue(series.getEnd()).toDouble()));
return indicators;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private BigDecimal formatBigDecimal(double value) {
try {
return new BigDecimal(df.format(value));
} catch (Exception e) {
return new BigDecimal(0);
}
}
private Map<Object, Object> makeEmptyObject() {
logger.info("map state of empty object");
Map<Object, Object> indicators = new LinkedHashMap<>();
indicators.put("symbol", symbol);
indicators.put("ClosePrice", new BigDecimal(0));
indicators.put("ShortSMA", new BigDecimal(0));
indicators.put("LongSMA", new BigDecimal(0));
indicators.put("ShortEMA", new BigDecimal(0));
indicators.put("LongEMA", new BigDecimal(0));
indicators.put("RSI", new BigDecimal(0));
indicators.put("SD", new BigDecimal(0));
indicators.put("MACD", new BigDecimal(0));
indicators.put("BBM", new BigDecimal(0));
indicators.put("BBL", new BigDecimal(0));
indicators.put("BBH", new BigDecimal(0));
indicators.put("BBW", new BigDecimal(0));
return indicators;
}
}
This is the Json Output from the local API that is used in the first class (ApiTestData)
I'm getting the following exception when attempting to save a simple POJO with a map field.
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to com.orientechnologies.orient.core.db.record.OIdentifiable
Here's my code:
package com.example.test;
import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.object.db.OObjectDatabaseTx;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Main {
static class Entity {
private Map map;
public Entity() {
}
public Entity(Map map) {
this.map = map;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
}
private static void doIt() {
String dbUser = "root";
String dbPass = "root";
String dbUrl = "remote:localhost:2424/sandbox";
try {
OServerAdmin serverAdmin = new OServerAdmin(dbUrl);
serverAdmin.connect(dbUser, dbPass);
if (serverAdmin.existsDatabase("plocal")) {
serverAdmin.dropDatabase("plocal");
}
serverAdmin.createDatabase("document", "plocal");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
ODatabaseDocumentTx databaseDocumentTx = new ODatabaseDocumentTx(dbUrl);
databaseDocumentTx.open(dbUser, dbPass);
OObjectDatabaseTx objectDatabaseTx = new OObjectDatabaseTx(databaseDocumentTx);
objectDatabaseTx.getEntityManager().registerEntityClass(Entity.class);
Map map = new HashMap();
map.put("a", "a");
Entity entity = objectDatabaseTx.save(new Entity(map)); //<-- EXCEPTION THROWN HERE!!!
}
public static void main(String[] args) {
doIt();
}
}
Full stack trace:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to com.orientechnologies.orient.core.db.record.OIdentifiable
at com.orientechnologies.orient.core.db.record.ORecordLazyMap.put(ORecordLazyMap.java:41)
at com.orientechnologies.orient.object.enhancement.OObjectEntitySerializer.multiValueToStream(OObjectEntitySerializer.java:1398)
at com.orientechnologies.orient.object.enhancement.OObjectEntitySerializer.typeToStream(OObjectEntitySerializer.java:805)
at com.orientechnologies.orient.object.enhancement.OObjectEntitySerializer.toStream(OObjectEntitySerializer.java:1216)
at com.orientechnologies.orient.object.enhancement.OObjectEntitySerializer.serializeObject(OObjectEntitySerializer.java:144)
at com.orientechnologies.orient.object.db.OObjectDatabaseTx.save(OObjectDatabaseTx.java:454)
at com.orientechnologies.orient.object.db.OObjectDatabaseTx.save(OObjectDatabaseTx.java:399)
at com.example.test.Main.doIt(Main.java:56)
at com.example.test.Main.main(Main.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Any guidance as to what is going on would greatly be appreciated!
I have used this code and it works
import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.orientechnologies.orient.object.db.OObjectDatabaseTx;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Main {
static class Entity {
private Map<String,Object> map;
public Entity() {
this.map=null;
}
public Entity(Map<String,Object> map) {
this.map = map;
}
public Map<String,Object> getMap() {
return map;
}
public void setMap(Map<String,Object> map) {
this.map = map;
}
}
private static void doIt() {
String dbUser = "root";
String dbPass = "root";
String dbUrl = "remote:localhost:2424/sandbox";
try {
OServerAdmin serverAdmin = new OServerAdmin(dbUrl);
serverAdmin.connect(dbUser, dbPass);
if (serverAdmin.existsDatabase("plocal")) {
serverAdmin.dropDatabase("plocal");
System.out.println("Db cancellalto");
}
//serverAdmin.createDatabase("document", "plocal");
serverAdmin.createDatabase("sandbox", "object", "plocal");
System.out.println("Db creato");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
OObjectDatabaseTx objectDatabaseTx = new OObjectDatabaseTx(dbUrl);
objectDatabaseTx.open(dbUser,dbPass);
objectDatabaseTx.getEntityManager().registerEntityClass(Entity.class);
Entity e = objectDatabaseTx.newInstance(Entity.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("a", "a");
e.setMap(map);
// Save the entity
e = objectDatabaseTx.save(e);
}
public static void main(String[] args) {
doIt();
}
}
Hope it helps
After some digging around I'm going to answer my own question. I can make my code work by explicitly declaring the Entity.map field as OType.EMBEDDEDMAP. See below:
...
objectDatabaseTx.getEntityManager().registerEntityClass(Entity.class);
OClass oClass = objectDatabaseTx.getMetadata().getSchema().getClass(Entity.class);
oClass.createProperty("map", OType.EMBEDDEDMAP);
...
However, I ultimately need my map to contain any value (ie: Map<String, Object>). But I can't because there's an open bug for that ...
https://github.com/orientechnologies/orientdb/issues/3063
So that's it folks...
I am working on code (java) that will open up a selenium headless browser with HTML Unit webdriver and then take a screenshot. Unfortunately, HTML Unit does not support screenshots on its own, so I had to download an extended version:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.internal.Base64Encoder;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class ScreenCaptureHtmlUnitDriver extends HtmlUnitDriver implements TakesScreenshot {
private static Map<String, byte[]> imagesCache = Collections.synchronizedMap(new HashMap<String, byte[]>());
private static Map<String, String> cssjsCache = Collections.synchronizedMap(new HashMap<String, String>());
// http://stackoverflow.com/questions/4652777/java-regex-to-get-the-urls-from-css
private final static Pattern cssUrlPattern = Pattern.compile("background(-image)?[\\s]*:[^url]*url[\\s]*\\([\\s]*([^\\)]*)[\\s]*\\)[\\s]*");// ?<url>
public ScreenCaptureHtmlUnitDriver() {
super();
}
public ScreenCaptureHtmlUnitDriver(boolean enableJavascript) {
super(enableJavascript);
}
public ScreenCaptureHtmlUnitDriver(Capabilities capabilities) {
super(capabilities);
}
public ScreenCaptureHtmlUnitDriver(BrowserVersion version) {
super(version);
DesiredCapabilities var = ((DesiredCapabilities) getCapabilities());
var.setCapability(CapabilityType.TAKES_SCREENSHOT, true);
}
//#Override
#SuppressWarnings("unchecked")
public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
byte[] archive = new byte[0];
try {
archive = downloadCssAndImages(getWebClient(), (HtmlPage) getCurrentWindow().getEnclosedPage());
} catch (Exception e) {
}
if(target.equals(OutputType.BASE64)){
return target.convertFromBase64Png(new Base64Encoder().encode(archive));
}
if(target.equals(OutputType.BYTES)){
return (X) archive;
}
return (X) archive;
}
// http://stackoverflow.com/questions/2244272/how-can-i-tell-htmlunits-webclient-to-download-images-and-css
protected byte[] downloadCssAndImages(WebClient webClient, HtmlPage page) throws Exception {
WebWindow currentWindow = webClient.getCurrentWindow();
Map<String, String> urlMapping = new HashMap<String, String>();
Map<String, byte[]> files = new HashMap<String, byte[]>();
WebWindow window = null;
try {
window = webClient.getWebWindowByName(page.getUrl().toString()+"_screenshot");
webClient.getPage(window, new WebRequest(page.getUrl()));
} catch (Exception e) {
window = webClient.openWindow(page.getUrl(), page.getUrl().toString()+"_screenshot");
}
String xPathExpression = "//*[name() = 'img' or name() = 'link' and (#type = 'text/css' or #type = 'image/x-icon') or #type = 'text/javascript']";
List<?> resultList = page.getByXPath(xPathExpression);
Iterator<?> i = resultList.iterator();
while (i.hasNext()) {
try {
HtmlElement el = (HtmlElement) i.next();
String resourceSourcePath = el.getAttribute("src").equals("") ? el.getAttribute("href") : el
.getAttribute("src");
if (resourceSourcePath == null || resourceSourcePath.equals(""))
continue;
URL resourceRemoteLink = page.getFullyQualifiedUrl(resourceSourcePath);
String resourceLocalPath = mapLocalUrl(page, resourceRemoteLink, resourceSourcePath, urlMapping);
urlMapping.put(resourceSourcePath, resourceLocalPath);
if (!resourceRemoteLink.toString().endsWith(".css")) {
byte[] image = downloadImage(webClient, window, resourceRemoteLink);
files.put(resourceLocalPath, image);
} else {
String css = downloadCss(webClient, window, resourceRemoteLink);
for (String cssImagePath : getLinksFromCss(css)) {
URL cssImagelink = page.getFullyQualifiedUrl(cssImagePath.replace("\"", "").replace("\'", "")
.replace(" ", ""));
String cssImageLocalPath = mapLocalUrl(page, cssImagelink, cssImagePath, urlMapping);
files.put(cssImageLocalPath, downloadImage(webClient, window, cssImagelink));
}
files.put(resourceLocalPath, replaceRemoteUrlsWithLocal(css, urlMapping)
.replace("resources/", "./").getBytes());
}
} catch (Exception e) {
}
}
String pagesrc = replaceRemoteUrlsWithLocal(page.getWebResponse().getContentAsString(), urlMapping);
files.put("page.html", pagesrc.getBytes());
webClient.setCurrentWindow(currentWindow);
return createZip(files);
}
String downloadCss(WebClient webClient, WebWindow window, URL resourceUrl) throws Exception {
if (cssjsCache.get(resourceUrl.toString()) == null) {
cssjsCache.put(resourceUrl.toString(), webClient.getPage(window, new WebRequest(resourceUrl))
.getWebResponse().getContentAsString());
}
return cssjsCache.get(resourceUrl.toString());
}
byte[] downloadImage(WebClient webClient, WebWindow window, URL resourceUrl) throws Exception {
if (imagesCache.get(resourceUrl.toString()) == null) {
imagesCache.put(
resourceUrl.toString(),
IOUtils.toByteArray(webClient.getPage(window, new WebRequest(resourceUrl)).getWebResponse()
.getContentAsStream()));
}
return imagesCache.get(resourceUrl.toString());
}
public static byte[] createZip(Map<String, byte[]> files) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zipfile = new ZipOutputStream(bos);
Iterator<String> i = files.keySet().iterator();
String fileName = null;
ZipEntry zipentry = null;
while (i.hasNext()) {
fileName = i.next();
zipentry = new ZipEntry(fileName);
zipfile.putNextEntry(zipentry);
zipfile.write(files.get(fileName));
}
zipfile.close();
return bos.toByteArray();
}
List<String> getLinksFromCss(String css) {
List<String> result = new LinkedList<String>();
Matcher m = cssUrlPattern.matcher(css);
while (m.find()) { // find next match
result.add( m.group(2));
}
return result;
}
String replaceRemoteUrlsWithLocal(String source, Map<String, String> replacement) {
for (String object : replacement.keySet()) {
// background:url(http://org.com/images/image.gif)
source = source.replace(object, replacement.get(object));
}
return source;
}
String mapLocalUrl(HtmlPage page, URL link, String path, Map<String, String> replacementToAdd) throws Exception {
String resultingFileName = "resources/" + FilenameUtils.getName(link.getFile());
replacementToAdd.put(path, resultingFileName);
return resultingFileName;
}
}
Anyway, I found this code, but I am unsure how to use this code to actually take a screenshot.
I would like the screenshot to be a .jpg and to be able to be stored in a certain folder.
In the long haul, I am also going to need to run the screenshot code repeatedly.
Any help would be appreciated.
I am trying to get Win32_SoundDevice and Win32_VideoControllerHardware id but getting Win32_SoundDevice instance throws Unknow Name Exception
here is my code
package com.az;
import static org.jinterop.dcom.core.JIProgId.valueOf;
import static org.jinterop.dcom.impls.JIObjectFactory.narrowObject;
import static org.jinterop.dcom.impls.automation.IJIDispatch.IID;
import java.awt.Label;
import java.util.logging.Level;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIArray;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JISession;
import org.jinterop.dcom.core.JIString;
import org.jinterop.dcom.core.JIVariant;
import org.jinterop.dcom.impls.automation.IJIDispatch;
import org.jinterop.dcom.impls.automation.IJIEnumVariant;
public class PerformanceMonitor extends JApplet {
String domain = "az.com.us";
String hostname = "mc-us-az";
String username = "az";
String password = "test_az_";
public JIComServer comServer = null;
public JISession dcomSession = null;
public IJIDispatch wbemServices = null;
public Object[] params = null;
public static final String soundCardInfo = "Win32_SoundDevice";
public void setWindowsCredentials(String domain, String hostname, String username, String password) {
try {
dcomSession = init(domain, username, password);
comServer = new JIComServer(valueOf("WbemScripting.SWbemLocator"), hostname, dcomSession);
IJIDispatch wbemLocator = (IJIDispatch) narrowObject(comServer.createInstance().queryInterface(IID));
params = new Object[] { new JIString(hostname), new JIString("ROOT\\CIMV2"), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(),
JIVariant.OPTIONAL_PARAM(), new Integer(0), JIVariant.OPTIONAL_PARAM() };
JIVariant results[] = wbemLocator.callMethodA("ConnectServer", params);
wbemServices = (IJIDispatch) narrowObject(results[0].getObjectAsComObject());
getWMISoundCard(getJIVariants(wbemLocator, soundCardInfo));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dcomSession != null) {
try {
JISession.destroySession(dcomSession);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
private void getWMISoundCard(JIVariant[] diskMonit) {
try {
IJIDispatch wbemObjectSet = (IJIDispatch) narrowObject(diskMonit[0].getObjectAsComObject());
JIVariant newEnumvariant = wbemObjectSet.get("_NewEnum");
IJIComObject object2 = newEnumvariant.getObjectAsComObject();
IJIEnumVariant enumVARIANT = (IJIEnumVariant) narrowObject(object2.queryInterface(IJIEnumVariant.IID));
JIVariant countVariant = wbemObjectSet.get("Count");
int numberOfServices = countVariant.getObjectAsInt();
for (int i = 0; i < numberOfServices; i++) {
Object[] elements = enumVARIANT.next(1);
JIArray aJIArray = (JIArray) elements[0];
JIVariant[] array = (JIVariant[]) aJIArray.getArrayInstance();
for (JIVariant variant : array) {
IJIDispatch wbemObjectDispatch = (IJIDispatch) narrowObject(variant.getObjectAsComObject());
JIVariant[] v = wbemObjectDispatch.callMethodA("GetObjectText_", new Object[] { 1 });
JIVariant deviceID = (JIVariant) (wbemObjectDispatch.get("DeviceID"));
System.out.println("SoundCard Device ID =" + deviceID.getObjectAsString2());
}
}
} catch (JIException e) {
e.printStackTrace();
}
}
public JIVariant[] getJIVariants(IJIDispatch wbemServices, String task) {
JIVariant[] arrJIVariant = null;
try {
params = new Object[] { new JIString(task), new Integer(0), JIVariant.OPTIONAL_PARAM() };
arrJIVariant = wbemServices.callMethodA("InstancesOf", params);
} catch (JIException e) {
e.printStackTrace();
}
return arrJIVariant;
}
private static JISession init(String domain, String user, String pass) throws Exception {
JISystem.getLogger().setLevel(Level.OFF);
JISystem.setAutoRegisteration(true);
JISession dcomSession = JISession.createSession(domain, user, pass);
dcomSession.useSessionSecurity(false);
return dcomSession;
}
public static void main(String[] args) {
PerformanceMonitor performanceMonitor = new PerformanceMonitor();
performanceMonitor.setWindowsCredentials(performanceMonitor.domain, performanceMonitor.hostname, performanceMonitor.username, performanceMonitor.password);
}
}
Stack Trace
org.jinterop.dcom.common.JIException: Unknown name. [0x80020006]
at org.jinterop.dcom.core.JIComServer.call(JIComServer.java:910)
at org.jinterop.dcom.core.JIComServer.call(JIComServer.java:856)
at org.jinterop.dcom.core.JIComObjectImpl.call(JIComObjectImpl.java:266)
at org.jinterop.dcom.core.JIComObjectImpl.call(JIComObjectImpl.java:153)
at org.jinterop.dcom.impls.automation.JIDispatchImpl.getIDsOfNames(JIDispatchImpl.java:109)
at org.jinterop.dcom.impls.automation.JIDispatchImpl.callMethodA(JIDispatchImpl.java:477)
at com.az.PerformanceMonitor.getJIVariants(PerformanceMonitor.java:682)
at com.az.PerformanceMonitor.setWindowsCredentials(PerformanceMonitor.java:123)
at com.az.PerformanceMonitor.init(PerformanceMonitor.java:80)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.jinterop.dcom.common.JIRuntimeException: Unknown name. [0x80020006]
at org.jinterop.dcom.core.JICallBuilder.readResult(JICallBuilder.java:1079)
at org.jinterop.dcom.core.JICallBuilder.read(JICallBuilder.java:957)
at ndr.NdrObject.decode(NdrObject.java:36)
at rpc.ConnectionOrientedEndpoint.call(ConnectionOrientedEndpoint.java:137)
at rpc.Stub.call(Stub.java:113)
at org.jinterop.dcom.core.JIComServer.call(JIComServer.java:901)
... 10 more
Just replace this line
getWMISoundCard(getJIVariants(wbemLocator, soundCardInfo));
with this
getWMISoundCard(getJIVariants(wbemServices, soundCardInfo));
and problem solved