Below is my code:
package com.newyzon.controllers;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.rpc.ServiceException;
import com.newyzon.beans.Cart;
import com.newyzon.beans.BookData;
import com.newyzon.beans.BookMeta;
import com.newyzon.beans.DisplayBookList;
import com.newyzon.services.*;
public class BooklistController {
LoginController lc;
Map<String, BookData> booklist = new HashMap<String, BookData>();
public BooklistController(LoginController lc) {
this.lc = lc;
}
public void displayBookList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ServiceException {
BooksService bs = new BooksServiceLocator();
Books books = bs.getBooksPort();
//response.getWriter().append(books.getBook(1).getTitle());
int quant = books.getSize();
String output = "<br/>";
for(int i=0; i < quant; i++) {
Book bk = books.getBook(i);
BookData bd = new BookData(bk.getId(), bk.getTitle(), bk.getAuthor(), bk.getPublisher());
output += "<a href='Controller?task=addbook&bookid=" + bd.getId() + "'>" + bd.getTitle() + "</a><br/>";
booklist.put("" + bd.getId(), bd);
}
DisplayBookList dbl = new DisplayBookList(output);
request.getSession().setAttribute("displayBookList", dbl);
lc.sendRedirectJsp("bookList", request, response);
}
public void addToCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String bookid = request.getParameter("bookid");
BookData bk = booklist.get(bookid);
// Add the book to the cart
Cart cart = (Cart)request.getSession().getAttribute("cart");
if(cart == null) {
cart = new Cart();
request.getSession().setAttribute("cart", cart);
}
BookMeta bm;
if((bm = cart.contains(bk)) != null) {
bm.setQuantity(bm.getQuantity() + 1);
} else {
bm = new BookMeta(bk, 1);
cart.getBooks().add(bm);
}
}
}
For some reason, the HashMap.put() is run, but the resultant booklist object contains no BookData objects, instead it just puts a null value in there. I've debugged and checked to see that the parameter 'bd' contains a BookData object, (and it does), so why doesn't it end up in the hashmap?
Related
i have a requirement in my project. i want to change the value of sended data through postman, like as if there is three parameter like as id, name, salary.now i am sending the data through postman
}
"id":1,
"name":"dhiraj",
"salary":787878
}
now when send the data,it should be save as actual data in database .but if i am sending like as that
}
"id":2,
"name":"",
"salary":787878
}
then name column should be null instead of empty in database.i am using following code for that, but not getting exact output,please help me .
'package com.httpmodify.test.HttpModify.filter;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;
import com.httpmodify.test.HttpModify.model.Student;
#Component
public class RequestModify implements Filter{
private static Logger log=LoggerFactory.getLogger(Student.class);
private static final String ACCEPT_LANGUAGE = "Accept-Language";
#Autowired
LocaleResolver localeResolver;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
// Need to add code if something is required to be initialized.
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
StringBuilder requestJson = new StringBuilder();
String responseJson = "";
BufferedReader bufferedReader = request.getReader();
String line = null;
if (bufferedReader != null) {
while (null != (line = bufferedReader.readLine())) {
requestJson.append(line);
}
}
if (request.getMethod().equals("POST")) {
RestAPIRequestWrapper requestWrapper = new RestAPIRequestWrapper(request,
requestJson.toString().getBytes());
RestAPIResponseWrapper responseWrapper = new RestAPIResponseWrapper(response);
chain.doFilter(requestWrapper, responseWrapper);
response.setContentType("text/plain");
responseJson = responseWrapper.getCaptureAsString();
response.getWriter().write(responseWrapper.getCaptureAsString());
} else {
chain.doFilter(request, response);
}
}
#Override
public void destroy() {
// Need to write some code if some resource needs to be destroyed.
}
/**
* #param locale
* #return String
*/
private String getAcceptLanguage(String locale) {
return locale != null ? locale : "en";
}
}
'
package com.httpmodify.test.HttpModify.filter;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* #author Ashwini Upadhyay
* #Version 1.0
* #date 2019-Apr-02 12:57:38 PM
*/
public class RestAPIRequestWrapper extends HttpServletRequestWrapper {
private final ByteArrayInputStream decryptedDataBAIS;
private HttpServletRequest wrapped;
private Map<String, String[]> parameterMap;
private Map<String, String> headerMap = new HashMap<>();
public RestAPIRequestWrapper(HttpServletRequest wrapped, byte[] decryptedData) {
super(wrapped);
this.wrapped = wrapped;
decryptedDataBAIS = new ByteArrayInputStream(decryptedData);
}
public RestAPIRequestWrapper(HttpServletRequest wrapped, byte[] decryptedData, Map<String, String> headerMap) {
super(wrapped);
this.wrapped = wrapped;
decryptedDataBAIS = new ByteArrayInputStream(decryptedData);
this.headerMap = headerMap;
}
public RestAPIRequestWrapper(HttpServletRequest wrapped) {
super(wrapped);
this.wrapped = wrapped;
decryptedDataBAIS = new ByteArrayInputStream("".getBytes());
}
public RestAPIRequestWrapper(HttpServletRequest wrapped, String paramstr) {
super(wrapped);
this.wrapped = wrapped;
decryptedDataBAIS = null;
String[] paramsArr = paramstr.split("&");
for (int i = 0; i < paramsArr.length; i++) {
String[] paramArr = paramsArr[i].split("=");
addParameter(paramArr[0], paramArr[1]);
}
}
#Override
public String getContentType() {
return super.getContentType();
}
#Override
public BufferedReader getReader() throws UnsupportedEncodingException {
return new BufferedReader(new InputStreamReader(decryptedDataBAIS, "UTF_8"));
}
#Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStream() {
#Override
public int read() {
return decryptedDataBAIS.read();
}
#Override
public boolean isFinished() {
return decryptedDataBAIS.available() == 0;
}
#Override
public boolean isReady() {
return true;
}
#Override
public void setReadListener(ReadListener arg0) {
throw new RuntimeException("Not implemented");
}
};
}
#Override
public Enumeration<String> getParameterNames() {
if (parameterMap == null) {
return wrapped.getParameterNames();
}
return Collections.enumeration(parameterMap.keySet());
}
#Override
public String[] getParameterValues(String name) {
if (parameterMap == null) {
return wrapped.getParameterValues(name);
}
return parameterMap.get(name);
}
#Override
public String getParameter(String name) {
if (parameterMap == null) {
return wrapped.getParameter(name);
}
String[] strings = parameterMap.get(name);
if (strings != null) {
return strings[0];
}
return null;
}
public void addParameter(String name, String value) {
if (parameterMap == null) {
parameterMap = new HashMap<>();
parameterMap.putAll(wrapped.getParameterMap());
}
String[] values = parameterMap.get(name);
if (values == null) {
values = new String[0];
}
List<String> list = new ArrayList<>(values.length + 1);
list.addAll(Arrays.asList(values));
list.add(value);
parameterMap.put(name, list.toArray(new String[0]));
}
#Override
public Map<String, String[]> getParameterMap() {
if (parameterMap == null) {
return wrapped.getParameterMap();
}
return Collections.unmodifiableMap(parameterMap);
}
#Override
public String getHeader(String headerName) {
String headerValue = null;
if (headerMap.containsKey(headerName)) {
headerValue = headerMap.get(headerName);
} else {
headerValue = super.getHeader(headerName);
}
return headerValue;
}
#Override
public Enumeration<String> getHeaders(String name) {
Set<String> values = new HashSet<>();
if (headerMap.containsKey(name) || name.equalsIgnoreCase("Authorization")) {
if (headerMap.get(name) != null)
values.add(headerMap.get(name));
} else {
for (Enumeration<String> e = super.getHeaders(name); e.hasMoreElements();) {
String headerValue = e.nextElement();
values.add(headerValue);
}
}
return Collections.enumeration(values);
}
#Override
public Enumeration<String> getHeaderNames() {
Set<String> names = new HashSet<>();
for (String name : headerMap.keySet()) {
names.add(name);
}
for (Enumeration<String> e = super.getHeaderNames(); e.hasMoreElements();) {
String headerName = e.nextElement();
if (!headerName.equalsIgnoreCase("Authorization"))
names.add(headerName);
}
return Collections.enumeration(names);
}
public void addHeader(String name, String value) {
headerMap.put(name, value);
}
}
package com.httpmodify.test.HttpModify.filter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* #author Ashwini Upadhyay
* #Version 1.0
* #date 2019-Apr-02 12:57:17 PM
*/
public class RestAPIResponseWrapper extends HttpServletResponseWrapper {
private final ByteArrayOutputStream capture;
private ServletOutputStream output;
private PrintWriter writer;
public RestAPIResponseWrapper(HttpServletResponse response) {
super(response);
capture = new ByteArrayOutputStream(response.getBufferSize());
}
#Override
public ServletOutputStream getOutputStream() throws IOException {
if (writer != null) {
throw new IllegalStateException("getWriter() has already been called on this response.");
}
if (output == null) {
output = new ServletOutputStream() {
#Override
public void write(int b) throws IOException {
capture.write(b);
}
#Override
public void flush() throws IOException {
capture.flush();
}
#Override
public void close() throws IOException {
capture.close();
}
#Override
public boolean isReady() {
return false;
}
#Override
public void setWriteListener(WriteListener arg0) {
}
};
}
return output;
}
#Override
public PrintWriter getWriter() throws IOException {
if (output != null) {
throw new IllegalStateException("getOutputStream() has already been called on this response.");
}
if (writer == null) {
writer = new PrintWriter(new OutputStreamWriter(capture, getCharacterEncoding()));
}
return writer;
}
#Override
public void flushBuffer() throws IOException {
super.flushBuffer();
if (writer != null) {
writer.flush();
} else if (output != null) {
output.flush();
}
}
public byte[] getCaptureAsBytes() throws IOException {
if (writer != null) {
writer.close();
} else if (output != null) {
output.close();
}
return capture.toByteArray();
}
public String getCaptureAsString() throws IOException {
return new String(getCaptureAsBytes(), getCharacterEncoding());
}
}
After getting the request in the controller, you can validate the input value. If the input for the name is empty then make it null, and perform the same operation for other input values. After performing these operations save the object to the database.
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 have a table on JSP page. I want to sort it, when click button. How I should do it? Result table will on other jsp page or I can change current table?
That is my servlet, but I cant understand, how return result after sorting. It
Thank you!
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/home")
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
String[] name = {"x1","x2","x3","x4","x5","x6","x7","x8","x9","x10"};
int[] price = {7600,8500,11700,15000,6000,10200,6400,5800,8700,10400};
int[] memory = {4,4,12,16,2,10,3,1,6,8};
int[] camera = {10,8,10,15,6,9,5,4,8,12};
public HomeServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int temp = 0;
List<Product> products = new ArrayList<Product>();
while(temp!=price.length-1){
Product pr = new Product(name[temp], camera[temp], memory[temp], price[temp]);
temp++;
products.add(pr);
}
request.setAttribute("productList", products);
RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/WEB-INF/views/home.jsp");
rd.forward(request, response);
if (request.getParameter("button1") != null) {
Sorts.function1(price);// in this function I sort table by a certain field
} else if (request.getParameter("button2") != null) {
Sorts.function1(memory);
}
}
//???? WHAT I SHOULD DO HERE?
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
I am trying to upload a file to web server and read the same. file uploading is working and the file is uploaded but when i call some methods to manipulate saved file the method is not getting called.
in the following file i call readFile method from post method.
I am using tomcat 7.0. Please save me from this. the code is :
package org.slingemp.fileupload;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slingemp.bean.setNotification;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Servlet implementation class Fileupload
*/
#WebServlet("/Fileupload")
public class Fileupload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Fileupload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("file upload started....Antony");
// TODO Auto-generated method stub
List fileItemsList = null;
float filesize = 0;
String _fileLink;
String _fileName = null;
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
// Change upload with your directory
HttpSession session = request.getSession(true);
try {
if (ServletFileUpload.isMultipartContent(request)) {
ServletFileUpload servletFileUpload = new ServletFileUpload(
new DiskFileItemFactory());
try {
fileItemsList = servletFileUpload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(Fileupload.class.getName()).log(
Level.SEVERE, null, ex);
// Change above line replace FileUploadExample with your
// file name
}
String optionalFileName = "";
FileItem fileItem = null;
Iterator it = fileItemsList.iterator();
while (it.hasNext()) {
FileItem fileItemTemp = (FileItem) it.next();
if (fileItemTemp.isFormField()) {
if (fileItemTemp.getFieldName().equals("filename")) {
optionalFileName = fileItemTemp.getString();
}
/*
* If you want to pass some other data from JSP page.
* You can access then in this way. For each field you
* have do create if like below. if
* (fileItemTemp.getFieldName
* ().equals("Name of other field like:Firstname")) {
* String Firstname = fileItemTemp.getString(); }
*/
} else {
fileItem = fileItemTemp;
}
}
if (fileItem != null) {
long size_long = fileItem.getSize();
filesize = size_long / 1024;
filesize = filesize / 1000;
// If you want to limit the file size. Here 30MB file size
// is allowed you can change it
//if (filesize > 30.0) {
// Pass error message in session.
//setNotification _sN = new setNotification();
//_sN.setError("File size can't be more than 30MB");
//session.setAttribute("error", _sN);
//} else {
_fileName = fileItem.getName();
if (fileItem.getSize() > 0) {
if (optionalFileName.trim().equals("")) {
_fileName = FilenameUtils.getName(_fileName);
} else {
_fileName = optionalFileName;
}
_fileLink = "../accesscarddata/" + _fileName;
try {
File file = new File(new File(_uploadDir + "/"),fileItem.getName());
fileItem.write(file);
} catch (Exception e) {
e.printStackTrace();
}
setNotification _sN = new setNotification();
_sN.setError("File Uploaded to : " + _fileLink + "");
session.setAttribute("accesscardDatafileNname", _fileName);
session.setAttribute("error", _sN);
}
//}
}
//SELECT * FROM leave_application WHERE from_date >= '2004-01-01' AND to_date <'2004-01-30' and emp_id=128
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("before calling readFile");
readFile(request,response);
System.out.println("after calling readFile");
response.sendRedirect("index.jsp");
}
protected void readFile(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("readFile is called..");
Map employeeMap = null;
String fileName = "",employeeAttendanceFilePath="";
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
HttpSession session = request.getSession(true);
if(session.getAttribute("accesscardDatafileNname") != null)
fileName = (String) session.getAttribute("accesscardDatafileNname");
employeeAttendanceFilePath = _uploadDir+fileName;
System.out.println("File Path : "+employeeAttendanceFilePath);
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(employeeAttendanceFilePath);
// Create an excel workbook from the file system.
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);// gets the first sheet on workbook
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
//count=count+1;
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
session.setAttribute("sheetData", sheetData);
processEmployeeAttendance(request,response);
System.out.println("employeeMap : "+employeeMap);
if(session.getAttribute("employeeMap")!=null)
employeeMap = (LinkedHashMap) session.getAttribute("sheetData");
Iterator<Map.Entry> entries = employeeMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
protected void processEmployeeAttendance(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("processEmployeeAttendance is called...");
String tempEmpid="",strdepartment="";
int j=1;
List sheetData =null;
HttpSession session = request.getSession(true);
if(session.getAttribute("sheetData")!=null)
sheetData = (ArrayList) session.getAttribute("sheetData");
Map employeeMap = new LinkedHashMap();
Map tempEmployeeMap = new LinkedHashMap();
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
HSSFCell employeeid = (HSSFCell) list.get(0);
HSSFCell department = (HSSFCell) list.get(3);
HSSFCell date = (HSSFCell) list.get(5);
strdepartment = department.getRichStringCellValue().getString();
if(!tempEmpid.equals("")){
if(tempEmpid.equals(employeeid.getRichStringCellValue().getString()) && !(employeeid.getRichStringCellValue().getString().equals("EmpID") || date.getRichStringCellValue().getString().equals("Date") || department.getRichStringCellValue().getString().equals("Department"))){
if(!(strdepartment.equals("Temporary Card") || strdepartment.equals("Contractor"))){
employeeMap.put(employeeid.getRichStringCellValue().getString()+"_"+j,date.getRichStringCellValue().getString());
// System.out.println("j value : "+j+":"+employeeid.getRichStringCellValue().getString()+"_"+j+","+date.getRichStringCellValue().getString());
j++;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
j=0;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
}
// System.out.println("");
}
session.setAttribute("employeeMap", employeeMap);
}
}
I wanted to put it as a comment, but somehow I am unable to comment.
My suggestion would be to debug the code using your IDE. Put breakpoints at relevant positions and see where its going.
how to update file to tomcat 5.5.
i tried with the follwoing code but the code does not run with tomcat5.5 and shows
Tomcat version 5.5 only supports J2EE 1.2, 1.3, and 1.4 Web module
the code is:
package org.slingemp.fileupload;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slingemp.bean.setNotification;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Servlet implementation class Fileupload
*/
#WebServlet("/Fileupload")
public class Fileupload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Fileupload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("file upload started....");
// TODO Auto-generated method stub
List fileItemsList = null;
float filesize = 0;
String _fileLink;
String _fileName = null;
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
System.out.println("_uploadDir :"+_uploadDir);
// Change upload with your directory
HttpSession session = request.getSession(true);
try {
if (ServletFileUpload.isMultipartContent(request)) {
ServletFileUpload servletFileUpload = new ServletFileUpload(
new DiskFileItemFactory());
try {
fileItemsList = servletFileUpload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(Fileupload.class.getName()).log(Level.SEVERE, null, ex);
// Change above line replace FileUploadExample with your
// file name
}
String optionalFileName = "";
FileItem fileItem = null;
Iterator it = fileItemsList.iterator();
while (it.hasNext()) {
FileItem fileItemTemp = (FileItem) it.next();
if (fileItemTemp.isFormField()) {
if (fileItemTemp.getFieldName().equals("filename")) {
optionalFileName = fileItemTemp.getString();
System.out.println("optionalFileName : "+optionalFileName);
}
/*
* If you want to pass some other data from JSP page.
* You can access then in this way. For each field you
* have do create if like below. if
* (fileItemTemp.getFieldName
* ().equals("Name of other field like:Firstname")) {
* String Firstname = fileItemTemp.getString(); }
*/
} else {
fileItem = fileItemTemp;
}
}
if (fileItem != null) {
long size_long = fileItem.getSize();
filesize = size_long / 1024;
filesize = filesize / 1000;
// If you want to limit the file size. Here 30MB file size
// is allowed you can change it
//if (filesize > 30.0) {
// Pass error message in session.
//setNotification _sN = new setNotification();
//_sN.setError("File size can't be more than 30MB");
//session.setAttribute("error", _sN);
//} else {
_fileName = fileItem.getName();
if (fileItem.getSize() > 0) {
if (optionalFileName.trim().equals("")) {
_fileName = FilenameUtils.getName(_fileName);
} else {
_fileName = optionalFileName;
}
_fileLink = "../accesscarddata/" + _fileName;
try {
File file = new File(new File(_uploadDir + "/"),fileItem.getName());
fileItem.write(file);
} catch (Exception e) {
e.printStackTrace();
}
setNotification _sN = new setNotification();
_sN.setError("File Uploaded to : " + _fileLink + "");
session.setAttribute("accesscardDatafileNname", _fileName);
session.setAttribute("error", _sN);
}
//}
}
//SELECT * FROM leave_application WHERE from_date >= '2004-01-01' AND to_date <'2004-01-30' and emp_id=128
}
} catch (Exception e) {
e.printStackTrace();
} finally{
}
System.out.println("before calling readFile");
readFile(request,response);
System.out.println("after calling readFile");
response.sendRedirect("index.jsp");
}
protected void readFile(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("readFile is called..");
Map employeeMap = null;
String fileName = "",employeeAttendanceFilePath="";
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
HttpSession session = request.getSession(true);
if(session.getAttribute("accesscardDatafileNname") != null)
fileName = (String) session.getAttribute("accesscardDatafileNname");
employeeAttendanceFilePath = _uploadDir+fileName;
System.out.println("File Path : "+employeeAttendanceFilePath);
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(employeeAttendanceFilePath);
// Create an excel workbook from the file system.
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);// gets the first sheet on workbook
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
//count=count+1;
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
session.setAttribute("sheetData", sheetData);
processEmployeeAttendance(request,response);
System.out.println("employeeMap : "+employeeMap);
if(session.getAttribute("employeeMap")!=null)
employeeMap = (LinkedHashMap) session.getAttribute("sheetData");
Iterator<Map.Entry> entries = employeeMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
protected void processEmployeeAttendance(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("processEmployeeAttendance is called...");
String tempEmpid="",strdepartment="";
int j=1;
List sheetData =null;
HttpSession session = request.getSession(true);
if(session.getAttribute("sheetData")!=null)
sheetData = (ArrayList) session.getAttribute("sheetData");
Map employeeMap = new LinkedHashMap();
Map tempEmployeeMap = new LinkedHashMap();
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
HSSFCell employeeid = (HSSFCell) list.get(0);
HSSFCell department = (HSSFCell) list.get(3);
HSSFCell date = (HSSFCell) list.get(5);
strdepartment = department.getRichStringCellValue().getString();
if(!tempEmpid.equals("")){
if(tempEmpid.equals(employeeid.getRichStringCellValue().getString()) && !(employeeid.getRichStringCellValue().getString().equals("EmpID") || date.getRichStringCellValue().getString().equals("Date") || department.getRichStringCellValue().getString().equals("Department"))){
if(!(strdepartment.equals("Temporary Card") || strdepartment.equals("Contractor"))){
employeeMap.put(employeeid.getRichStringCellValue().getString()+"_"+j,date.getRichStringCellValue().getString());
// System.out.println("j value : "+j+":"+employeeid.getRichStringCellValue().getString()+"_"+j+","+date.getRichStringCellValue().getString());
j++;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
j=0;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
}
// System.out.println("");
}
session.setAttribute("employeeMap", employeeMap);
}
}
when i run this code in tomcat 7 it says this error when uploading the file :
java.io.FileNotFoundException: D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\Fileupload\accesscarddata\C:\Users\anthony.savarimut\Desktop\Map Iterate\SampleData.xls (The filename, directory name, or volume label syntax is incorrect)
Please save me form this.
You are running the tomcat in workspace. Please change location to where tomcat installed. I assuming that your are running with eclipse, click on server and set the location.