Skip to content

Commit

Permalink
Update for #71, better save cache, still not working load cache - need
Browse files Browse the repository at this point in the history
further work
  • Loading branch information
tkohegyi committed May 5, 2016
1 parent d85195e commit 426fdf8
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,16 @@
along with Wilma. If not, see <http://www.gnu.org/licenses/>.
===========================================================================*/

import com.epam.wilma.common.helper.FileFactory;
import com.epam.wilma.common.helper.LogFilePathProvider;
import com.epam.wilma.domain.http.WilmaHttpRequest;
import com.epam.wilma.domain.http.WilmaHttpResponse;
import com.epam.wilma.domain.stubconfig.parameter.ParameterList;
import com.epam.wilma.webapp.config.servlet.stub.upload.helper.FileOutputStreamFactory;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
Expand All @@ -40,6 +44,13 @@ class ShortCircuitInterceptorCore {
private final Logger logger = LoggerFactory.getLogger(ShortCircuitInterceptorCore.class);
private final ShortCircuitResponseInformationFileHandler shortCircuitResponseInformationFileHandler = new ShortCircuitResponseInformationFileHandler();

@Autowired
private LogFilePathProvider logFilePathProvider;
@Autowired
private FileFactory fileFactory;
@Autowired
private FileOutputStreamFactory fileOutputStreamFactory;

/**
* Method that generates the general hash code for a request in Short Circuit.
*
Expand Down Expand Up @@ -110,11 +121,13 @@ String handleComplexCall(String myMethod, String folder, HttpServletResponse htt
String response = null;
if ("post".equalsIgnoreCase(myMethod)) {
//save map (to files) (post + circuits?folder=...)
response = shortCircuitResponseInformationFileHandler.savePreservedMessagesFromMap(httpServletResponse, folder);
String path = logFilePathProvider.getLogFilePath() + "/" + folder + "/";
response = shortCircuitResponseInformationFileHandler.savePreservedMessagesFromMap(path, fileFactory, fileOutputStreamFactory, httpServletResponse);
}
if ("get".equalsIgnoreCase(myMethod)) {
//load map (from files) (get + circuits?folder=....)
shortCircuitResponseInformationFileHandler.loadPreservedMessagesToMap(folder);
String path = logFilePathProvider.getLogFilePath() + "/" + folder;
shortCircuitResponseInformationFileHandler.loadPreservedMessagesToMap(path);
response = getShortCircuitMap(httpServletResponse);
}
return response;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@
===========================================================================*/

import com.epam.wilma.common.helper.FileFactory;
import com.epam.wilma.common.helper.LogFilePathProvider;
import com.epam.wilma.common.helper.UniqueIdGenerator;
import com.epam.wilma.webapp.config.servlet.stub.upload.helper.FileOutputStreamFactory;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
Expand All @@ -38,8 +38,6 @@
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* This class provides file save and load utility for {@link ShortCircuitResponseInformation}.
Expand All @@ -53,24 +51,15 @@ class ShortCircuitResponseInformationFileHandler {
private final Logger logger = LoggerFactory.getLogger(ShortCircuitResponseInformationFileHandler.class);
private final int e500 = 500;


@Autowired
private LogFilePathProvider logFilePathProvider;
@Autowired
private FileFactory fileFactory;
@Autowired
private FileOutputStreamFactory fileOutputStreamFactory;

/**
* Saves the map to a folder, to preserve it for later use.
*
* @param httpServletResponse is the response object
* @param folder is the folder to be used, under Wilma'S message folder.
* @return with the response body - that is a json info about the result of the call
*/
String savePreservedMessagesFromMap(HttpServletResponse httpServletResponse, String folder) {
String savePreservedMessagesFromMap(String path, FileFactory fileFactory, FileOutputStreamFactory fileOutputStreamFactory,
HttpServletResponse httpServletResponse) {
String response = null;
String path = logFilePathProvider.getLogFilePath() + "/" + folder + "/";
String filenamePrefix = "sc" + UniqueIdGenerator.getNextUniqueId() + "_";
if (!shortCircuitMap.isEmpty()) {
String[] keySet = shortCircuitMap.keySet().toArray(new String[shortCircuitMap.size()]);
Expand All @@ -81,7 +70,7 @@ String savePreservedMessagesFromMap(HttpServletResponse httpServletResponse, Str
String filename = path + filenamePrefix + UniqueIdGenerator.getNextUniqueId() + ".json";
File file = fileFactory.createFile(filename);
try {
saveMapObject(file, entryKey, information);
saveMapObject(fileOutputStreamFactory, file, entryKey, information);
} catch (IOException e) {
String message = "Cache save failed at file: " + filename + ", with message: " + e.getLocalizedMessage();
logger.info("ShortCircuit: " + message);
Expand All @@ -104,27 +93,23 @@ String savePreservedMessagesFromMap(HttpServletResponse httpServletResponse, Str
/**
* Load the map from a folder, and create a new map from it.
*
* @param folder is the folder to be used, under Wilma'S message folder.
* @param path is the folder to be used, under Wilma's message folder.
*/
void loadPreservedMessagesToMap(String folder) {
void loadPreservedMessagesToMap(String path) {
Map<String, ShortCircuitResponseInformation> newShortCircuitMap = new HashMap<>();

String path = logFilePathProvider.getLogFilePath() + "/" + folder;
File folderFile = new File(path);
File[] listOfFiles = folderFile.listFiles();
if (listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String pattern = "sc*.json";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(listOfFiles[i].getName());
if (m.find()) {
ShortCircuitResponseInformation mapObject = loadMapObject(listOfFiles[i].getName());
if (listOfFiles[i].isFile() && listOfFiles[i].getName().endsWith(".json")) {
try {
ShortCircuitResponseInformation mapObject = loadMapObject(listOfFiles[i].getAbsolutePath());
if (mapObject != null) {
newShortCircuitMap.put(Integer.toString(i), mapObject);
newShortCircuitMap.put(mapObject.getHashCode(), mapObject);
}
} catch (JSONException e) {
logger.info("Cannot load JSON file to Short Circuit map: " + listOfFiles[i].getAbsolutePath() + ", error:" + e.getLocalizedMessage());
}
}
}
Expand All @@ -141,7 +126,7 @@ private ShortCircuitResponseInformation loadMapObject(String fileName) {
if (file.exists()) {
//load the file
String fileContent = loadFileToString(fileName);
if (fileContent != null) { //TODO - this part can fail even if the string is not null
if (fileContent != null) {
JSONObject obj = new JSONObject(fileContent);
String hashKey = obj.getString("Key");
int responseCode;
Expand All @@ -158,6 +143,9 @@ private ShortCircuitResponseInformation loadMapObject(String fileName) {
information.setHashCode(hashKey);
information.setStatusCode(responseCode);
information.setContentType(contentType);
//CHECKSTYLE OFF - we must use "new String" here
body = new String(Base64.decodeBase64(body)); //make it human readable
//CHECKSTYLE ON
information.setBody(body);
Map<String, String> headers = new HashMap<>();
for (int i = 0; i < headerArray.length(); i++) {
Expand Down Expand Up @@ -189,7 +177,7 @@ private String loadFileToString(final String fileName) {
return text;
}

private void saveMapObject(File file, String entryKey, ShortCircuitResponseInformation information) throws IOException {
private void saveMapObject(FileOutputStreamFactory fileOutputStreamFactory, File file, String entryKey, ShortCircuitResponseInformation information) throws IOException {
// if file does not exists, then create it
if (!file.exists()) {
if (file.getParentFile() != null) {
Expand All @@ -213,7 +201,11 @@ private void saveMapObject(File file, String entryKey, ShortCircuitResponseInfor
j++;
}
fos.write(" ],\n \"Body\": ".getBytes());
String myBody = new JSONObject().put("Body", information.getBody()).toString();
//CHECKSTYLE OFF - we must use "new String" here
String body = new String(Base64.encodeBase64(information.getBody().getBytes()));
//CHECKSTYLE ON

String myBody = new JSONObject().put("Body", body).toString();
fos.write((myBody + "\n}").getBytes());
fos.close();
}
Expand Down

0 comments on commit 426fdf8

Please sign in to comment.