<%@ page import="java.io.*"%>
<%@ page import="java.net.*"%>
<%@ page import="java.util.regex.*"%>
<%@ page import="org.apache.commons.codec.binary.Base64"%>
<%@page contentType="application/json; charset=UTF-8"%>
<%!
String getPluginsRoot(ServletContext ctx){
      return ctx.getRealPath("/") + "/plugins/";
}

String getChartsRoot(ServletContext ctx){
      return getPluginsRoot(ctx) + "VitaraMaps/";
}

String getRFilePath(String rFilePath){
      return "/plugins/VitaraMaps/" + rFilePath;
}

void createFile(String path, String data) throws IOException{
      FileWriter filewriter = new FileWriter(path, true);
      filewriter.write(data);
      filewriter.close();
}

void deleteFile(String path){
      File mFile = new File(path);
      if (mFile.exists()){
            mFile.delete();
      }
}

String getOFilePath(ServletContext ctx, String rFilePath){
      return getChartsRoot(ctx) + rFilePath;
}

String[] getDirs(String path){
      File file = new File(path);
      String[] directories = file.list(new FilenameFilter() {
            @Override
            public boolean accept(File current, String name) {
                  return new File(current, name).isDirectory();
            }
      });
      return directories;
}

String readFolderContent(ServletContext ctx, String filePath) throws FileNotFoundException, IOException{
      String res = "";
      String file = getOFilePath(ctx, filePath);
      String[] directories = getDirs(file);
      StringBuffer sb = new StringBuffer();      
      for(int i = 0; i < directories.length; i++) {
            sb.append(directories[i]+"\n");
      }
      res = sb.toString();
      return res;
}

String readFileIS(ServletContext ctx, String rFilePath) throws FileNotFoundException, IOException{
      String res = null;
      InputStream is = ctx.getResourceAsStream(rFilePath);
      if (is != null) {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line;
            while((line = reader.readLine())!= null){
                  sb.append(line+"\n");
            }
            reader.close();
            res = sb.toString();
      }
      return res;
}

String readFile(ServletContext ctx, String rFilePath) throws FileNotFoundException, IOException{
      String path = getOFilePath(ctx, rFilePath);
      BufferedReader reader = new BufferedReader(new FileReader(path));
      StringBuilder sb = new StringBuilder();
      String line;
      while((line = reader.readLine())!= null){
          sb.append(line+"\n");
      }
      reader.close();
      return sb.toString();
}

String readFromURL(String url) throws MalformedURLException, IOException {
      URL mUrl = new URL(url);
      BufferedReader reader = new BufferedReader(new InputStreamReader(mUrl.openStream()));
      StringBuilder sb = new StringBuilder();
      String line;
      while((line = reader.readLine()) != null) {
            sb.append(line+"\n");
      }
      reader.close();
      return sb.toString();
}

String getResponse(String data){
      return new String(Base64.encodeBase64(data.getBytes()));
}

private class URLRequest {
      int status;
      String callback, url, message, data, fileType, context;

      URLRequest(String callback, String url, String fileType, String context) {
            this.callback = callback;
            this.url = url;
            this.fileType = fileType;
            this.context = context;
      }

      String encode(String data) {
            try {
                  return new String(Base64.encodeBase64(data.getBytes()));
            } catch(Exception ex) {
                  ex.printStackTrace();
            }
            return "";
      }
      String getResponse() {
            return this.callback + "({status:" + this.status + ", msg:'" 
            + this.message + "', data:'" 
            + encode(this.data) + "', type:'" 
            + this.fileType + "', ctx:'" 
            + this.context + "'})";
      }
}

String getUrlContent (URLRequest mRequest) {
      HttpURLConnection mConnection = null;
      try {
            mConnection = (HttpURLConnection) (new URL(mRequest.url)).openConnection();
            mConnection.setRequestMethod("GET");
            mRequest.status = mConnection.getResponseCode();
            if (mConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                  mRequest.message = "success";
                  BufferedReader in = new BufferedReader(
                        new InputStreamReader(mConnection.getInputStream()));

                  StringBuilder content = new StringBuilder();
                  String currentLine;
                  while ((currentLine = in.readLine()) != null) {
                        content.append(currentLine);
                  }
                  in.close();
                  mRequest.data = content.toString();
            }
      } catch (MalformedURLException ex) {
            mRequest.status = 500;
            mRequest.message = ex.getMessage();
            ex.printStackTrace();
            System.out.println("ml ex: " + ex.getMessage());
      } catch (Exception ex) {
            mRequest.status = 500;
            mRequest.message = ex.getMessage();
            System.out.println("ex: " + ex.getMessage());
            ex.printStackTrace();
      } finally {
            if (mConnection != null) {
                  mConnection.disconnect();
            }
      }

      return mRequest.getResponse();
}

Boolean isValidAbsoluteUrl(String strUrl) {
      Boolean res = false;
      try {
            URL mUrl = new URL(strUrl);
            res = true;
      } catch (MalformedURLException ex) {
            ex.printStackTrace();
      } catch (Exception ex) {
            ex.printStackTrace();
      }
      return res;
}

%>

<%
      response.setContentType("application/javascript");
      String filePath = request.getParameter("file");
      String callbackFun = request.getParameter("callback");
      String fileType = request.getParameter("type");
      String context = request.getParameter("ctx");	
      if (isValidAbsoluteUrl(filePath)) {
            out.println(getUrlContent(new URLRequest(callbackFun, filePath, fileType, context)));
      } else {
            try {
                  String content;
                  if(fileType != null && fileType.equals("folder")){
                        content = readFolderContent(application, filePath);
                  } else {
                        content = readFileIS(application, getRFilePath(filePath));
                  }
                  String json = callbackFun + "({status:200, msg:'success', data:'"+ getResponse(content) +"', type:'"+ fileType +"', ctx:'"+ context + "'})";
                  out.println(json);
            }
            catch(Exception e){
                  out.println(callbackFun + "({status:500, msg: '"+ e.getMessage() +"', data:'VITARA_MOBILE_FILE_READ_EXCEPTION', ctx:'"+ context + "'})");
            }	 
      }
%>