ANN - BM-ActivityStream - POC - BitMessage


SUBMITTED BY: Guest

DATE: Aug. 9, 2013, 12:56 a.m.

FORMAT: Text only

SIZE: 234.5 kB

HITS: 1183

  1. package BMActivityStream;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.BufferedReader;
  8. import java.io.UnsupportedEncodingException;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import java.util.Map;
  12. import java.util.HashMap;
  13. import java.util.Vector;
  14. import java.util.Enumeration;
  15. import java.security.MessageDigest;
  16. import java.security.NoSuchAlgorithmException;
  17. import java.util.UUID;
  18. import org.apache.commons.io.IOUtils;
  19. import java.util.Iterator;
  20. import java.util.Set;
  21. import com.sun.net.httpserver.Headers;
  22. import java.io.BufferedInputStream;
  23. import java.io.ByteArrayOutputStream;
  24. import java.io.OutputStream;
  25. import java.net.InetSocketAddress;
  26. import java.net.URLDecoder;
  27. import java.net.URI;
  28. import com.sun.net.httpserver.HttpExchange;
  29. import com.sun.net.httpserver.HttpHandler;
  30. import com.sun.net.httpserver.HttpServer;
  31. import com.sun.net.httpserver.Filter;
  32. import com.sun.net.httpserver.HttpContext;
  33. import javax.xml.parsers.DocumentBuilderFactory;
  34. import javax.xml.parsers.DocumentBuilder;
  35. import org.w3c.dom.Document;
  36. import org.w3c.dom.NodeList;
  37. import org.w3c.dom.Node;
  38. import org.w3c.dom.Element;
  39. import javax.xml.transform.Transformer;
  40. import javax.xml.transform.TransformerException;
  41. import javax.xml.transform.TransformerFactory;
  42. import javax.xml.transform.dom.DOMSource;
  43. import javax.xml.transform.stream.StreamResult;
  44. import java.io.ByteArrayInputStream;
  45. import org.apache.commons.codec.binary.Base64;
  46. import org.apache.http.HttpEntity;
  47. import org.apache.http.HttpResponse;
  48. import org.apache.http.NameValuePair;
  49. import org.apache.http.client.entity.UrlEncodedFormEntity;
  50. import org.apache.http.client.methods.HttpGet;
  51. import org.apache.http.client.methods.HttpPost;
  52. import org.apache.http.impl.client.DefaultHttpClient;
  53. import org.apache.http.message.BasicNameValuePair;
  54. import org.apache.http.entity.StringEntity;
  55. import org.apache.http.util.EntityUtils;
  56. import org.apache.http.auth.AuthScope;
  57. import org.apache.http.auth.UsernamePasswordCredentials;
  58. import java.sql.Connection;
  59. import java.sql.DriverManager;
  60. import java.sql.PreparedStatement;
  61. import java.sql.ResultSet;
  62. import java.sql.ResultSetMetaData;
  63. import java.sql.SQLException;
  64. import java.sql.Statement;
  65. import org.json.simple.parser.ContainerFactory;
  66. import org.json.simple.parser.ContentHandler;
  67. import org.json.simple.parser.JSONParser;
  68. import org.json.simple.parser.ParseException;
  69. import java.io.*;
  70. import java.util.Hashtable;
  71. import javax.mail.*;
  72. import javax.mail.internet.*;
  73. import javax.mail.util.*;
  74. import javax.activation.*;
  75. public class BMActivityStream {
  76. private static ActivityStreamdb db = null;
  77. public static void main(String[] args) throws Exception
  78. {
  79. try {
  80. db = new ActivityStreamdb("db_file_activitystream");
  81. } catch (Exception ex1) {
  82. ex1.printStackTrace();
  83. return; // bye bye
  84. }
  85. try {
  86. System.out.println("Creating database entries");
  87. db.update("CREATE TABLE bm_table ( msgid VARCHAR(64), address VARCHAR(38), application VARCHAR(64), message LONGVARCHAR, dtstamp TIMESTAMP)");
  88. System.out.println("Created bm_table");
  89. } catch (SQLException ex2) {
  90. System.out.println("Table bm_table in place");
  91. }
  92. try {
  93. db.update("CREATE TABLE bm_mail ( msgid VARCHAR(64), ackdata VARCHAR(64), read BOOLEAN, folder VARCHAR(64), toaddress VARCHAR(38), fromaddress VARCHAR(38), subject LONGVARCHAR, message LONGVARCHAR, encodingtype INTEGER, dtstamp TIMESTAMP)");
  94. System.out.println("Created bm_mail");
  95. } catch (SQLException ex2) {
  96. System.out.println("Table bm_mail in place");
  97. }
  98. try {
  99. db.update("CREATE TABLE bm_mail_folders ( folder VARCHAR(64))");
  100. System.out.println("Created bm_mail_folders");
  101. try {
  102. String INSERT_RECORD = "INSERT INTO bm_mail_folders(folder) VALUES(?)";
  103. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  104. pstmt.setString(1, "Inbox");
  105. int i = pstmt.executeUpdate();
  106. if (i == -1) {
  107. System.out.println("db error : " );
  108. }
  109. pstmt.close();
  110. } catch (SQLException ex3) {
  111. ex3.printStackTrace();
  112. }
  113. try {
  114. String INSERT_RECORD = "INSERT INTO bm_mail_folders(folder) VALUES(?)";
  115. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  116. pstmt.setString(1, "Sent");
  117. int i = pstmt.executeUpdate();
  118. if (i == -1) {
  119. System.out.println("db error : " );
  120. }
  121. pstmt.close();
  122. } catch (SQLException ex3) {
  123. ex3.printStackTrace();
  124. }
  125. try {
  126. String INSERT_RECORD = "INSERT INTO bm_mail_folders(folder) VALUES(?)";
  127. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  128. pstmt.setString(1, "Drafts");
  129. int i = pstmt.executeUpdate();
  130. if (i == -1) {
  131. System.out.println("db error : " );
  132. }
  133. pstmt.close();
  134. } catch (SQLException ex3) {
  135. ex3.printStackTrace();
  136. }
  137. try {
  138. String INSERT_RECORD = "INSERT INTO bm_mail_folders(folder) VALUES(?)";
  139. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  140. pstmt.setString(1, "Spam");
  141. int i = pstmt.executeUpdate();
  142. if (i == -1) {
  143. System.out.println("db error : " );
  144. }
  145. pstmt.close();
  146. } catch (SQLException ex3) {
  147. ex3.printStackTrace();
  148. }
  149. try {
  150. String INSERT_RECORD = "INSERT INTO bm_mail_folders(folder) VALUES(?)";
  151. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  152. pstmt.setString(1, "Trash");
  153. int i = pstmt.executeUpdate();
  154. if (i == -1) {
  155. System.out.println("db error : " );
  156. }
  157. pstmt.close();
  158. } catch (SQLException ex3) {
  159. ex3.printStackTrace();
  160. }
  161. } catch (SQLException ex2) {
  162. System.out.println("Table bm_mail_folders in place");
  163. }
  164. try {
  165. db.update("CREATE TABLE bm_profiles ( address VARCHAR(38), follower BOOLEAN, follower_msgid VARCHAR(64), following BOOLEAN, following_msgid VARCHAR(64), label VARCHAR(128), notes LONGVARCHAR, dtstamp TIMESTAMP)");
  166. System.out.println("Created bm_profiles");
  167. } catch (SQLException ex2) {
  168. System.out.println("Table bm_profiles in place");
  169. }
  170. try {
  171. db.update("CREATE TABLE bm_profiles_lists ( address VARCHAR(38), list LONGVARCHAR)");
  172. System.out.println("Created bm_profiles_lists");
  173. } catch (SQLException ex2) {
  174. System.out.println("Table bm_profiles_lists in place");
  175. }
  176. try {
  177. db.update("CREATE TABLE bm_alerts ( msgid VARCHAR(64), message LONGVARCHAR, dtstamp TIMESTAMP)");
  178. System.out.println("Created bm_alerts");
  179. } catch (SQLException ex2) {
  180. System.out.println("Table bm_alerts in place");
  181. }
  182. try {
  183. db.update("CREATE TABLE bm_groups ( address VARCHAR(38), label LONGVARCHAR, know_members VARCHAR(38))");
  184. System.out.println("Created bm_groups");
  185. } catch (SQLException ex2) {
  186. System.out.println("Table bm_groups in place");
  187. }
  188. try {
  189. db.update("CREATE TABLE bm_lastclick ( wpage VARCHAR(64), dtstamp TIMESTAMP)");
  190. System.out.println("Created bm_lastclick");
  191. try {
  192. String INSERT_RECORD = "INSERT INTO bm_lastclick(wpage,dtstamp) VALUES(?,?)";
  193. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  194. pstmt.setString(1, "MESSAGES");
  195. java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
  196. pstmt.setTimestamp(2, sqlDate);
  197. int i = pstmt.executeUpdate();
  198. if (i == -1) {
  199. System.out.println("db error : " );
  200. }
  201. pstmt.close();
  202. } catch (SQLException ex3) {
  203. ex3.printStackTrace();
  204. }
  205. try {
  206. String INSERT_RECORD = "INSERT INTO bm_lastclick(wpage,dtstamp) VALUES(?,?)";
  207. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  208. pstmt.setString(1, "FOLLOWERS");
  209. java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
  210. pstmt.setTimestamp(2, sqlDate);
  211. int i = pstmt.executeUpdate();
  212. if (i == -1) {
  213. System.out.println("db error : " );
  214. }
  215. pstmt.close();
  216. } catch (SQLException ex3) {
  217. ex3.printStackTrace();
  218. }
  219. try {
  220. String INSERT_RECORD = "INSERT INTO bm_lastclick(wpage,dtstamp) VALUES(?,?)";
  221. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  222. pstmt.setString(1, "ALERTS");
  223. java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
  224. pstmt.setTimestamp(2, sqlDate);
  225. int i = pstmt.executeUpdate();
  226. if (i == -1) {
  227. System.out.println("db error : " );
  228. }
  229. pstmt.close();
  230. } catch (SQLException ex3) {
  231. ex3.printStackTrace();
  232. }
  233. } catch (SQLException ex2) {
  234. System.out.println("Table bm_lastclick in place");
  235. }
  236. try {
  237. db.update("CREATE TABLE bm_settings ( setting LONGVARCHAR, value LONGVARCHAR)");
  238. System.out.println("Created bm_settings");
  239. try {
  240. String INSERT_RECORD = "INSERT INTO bm_settings(setting,value) VALUES(?,?)";
  241. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  242. pstmt.setString(1, "bmapi_ip");
  243. pstmt.setString(2, "localhost");
  244. int i = pstmt.executeUpdate();
  245. if (i == -1) {
  246. System.out.println("db error : " );
  247. }
  248. pstmt.close();
  249. } catch (SQLException ex3) {
  250. ex3.printStackTrace();
  251. }
  252. try {
  253. String INSERT_RECORD = "INSERT INTO bm_settings(setting,value) VALUES(?,?)";
  254. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  255. pstmt.setString(1, "bmapi_port");
  256. pstmt.setString(2, "8442");
  257. int i = pstmt.executeUpdate();
  258. if (i == -1) {
  259. System.out.println("db error : " );
  260. }
  261. pstmt.close();
  262. } catch (SQLException ex3) {
  263. ex3.printStackTrace();
  264. }
  265. try {
  266. String INSERT_RECORD = "INSERT INTO bm_settings(setting,value) VALUES(?,?)";
  267. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  268. pstmt.setString(1, "bmapi_user");
  269. pstmt.setString(2, "default");
  270. int i = pstmt.executeUpdate();
  271. if (i == -1) {
  272. System.out.println("db error : " );
  273. }
  274. pstmt.close();
  275. } catch (SQLException ex3) {
  276. ex3.printStackTrace();
  277. }
  278. try {
  279. String INSERT_RECORD = "INSERT INTO bm_settings(setting,value) VALUES(?,?)";
  280. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  281. pstmt.setString(1, "bmapi_password");
  282. pstmt.setString(2, "default");
  283. int i = pstmt.executeUpdate();
  284. if (i == -1) {
  285. System.out.println("db error : " );
  286. }
  287. pstmt.close();
  288. } catch (SQLException ex3) {
  289. ex3.printStackTrace();
  290. }
  291. try {
  292. String INSERT_RECORD = "INSERT INTO bm_settings(setting,value) VALUES(?,?)";
  293. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  294. pstmt.setString(1, "bmapi_client");
  295. pstmt.setString(2, "false");
  296. int i = pstmt.executeUpdate();
  297. if (i == -1) {
  298. System.out.println("db error : " );
  299. }
  300. pstmt.close();
  301. } catch (SQLException ex3) {
  302. ex3.printStackTrace();
  303. }
  304. } catch (SQLException ex2) {
  305. System.out.println("Table bm_settings in place");
  306. }
  307. HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
  308. HttpContext context = server.createContext("/", new MainHandler(db));
  309. context.getFilters().add(new ParameterFilter());
  310. context = server.createContext("/alerts", new AlertsHandler(db));
  311. context.getFilters().add(new ParameterFilter());
  312. context = server.createContext("/followers", new ProfilesHandler(db));
  313. context.getFilters().add(new ParameterFilter());
  314. context = server.createContext("/message", new MessageHandler(db));
  315. context.getFilters().add(new ParameterFilter());
  316. context = server.createContext("/messages", new MessagesHandler(db));
  317. context.getFilters().add(new ParameterFilter());
  318. context = server.createContext("/profile", new ProfileHandler(db));
  319. context.getFilters().add(new ParameterFilter());
  320. context = server.createContext("/send", new SendHandler(db));
  321. context.getFilters().add(new ParameterFilter());
  322. context = server.createContext("/send_message", new SendMessageHandler(db));
  323. context.getFilters().add(new ParameterFilter());
  324. context = server.createContext("/settings", new SettingsHandler(db));
  325. context.getFilters().add(new ParameterFilter());
  326. context = server.createContext("/logout", new LogoutHandler(db, server));
  327. context.getFilters().add(new ParameterFilter());
  328. server.setExecutor(null); // creates a default executor
  329. System.out.println("HttpServer started");
  330. server.start();
  331. }
  332. static class MainHandler implements HttpHandler
  333. {
  334. private ActivityStreamdb db = null;
  335. public MainHandler(ActivityStreamdb db) {
  336. this.db = db;
  337. }
  338. public void handle(HttpExchange t) throws IOException {
  339. String response = "";
  340. String application = "news";
  341. String mid = "";
  342. processMessages processor = new processMessages(db);
  343. processor.process();
  344. HTMLBuilder html = new HTMLBuilder();
  345. html.appendHTMLHead();
  346. html.appendHTMLStyle();
  347. html.appendHTMLScript();
  348. html.appendHTMLHeadEndNews();
  349. html.appendNAVBar();
  350. html.appendMainLeftMenu();
  351. html.appendEndDiv();
  352. html.appendMainStart();
  353. @SuppressWarnings("unchecked")
  354. Map<String, Object> params = (Map<String, Object>)t.getAttribute("parameters");
  355. if (params.containsKey("application"))
  356. {
  357. application = (String)params.get("application");
  358. }
  359. if (params.containsKey("msgid"))
  360. {
  361. mid = (String)params.get("msgid");
  362. }
  363. NewsPostForm postform = new NewsPostForm();
  364. if (mid.equals(""))
  365. {
  366. response = response + postform.getNewsPostForm();
  367. }
  368. int offset = 0;
  369. int maxPages = 1;
  370. int page = 1;
  371. if (mid.equals(""))
  372. {
  373. int count = 0;
  374. String csql = "SELECT COUNT(*) AS rowcount FROM bm_table WHERE application=?";
  375. try {
  376. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  377. pstmt.setString(1, application);
  378. ResultSet rs = pstmt.executeQuery();
  379. rs.next();
  380. count = rs.getInt(1);
  381. pstmt.close();
  382. } catch (SQLException ex3) {
  383. ex3.printStackTrace();
  384. }
  385. maxPages = (count/100);
  386. if (maxPages*100 < count)
  387. {
  388. maxPages = maxPages + 1;
  389. }
  390. page = 1;
  391. if (params.containsKey("page"))
  392. {
  393. String spage = (String)params.get("page");
  394. page = Integer.parseInt(spage);
  395. }
  396. offset = (page*100) - 100;
  397. }
  398. if (application.equals("news"))
  399. {
  400. String like = "";
  401. String addressFrom = "";
  402. String target = "";
  403. String inReplyTo = "";
  404. if (params.containsKey("like"))
  405. {
  406. like = (String)params.get("like");
  407. addressFrom = (String)params.get("address");
  408. target = (String)params.get("target");
  409. inReplyTo = (String)params.get("inReplyTo");
  410. Node activity = null;
  411. try {
  412. String query = "SELECT message FROM bm_table WHERE msgid='" + target + "'";
  413. ResultSet dbq = db.query(query);
  414. Object o = null;
  415. for (; dbq.next(); ) {
  416. o = dbq.getObject(1);
  417. String message = o.toString();
  418. try {
  419. DocumentBuilderFactory dbFactory2 = DocumentBuilderFactory.newInstance();
  420. DocumentBuilder dBuilder2 = dbFactory2.newDocumentBuilder();
  421. Document doc2 = dBuilder2.parse(new ByteArrayInputStream(message.getBytes()));
  422. doc2.getDocumentElement().normalize();
  423. activity = doc2.getElementsByTagName("activity").item(0);
  424. } catch (Exception e) {
  425. e.printStackTrace();
  426. }
  427. }
  428. db.st.close();
  429. } catch (SQLException ex3) {
  430. ex3.printStackTrace();
  431. }
  432. Like liker = new Like(activity, addressFrom, target, inReplyTo);
  433. liker.like();
  434. }
  435. InputStream is = t.getRequestBody();
  436. if (t.getRequestMethod().equalsIgnoreCase("POST"))
  437. {
  438. stream2File fstream = new stream2File();
  439. File tmpfile = fstream.getstream2file(is);
  440. try {
  441. DataSource ds = new FileDataSource(tmpfile);
  442. FormdataMultipart forminput = new FormdataMultipart(ds);
  443. Hashtable paramsa = forminput.getParameters();
  444. if (paramsa.containsKey("comment"))
  445. {
  446. String[] commenta = (String[])paramsa.get("comment");
  447. String comment = commenta[0];
  448. comment = "<![CDATA[" + comment + "]]>";
  449. String[] addressFroma = (String[])paramsa.get("address");
  450. addressFrom = addressFroma[0];
  451. String[] targeta = (String[])paramsa.get("targetid");
  452. target = targeta[0];
  453. String[] inReplyToa = (String[])paramsa.get("inreplytoid");
  454. inReplyTo = inReplyToa[0];
  455. String[] comment_typea = (String[])paramsa.get("comment_type");
  456. String comment_type = comment_typea[0];
  457. Node activity = null;
  458. try {
  459. String query = "SELECT message FROM bm_table WHERE msgid='" + target + "'";
  460. ResultSet dbq = db.query(query);
  461. Object o = null;
  462. for (; dbq.next(); ) {
  463. o = dbq.getObject(1);
  464. String message = o.toString();
  465. try {
  466. DocumentBuilderFactory dbFactory2 = DocumentBuilderFactory.newInstance();
  467. DocumentBuilder dBuilder2 = dbFactory2.newDocumentBuilder();
  468. Document doc2 = dBuilder2.parse(new ByteArrayInputStream(message.getBytes()));
  469. doc2.getDocumentElement().normalize();
  470. activity = doc2.getElementsByTagName("activity").item(0);
  471. } catch (Exception e) {
  472. e.printStackTrace();
  473. }
  474. }
  475. db.st.close();
  476. } catch (SQLException ex3) {
  477. ex3.printStackTrace();
  478. }
  479. Comment commenter = new Comment(activity, addressFrom, target, inReplyTo, comment, comment_type);
  480. commenter.comment();
  481. }
  482. if (paramsa.containsKey("share_post"))
  483. {
  484. String[] commenta = (String[])paramsa.get("share_post");
  485. String comment = commenta[0];
  486. comment = "<![CDATA[" + comment + "]]>";
  487. ArrayList<String> images = new ArrayList<String>();
  488. for (int i=0; i< forminput.getCount(); i++)
  489. {
  490. BodyPart bodprt = forminput.getBodyPart(i);
  491. DataHandler blah = bodprt.getDataHandler();
  492. InputStream is4 = blah.getInputStream();
  493. String imagein = "data:" + blah.getContentType() + ";base64,";
  494. base64processor encoded = new base64processor();
  495. imagein = imagein + encoded.toString(IOUtils.toByteArray(is4));
  496. images.add(imagein);
  497. }
  498. String[] ToAddress = (String[])paramsa.get("To");
  499. String[] followersa = (String[])paramsa.get("followers");
  500. String ToAddressType = followersa[0];
  501. Post poster = new Post(ToAddressType, ToAddress, comment, images);
  502. poster.post();
  503. }
  504. } catch (Exception e) {
  505. e.printStackTrace();
  506. }
  507. }
  508. try {
  509. String query = "";
  510. if (mid.equals(""))
  511. {
  512. query = "SELECT msgid, address, message FROM bm_table WHERE application='news' ORDER BY dtstamp DESC LIMIT 100 OFFSET " + Integer.toString(offset) + "";
  513. } else {
  514. query = "SELECT msgid, address, message FROM bm_table WHERE application='news' AND msgid='" + mid + "'";
  515. }
  516. ResultSet dbq = db.query(query);
  517. Object o = null;
  518. for (; dbq.next(); ) {
  519. o = dbq.getObject(1);
  520. String msgid = o.toString();
  521. o = dbq.getObject(2);
  522. String address = o.toString();
  523. o = dbq.getObject(3);
  524. String message = o.toString();
  525. response = response + "<br><div id='post'><div id='" + msgid + "'><a href='/profile?address=" + address + "'>" + address + "</a><br>";
  526. try {
  527. DocumentBuilderFactory dbFactory2 = DocumentBuilderFactory.newInstance();
  528. DocumentBuilder dBuilder2 = dbFactory2.newDocumentBuilder();
  529. Document doc2 = dBuilder2.parse(new ByteArrayInputStream(message.getBytes()));
  530. doc2.getDocumentElement().normalize();
  531. NodeList nList2 = doc2.getElementsByTagName("activity");
  532. String content = "";
  533. String image = "";
  534. int likes = 0;
  535. String likers = "";
  536. int commentnumber = 0;
  537. ArrayList<String> recipients = new ArrayList<String>();
  538. ArrayList<String> commenters = new ArrayList<String>();
  539. ArrayList<String> contents = new ArrayList<String>();
  540. for (int temp2 = 0; temp2 < nList2.getLength(); temp2++)
  541. {
  542. Node nNode2 = nList2.item(temp2);
  543. if (nNode2.getNodeType() == Node.ELEMENT_NODE)
  544. {
  545. Element eElement = (Element) nNode2;
  546. NodeList toNodeList = eElement.getElementsByTagName("to");
  547. for (int temp3 = 0; temp3 < toNodeList.getLength(); temp3++)
  548. {
  549. Node toCNode = toNodeList.item(temp3);
  550. Element toE = (Element) toCNode;
  551. NodeList toCNodeList = toE.getChildNodes();
  552. for (int temp4 = 0; temp4 < toCNodeList.getLength(); temp4++)
  553. {
  554. Node cnode = toCNodeList.item(temp4);
  555. if (cnode.getNodeName().equals("id"))
  556. {
  557. recipients.add(cnode.getTextContent());
  558. }
  559. }
  560. }
  561. NodeList objectNodeList = eElement.getElementsByTagName("object");
  562. for (int temp3 = 0; temp3 < objectNodeList.getLength(); temp3++)
  563. {
  564. Node objectCNode = objectNodeList.item(temp3);
  565. if (objectCNode.getNodeType() == Node.ELEMENT_NODE)
  566. {
  567. Element cElement = (Element) objectCNode;
  568. NodeList objectCNodeList = cElement.getChildNodes();
  569. for (int temp4=0; temp4<objectCNodeList.getLength(); temp4++)
  570. {
  571. Node cnode = objectCNodeList.item(temp4);
  572. if (cnode.getNodeName().equals("content"))
  573. {
  574. content = cElement.getElementsByTagName("content").item(temp3).getTextContent();
  575. content = content.replace("&", "&");
  576. content = content.replace("\"", """);
  577. content = content.replace("<", "<");
  578. content = content.replace(">", ">");
  579. response = response + "<pre>" + content + "</pre>";
  580. }
  581. }
  582. for (int temp4=0; temp4<objectCNodeList.getLength(); temp4++)
  583. {
  584. Node cnode = objectCNodeList.item(temp4);
  585. if (cnode.getNodeName().equals("image"))
  586. {
  587. image = cElement.getElementsByTagName("image").item(temp3).getTextContent();
  588. if (image.length() > 0)
  589. {
  590. response = response + "<div id='newsimage'><img src=\"" + image + "\"></div><br>";
  591. }
  592. }
  593. }
  594. for (int temp4=0; temp4<objectCNodeList.getLength(); temp4++)
  595. {
  596. Node cnode = objectCNodeList.item(temp4);
  597. if (cnode.getNodeName().equals("likes"))
  598. {
  599. likes = Integer.parseInt(cElement.getElementsByTagName("totalItems").item(0).getTextContent());
  600. Node itemsN = cElement.getElementsByTagName("items").item(0);
  601. Element itemsE = (Element) itemsN;
  602. NodeList itemNL = itemsE.getChildNodes();
  603. for (int temp5=0; temp5 < itemNL.getLength(); temp5++)
  604. {
  605. Node itemN = itemNL.item(temp5);
  606. Element itemE = (Element) itemN;
  607. Node actorN = itemE.getElementsByTagName("actor").item(0);
  608. Element actorE = (Element) actorN;
  609. likers = likers + actorE.getElementsByTagName("id").item(0).getTextContent() + "&#13;";
  610. }
  611. }
  612. }
  613. for (int temp4=0; temp4<objectCNodeList.getLength(); temp4++)
  614. {
  615. Node cnode = objectCNodeList.item(temp4);
  616. if (cnode.getNodeName().equals("comments"))
  617. {
  618. commentnumber = Integer.parseInt(cElement.getElementsByTagName("totalItems").item(0).getTextContent());
  619. }
  620. }
  621. response = response + "<a title='Liked by:&#13;" + likers + "' href='/?application=" + application + "&page=" + page + "&like=y&address=" + address + "&target=" + msgid + "&inReplyTo=" + msgid + "'>Like (" + likes + ")</a> <a href='javascript:movecomment_form(\"" + msgid + "\",\"form" + msgid + "\",\"comment_form" + msgid + "\",\"" + address + "\",\"" + msgid + "\",\"" + msgid + "\")'>Comment (" + commentnumber + ")</a>";
  622. for (int temp4=0; temp4<objectCNodeList.getLength(); temp4++)
  623. {
  624. Node cnode = objectCNodeList.item(temp4);
  625. if (cnode.getNodeName().equals("comments"))
  626. {
  627. commentnumber = Integer.parseInt(cElement.getElementsByTagName("totalItems").item(0).getTextContent());
  628. Node itemsN = cElement.getElementsByTagName("items").item(0);
  629. Element itemsE = (Element) itemsN;
  630. NodeList itemNL = itemsE.getChildNodes();
  631. for (int temp5=0; temp5 < itemNL.getLength(); temp5++)
  632. {
  633. int clikes = 0;
  634. String clikers = "";
  635. String commentID = "";
  636. Node itemN = itemNL.item(temp5);
  637. Element itemE = (Element) itemN;
  638. NodeList itemCNL = itemE.getChildNodes();
  639. for (int temp6 = 0; temp6<itemCNL.getLength(); temp6++)
  640. {
  641. Node itemCNode = itemCNL.item(temp6);
  642. if (itemCNode.getNodeName().equals("id"))
  643. {
  644. commentID = itemCNode.getTextContent();
  645. }
  646. }
  647. for (int temp6 = 0; temp6<itemCNL.getLength(); temp6++)
  648. {
  649. Node itemCNode = itemCNL.item(temp6);
  650. if (itemCNode.getNodeName().equals("actor"))
  651. {
  652. Node actorN = itemE.getElementsByTagName("actor").item(0);
  653. Element actorE = (Element) actorN;
  654. String commenter = actorE.getElementsByTagName("id").item(0).getTextContent();
  655. response = response + "<div id='comment'><div id='" + commentID +"'><a href='/profile?address=" + commenter + "'>" + commenter + "</a><br>";
  656. }
  657. }
  658. for (int temp6 = 0; temp6<itemCNL.getLength(); temp6++)
  659. {
  660. Node itemCNode = itemCNL.item(temp6);
  661. if (itemCNode.getNodeName().equals("content"))
  662. {
  663. String contento = itemE.getElementsByTagName("content").item(0).getTextContent();
  664. response = response + "<pre>" + contento + "</pre>";
  665. }
  666. }
  667. for (int temp6 = 0; temp6<itemCNL.getLength(); temp6++)
  668. {
  669. Node itemCNode = itemCNL.item(temp6);
  670. if (itemCNode.getNodeName().equals("likes"))
  671. {
  672. clikes = Integer.parseInt(itemE.getElementsByTagName("totalItems").item(0).getTextContent());
  673. Node itemsN2 = itemE.getElementsByTagName("items").item(0);
  674. Element itemsE2 = (Element) itemsN2;
  675. NodeList itemNL2 = itemsE2.getChildNodes();
  676. for (int itemno=0; itemno < itemNL2.getLength(); itemno++)
  677. {
  678. Node itemN2 = itemNL2.item(itemno);
  679. Element itemE2 = (Element) itemN2;
  680. Node actorN = itemE.getElementsByTagName("actor").item(0);
  681. Element actorE = (Element) actorN;
  682. clikers = clikers + actorE.getElementsByTagName("id").item(0).getTextContent() + "&#13;";
  683. }
  684. }
  685. }
  686. int commentnumber2 = 0;
  687. for (int temp6 = 0; temp6<itemCNL.getLength(); temp6++)
  688. {
  689. Node itemCNode = itemCNL.item(temp6);
  690. if (itemCNode.getNodeName().equals("comments"))
  691. {
  692. commentnumber2 = Integer.parseInt(itemE.getElementsByTagName("totalItems").item(0).getTextContent());
  693. }
  694. }
  695. response = response + "<a title='Liked by:&#13;" + clikers + "' href='/?application=" + application + "&page=" + page + "&like=y&address=" + address + "&target=" + msgid + "&inReplyTo=" + commentID + "'>Like (" + clikes + ")</a> <a href='javascript:movecomment_form(\"" + commentID + "\",\"form" + msgid + "\",\"comment_form" + msgid + "\",\"" + address + "\",\"" + msgid + "\",\"" + commentID + "\")'>Comment (" + commentnumber2 + ")</a>";
  696. for (int temp6 = 0; temp6<itemCNL.getLength(); temp6++)
  697. {
  698. Node itemCNode = itemCNL.item(temp6);
  699. if (itemCNode.getNodeName().equals("comments"))
  700. {
  701. Node itemsN2 = itemE.getElementsByTagName("items").item(0);
  702. Element itemsE2 = (Element) itemsN2;
  703. NodeList itemNL2 = itemsE2.getChildNodes();
  704. for (int itemno=0; itemno < itemNL2.getLength(); itemno++)
  705. {
  706. Node innode = itemNL2.item(itemno);
  707. response = processComment(innode, address, msgid, application, page, response);
  708. }
  709. }
  710. }
  711. response = response + "</div></div><br>";
  712. }
  713. }
  714. }
  715. }
  716. }
  717. }
  718. }
  719. response = response + "<div id='form" + msgid + "'><div id='comment_form'><form id='comment_form" + msgid + "' action='/' method='post' enctype='multipart/form-data'>";
  720. response = response + "<textarea name='comment' style='display:block;width:100%;left-margin:10px;right-margin:10px'></textarea><br>";
  721. response = response + "<input name='address' type='hidden' value='" + address + "'>";
  722. response = response + "<input name='targetid' type='hidden' value='" + msgid + "'>";
  723. response = response + "<input name='inreplytoid' type='hidden' value='" + msgid + "'>";
  724. response = response + "<input type='submit' value='Comment'>";
  725. bmasAddresses useraddress = new bmasAddresses();
  726. String user = useraddress.getChan();
  727. if ((address.equals(user)) || (recipients.contains(user)))
  728. {
  729. response = response + "<select name='comment_type'>";
  730. response = response + "<option value='Signed'>Signed</option>";
  731. response = response + "<option value='Anonymous'>Anonymous</option>";
  732. response = response + "<select>";
  733. } else {
  734. response = response + "<input name='comment_type' type='hidden' value='Signed'>";
  735. }
  736. response = response + "</form></div></div>";
  737. response = response + "</div></div>";
  738. } catch (Exception e) {
  739. e.printStackTrace();
  740. }
  741. }
  742. db.st.close();
  743. } catch (SQLException ex3) {
  744. ex3.printStackTrace();
  745. }
  746. }
  747. if (mid.equals(""))
  748. {
  749. response = response + "<p style=\"text-align:center\">";
  750. if (page > 1)
  751. {
  752. response = response + "<a href='/?application=" + application + "&page=1'>First</a> ";
  753. response = response + "<a href='/?application=" + application + "&page=" + (page - 1) + "'>Previous</a> ";
  754. }
  755. int opage = page;
  756. while ((opage <= page + 9) && (opage <= maxPages))
  757. {
  758. response = response + "<a href='/?application=" + application + "&page=" + opage + "'>" + opage + "</a> ";
  759. opage = opage + 1;
  760. }
  761. if (page < maxPages)
  762. {
  763. response = response + "<a href='/?application=" + application + "&page=" + (page + 1) + "'>Next</a> ";
  764. }
  765. response = response + "<a href='/?application=" + application + "&page=" + maxPages +"'>Last</a> ";
  766. response = response + "</p>";
  767. }
  768. html.append(response);
  769. html.appendEndDiv();
  770. html.appendEndBody();
  771. t.sendResponseHeaders(200, html.getHTML().length());
  772. OutputStream os = t.getResponseBody();
  773. os.write(html.getHTML().getBytes());
  774. os.close();
  775. }
  776. public String processComment(Node itemN, String address, String msgid, String application, int page, String response)
  777. {
  778. int clikes = 0;
  779. String clikers = "";
  780. String commentID = "";
  781. Element itemE = (Element) itemN;
  782. NodeList itemCNL = itemE.getChildNodes();
  783. for (int temp6 = 0; temp6<itemCNL.getLength(); temp6++)
  784. {
  785. Node itemCNode = itemCNL.item(temp6);
  786. if (itemCNode.getNodeName().equals("id"))
  787. {
  788. commentID = itemCNode.getTextContent();
  789. }
  790. }
  791. for (int temp6 = 0; temp6<itemCNL.getLength(); temp6++)
  792. {
  793. Node itemCNode = itemCNL.item(temp6);
  794. if (itemCNode.getNodeName().equals("actor"))
  795. {
  796. Node actorN = itemE.getElementsByTagName("actor").item(0);
  797. Element actorE = (Element) actorN;
  798. String commenter = actorE.getElementsByTagName("id").item(0).getTextContent();
  799. response = response + "<div id='comment'><div id='" + commentID +"'><a href='/profile?address=" + commenter + "'>" + commenter + "</a><br>";
  800. }
  801. }
  802. for (int temp6 = 0; temp6<itemCNL.getLength(); temp6++)
  803. {
  804. Node itemCNode = itemCNL.item(temp6);
  805. if (itemCNode.getNodeName().equals("content"))
  806. {
  807. String contento = itemE.getElementsByTagName("content").item(0).getTextContent();
  808. response = response + "<pre>" + contento + "</pre>";
  809. }
  810. }
  811. for (int temp6 = 0; temp6<itemCNL.getLength(); temp6++)
  812. {
  813. Node itemCNode = itemCNL.item(temp6);
  814. if (itemCNode.getNodeName().equals("likes"))
  815. {
  816. Node likesN = itemE.getElementsByTagName("likes").item(0);
  817. Element likesE = (Element) likesN;
  818. clikes = Integer.parseInt(likesE.getElementsByTagName("totalItems").item(0).getTextContent());
  819. Node itemsN2 = likesE.getElementsByTagName("items").item(0);
  820. Element itemsE2 = (Element) itemsN2;
  821. NodeList itemNL2 = itemsE2.getChildNodes();
  822. for (int itemno=0; itemno < itemNL2.getLength(); itemno++)
  823. {
  824. Node itemN2 = itemNL2.item(itemno);
  825. Element itemE2 = (Element) itemN2;
  826. Node actorN = itemE2.getElementsByTagName("actor").item(0);
  827. Element actorE = (Element) actorN;
  828. clikers = clikers + actorE.getElementsByTagName("id").item(0).getTextContent() + "&#13;";
  829. }
  830. }
  831. }
  832. int commentnumber2 = 0;
  833. for (int temp6 = 0; temp6<itemCNL.getLength(); temp6++)
  834. {
  835. Node itemCNode = itemCNL.item(temp6);
  836. if (itemCNode.getNodeName().equals("comments"))
  837. {
  838. Node commentsN2 = itemE.getElementsByTagName("comments").item(0);
  839. Element commentsE2 = (Element) commentsN2;
  840. commentnumber2 = Integer.parseInt(commentsE2.getElementsByTagName("totalItems").item(0).getTextContent());
  841. }
  842. }
  843. response = response + "<a title='Liked by:&#13;" + clikers + "' href='/?application=" + application + "&page=" + page + "&like=y&address=" + address + "&target=" + msgid + "&inReplyTo=" + commentID + "'>Like (" + clikes + ")</a> <a href='javascript:movecomment_form(\"" + commentID + "\",\"form" + msgid + "\",\"comment_form" + msgid + "\",\"" + address + "\",\"" + msgid + "\",\"" + commentID + "\")'>Comment (" + commentnumber2 + ")</a>";
  844. for (int temp6 = 0; temp6<itemCNL.getLength(); temp6++)
  845. {
  846. Node itemCNode = itemCNL.item(temp6);
  847. if (itemCNode.getNodeName().equals("comments"))
  848. {
  849. Node commentsN2 = itemE.getElementsByTagName("comments").item(0);
  850. Element commentsE2 = (Element) commentsN2;
  851. Node itemsN2 = commentsE2.getElementsByTagName("items").item(0);
  852. Element itemsE2 = (Element) itemsN2;
  853. NodeList itemNL2 = itemsE2.getChildNodes();
  854. for (int itemno=0; itemno < itemNL2.getLength(); itemno++)
  855. {
  856. Node itemo = itemNL2.item(itemno);
  857. response = processComment(itemo, address, msgid, application, page, response);
  858. }
  859. }
  860. }
  861. response = response + "</div></div><br>";
  862. return response;
  863. }
  864. }
  865. static class AlertsHandler implements HttpHandler
  866. {
  867. private ActivityStreamdb db = null;
  868. public AlertsHandler(ActivityStreamdb db) {
  869. this.db = db;
  870. }
  871. public void handle(HttpExchange t) throws IOException {
  872. String response = "";
  873. processMessages processor = new processMessages(db);
  874. processor.process();
  875. try {
  876. String INSERT_RECORD = "UPDATE bm_lastclick SET dtstamp=? WHERE wpage=?";
  877. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  878. java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
  879. pstmt.setTimestamp(1, sqlDate);
  880. pstmt.setString(2, "ALERTS");
  881. int i = pstmt.executeUpdate();
  882. if (i == -1) {
  883. System.out.println("db error : " );
  884. }
  885. pstmt.close();
  886. } catch (SQLException ex3) {
  887. ex3.printStackTrace();
  888. }
  889. HTMLBuilder html = new HTMLBuilder();
  890. html.appendDefaultStart();
  891. html.appendEndDiv();
  892. html.appendMainStart();
  893. @SuppressWarnings("unchecked")
  894. Map<String, Object> params = (Map<String, Object>)t.getAttribute("parameters");
  895. int offset = 0;
  896. int maxPages = 1;
  897. int page = 1;
  898. int count = 0;
  899. String csql = "SELECT COUNT(*) AS rowcount FROM bm_alerts";
  900. try {
  901. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  902. ResultSet rs = pstmt.executeQuery();
  903. rs.next();
  904. count = rs.getInt(1);
  905. pstmt.close();
  906. } catch (SQLException ex3) {
  907. ex3.printStackTrace();
  908. }
  909. maxPages = (count/100);
  910. if (maxPages*100 < count)
  911. {
  912. maxPages = maxPages + 1;
  913. }
  914. page = 1;
  915. if (params.containsKey("page"))
  916. {
  917. String spage = (String)params.get("page");
  918. page = Integer.parseInt(spage);
  919. }
  920. offset = (page*100) - 100;
  921. try {
  922. String query = "";
  923. query = "SELECT msgid, message, dtstamp FROM bm_alerts ORDER BY dtstamp DESC LIMIT 100 OFFSET " + Integer.toString(offset) + "";
  924. ResultSet dbq = db.query(query);
  925. Object o = null;
  926. for (; dbq.next(); ) {
  927. o = dbq.getObject(1);
  928. String msgid = o.toString();
  929. o = dbq.getObject(2);
  930. String message = o.toString();
  931. o = dbq.getObject(3);
  932. String datestamp = o.toString();
  933. String application = "";
  934. String query2 = "SELECT application FROM bm_table WHERE msgid='" + msgid +"'";
  935. ResultSet dbq2 = db.query(query2);
  936. Object o2 = null;
  937. for (; dbq2.next(); ) {
  938. o2 = dbq2.getObject(1);
  939. application = o2.toString();
  940. }
  941. response = response + "<br>";
  942. response = response + "<a href='/?application=" + application + "&msgid=" + msgid + "'>" + message + "</a> " + datestamp + "<br>";
  943. }
  944. db.st.close();
  945. } catch (SQLException ex3) {
  946. ex3.printStackTrace();
  947. }
  948. response = response + "<p style=\"text-align:center\">";
  949. if (page > 1)
  950. {
  951. response = response + "<a href='/alerts?page=1'>First</a> ";
  952. response = response + "<a href='/alerts?page=" + (page - 1) + "'>Previous</a> ";
  953. }
  954. int opage = page;
  955. while ((opage <= page + 9) && (opage <= maxPages))
  956. {
  957. response = response + "<a href='/alerts?page=" + opage + "'>" + opage + "</a> ";
  958. opage = opage + 1;
  959. }
  960. if (page < maxPages)
  961. {
  962. response = response + "<a href='/alerts?page=" + (page + 1) + "'>Next</a> ";
  963. }
  964. response = response + "<a href='/alerts?page=" + maxPages +"'>Last</a> ";
  965. response = response + "</p>";
  966. html.append(response);
  967. html.appendEndDiv();
  968. html.appendEndBody();
  969. t.sendResponseHeaders(200, html.getHTML().length());
  970. OutputStream os = t.getResponseBody();
  971. os.write(html.getHTML().getBytes());
  972. os.close();
  973. }
  974. }
  975. static class LogoutHandler implements HttpHandler
  976. {
  977. private ActivityStreamdb db = null;
  978. private HttpServer server = null;
  979. public LogoutHandler(ActivityStreamdb db, HttpServer server) {
  980. this.db = db;
  981. this.server = server;
  982. }
  983. public void handle(HttpExchange t) throws IOException {
  984. String response = "";
  985. HTMLBuilder html = new HTMLBuilder();
  986. html.appendHTMLHead();
  987. html.appendHTMLStyle();
  988. html.appendHTMLScript();
  989. html.appendHTMLHeadEnd();
  990. html.appendMainStart();
  991. html.append("<div style='text-align:center;'>GoodBye<div>");
  992. html.appendEndDiv();
  993. html.appendEndBody();
  994. t.sendResponseHeaders(200, html.getHTML().length());
  995. OutputStream os = t.getResponseBody();
  996. os.write(html.getHTML().getBytes());
  997. os.close();
  998. System.out.println("Database shutdown start");
  999. try {
  1000. db.shutdown();
  1001. } catch (Exception e) {
  1002. e.printStackTrace();
  1003. }
  1004. System.out.println("Database shutdown complete");
  1005. System.out.println("HttpServer shutdown start");
  1006. server.stop(0);
  1007. System.out.println("HttpServer shutdown complete");
  1008. }
  1009. }
  1010. static class SettingsHandler implements HttpHandler
  1011. {
  1012. private ActivityStreamdb db = null;
  1013. public SettingsHandler(ActivityStreamdb db) {
  1014. this.db = db;
  1015. }
  1016. public void handle(HttpExchange t) throws IOException {
  1017. String response = "";
  1018. String setting = "";
  1019. processMessages processor = new processMessages(db);
  1020. processor.process();
  1021. HTMLBuilder html = new HTMLBuilder();
  1022. html.appendDefaultStart();
  1023. html.appendSettingsLeftMenu();
  1024. html.appendEndDiv();
  1025. html.appendMainStart();
  1026. @SuppressWarnings("unchecked")
  1027. Map<String, Object> params = (Map<String, Object>)t.getAttribute("parameters");
  1028. if (params.containsKey("setting"))
  1029. {
  1030. setting = (String)params.get("setting");
  1031. }
  1032. if (t.getRequestMethod().equalsIgnoreCase("POST"))
  1033. {
  1034. InputStream is = t.getRequestBody();
  1035. stream2File fstream = new stream2File();
  1036. File tmpfile = fstream.getstream2file(is);
  1037. try {
  1038. DataSource ds = new FileDataSource(tmpfile);
  1039. FormdataMultipart forminput = new FormdataMultipart(ds);
  1040. Hashtable paramsa = forminput.getParameters();
  1041. if (paramsa.containsKey("add_hashtag"))
  1042. {
  1043. String[] hasharr = (String[])paramsa.get("hashtag_name");
  1044. String hashtag = hasharr[0];
  1045. String INSERT_RECORD = "INSERT INTO bm_settings(setting,value) VALUES(?,?)";
  1046. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1047. pstmt.setString(1, "hashtag");
  1048. pstmt.setString(2, hashtag);
  1049. int i = pstmt.executeUpdate();
  1050. if (i == -1) {
  1051. System.out.println("db error : " );
  1052. }
  1053. pstmt.close();
  1054. }
  1055. if (paramsa.containsKey("del_hashtag"))
  1056. {
  1057. String[] hasharr = (String[])paramsa.get("hashtag_name");
  1058. String hashtag = hasharr[0];
  1059. String INSERT_RECORD = "DELETE FROM bm_settings WHERE value=?";
  1060. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1061. pstmt.setString(1, hashtag);
  1062. int i = pstmt.executeUpdate();
  1063. if (i == -1) {
  1064. System.out.println("db error : " );
  1065. }
  1066. pstmt.close();
  1067. }
  1068. if (paramsa.containsKey("upd_bmapi"))
  1069. {
  1070. String[] bmapi_iparr = (String[])paramsa.get("bmapi_ip");
  1071. String bmapi_ip = bmapi_iparr[0];
  1072. String INSERT_RECORD = "UPDATE bm_settings SET value=? WHERE setting=?";
  1073. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1074. pstmt.setString(1, bmapi_ip);
  1075. pstmt.setString(2, "bmapi_ip");
  1076. int i = pstmt.executeUpdate();
  1077. if (i == -1) {
  1078. System.out.println("db error : " );
  1079. }
  1080. pstmt.close();
  1081. String[] bmapi_portarr = (String[])paramsa.get("bmapi_port");
  1082. String bmapi_port = bmapi_portarr[0];
  1083. INSERT_RECORD = "UPDATE bm_settings SET value=? WHERE setting=?";
  1084. pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1085. pstmt.setString(1, bmapi_port);
  1086. pstmt.setString(2, "bmapi_port");
  1087. i = pstmt.executeUpdate();
  1088. if (i == -1) {
  1089. System.out.println("db error : " );
  1090. }
  1091. pstmt.close();
  1092. String[] bmapi_userarr = (String[])paramsa.get("bmapi_user");
  1093. String bmapi_user = bmapi_userarr[0];
  1094. INSERT_RECORD = "UPDATE bm_settings SET value=? WHERE setting=?";
  1095. pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1096. pstmt.setString(1, bmapi_user);
  1097. pstmt.setString(2, "bmapi_user");
  1098. i = pstmt.executeUpdate();
  1099. if (i == -1) {
  1100. System.out.println("db error : " );
  1101. }
  1102. pstmt.close();
  1103. String[] bmapi_passwordarr = (String[])paramsa.get("bmapi_password");
  1104. String bmapi_password = bmapi_passwordarr[0];
  1105. INSERT_RECORD = "UPDATE bm_settings SET value=? WHERE setting=?";
  1106. pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1107. pstmt.setString(1, bmapi_password);
  1108. pstmt.setString(2, "bmapi_password");
  1109. i = pstmt.executeUpdate();
  1110. if (i == -1) {
  1111. System.out.println("db error : " );
  1112. }
  1113. pstmt.close();
  1114. String[] bmapi_clientarr = (String[])paramsa.get("bmapi_client");
  1115. String bmapi_client = bmapi_clientarr[0];
  1116. INSERT_RECORD = "UPDATE bm_settings SET value=? WHERE setting=?";
  1117. pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1118. pstmt.setString(1, bmapi_client);
  1119. pstmt.setString(2, "bmapi_client");
  1120. i = pstmt.executeUpdate();
  1121. if (i == -1) {
  1122. System.out.println("db error : " );
  1123. }
  1124. pstmt.close();
  1125. }
  1126. } catch (Exception e) {
  1127. e.printStackTrace();
  1128. }
  1129. }
  1130. if (setting.equals("hashtags"))
  1131. {
  1132. response = response + "<form name='add_hashtag' action='/settings?setting=" + setting + "' method='post' enctype='multipart/form-data'>";
  1133. response = response + "Hashtag:<br><input name=hashtag_name><br>";
  1134. response = response + "<input type=submit name='add_hashtag' value='Add Hashtag'>";
  1135. response = response + "</form>";
  1136. response = response + "<br>";
  1137. response = response + "<form name='del_hashtag' action='/settings?setting=" + setting + "' method='post' enctype='multipart/form-data'>";
  1138. response = response + "Hashtag Name:<br><select name=hashtag_name>";
  1139. try {
  1140. String query = "SELECT value FROM bm_settings WHERE setting='hashtag'";
  1141. ResultSet dbq = db.query(query);
  1142. Object o = null;
  1143. for (; dbq.next(); ) {
  1144. o = dbq.getObject(1);
  1145. String hashtag = (String)o;
  1146. response = response + "<option value='" + hashtag + "'>" + hashtag + "</option>";
  1147. }
  1148. } catch (SQLException ex3) {
  1149. ex3.printStackTrace();
  1150. }
  1151. response = response + "</select>";
  1152. response = response + "<br><input type=submit name='del_hashtag' value='Delete Hashtag'>";
  1153. response = response + "</form>";
  1154. }
  1155. if (setting.equals("bm_api"))
  1156. {
  1157. response = response + "<form name='upd_bmapi' action='/settings?setting=" + setting + "' method='post' enctype='multipart/form-data'>";
  1158. try {
  1159. String query = "SELECT value FROM bm_settings WHERE setting='bmapi_ip'";
  1160. ResultSet dbq = db.query(query);
  1161. Object o = null;
  1162. for (; dbq.next(); ) {
  1163. o = dbq.getObject(1);
  1164. String bmapi_ip = (String)o;
  1165. response = response + "BM API Host:<br><input name=bmapi_ip value='" + bmapi_ip + "'><br>";
  1166. }
  1167. } catch (SQLException ex3) {
  1168. ex3.printStackTrace();
  1169. }
  1170. try {
  1171. String query = "SELECT value FROM bm_settings WHERE setting='bmapi_port'";
  1172. ResultSet dbq = db.query(query);
  1173. Object o = null;
  1174. for (; dbq.next(); ) {
  1175. o = dbq.getObject(1);
  1176. String bmapi_port = (String)o;
  1177. response = response + "BM API Port Number:<br><input name=bmapi_port value='" + bmapi_port + "'><br>";
  1178. }
  1179. } catch (SQLException ex3) {
  1180. ex3.printStackTrace();
  1181. }
  1182. try {
  1183. String query = "SELECT value FROM bm_settings WHERE setting='bmapi_user'";
  1184. ResultSet dbq = db.query(query);
  1185. Object o = null;
  1186. for (; dbq.next(); ) {
  1187. o = dbq.getObject(1);
  1188. String bmapi_user = (String)o;
  1189. response = response + "BM API User:<br><input name=bmapi_user value='" + bmapi_user + "'><br>";
  1190. }
  1191. } catch (SQLException ex3) {
  1192. ex3.printStackTrace();
  1193. }
  1194. try {
  1195. String query = "SELECT value FROM bm_settings WHERE setting='bmapi_password'";
  1196. ResultSet dbq = db.query(query);
  1197. Object o = null;
  1198. for (; dbq.next(); ) {
  1199. o = dbq.getObject(1);
  1200. String bmapi_password = (String)o;
  1201. response = response + "BM API Password:<br><input type=password name=bmapi_password value='" + bmapi_password + "'><br>";
  1202. }
  1203. } catch (SQLException ex3) {
  1204. ex3.printStackTrace();
  1205. }
  1206. try {
  1207. String query = "SELECT value FROM bm_settings WHERE setting='bmapi_client'";
  1208. ResultSet dbq = db.query(query);
  1209. Object o = null;
  1210. for (; dbq.next(); ) {
  1211. o = dbq.getObject(1);
  1212. String bmapi_client = (String)o;
  1213. if (bmapi_client.equals("false"))
  1214. {
  1215. response = response + "Use browser interface as mail client<input type='radio' name='bmapi_client' value='false' checked />No<input type='radio' name='bmapi_client' value='true' />Yes<br>";
  1216. } else {
  1217. response = response + "Use browser interface as mail client<input type='radio' name='bmapi_client' value='false' />No<input type='radio' name='bmapi_client' value='true' checked />Yes<br>";
  1218. }
  1219. }
  1220. } catch (SQLException ex3) {
  1221. ex3.printStackTrace();
  1222. }
  1223. response = response + "<input type=submit name='upd_bmapi' value='Update'>";
  1224. response = response + "</form>";
  1225. }
  1226. html.append(response);
  1227. html.appendEndDiv();
  1228. html.appendEndBody();
  1229. t.sendResponseHeaders(200, html.getHTML().length());
  1230. OutputStream os = t.getResponseBody();
  1231. os.write(html.getHTML().getBytes());
  1232. os.close();
  1233. }
  1234. }
  1235. static class MessagesHandler implements HttpHandler
  1236. {
  1237. private ActivityStreamdb db = null;
  1238. public MessagesHandler(ActivityStreamdb db) {
  1239. this.db = db;
  1240. }
  1241. public void handle(HttpExchange t) throws IOException {
  1242. String response = "";
  1243. processMessages processor = new processMessages(db);
  1244. processor.process();
  1245. try {
  1246. String INSERT_RECORD = "UPDATE bm_lastclick SET dtstamp=? WHERE wpage=?";
  1247. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1248. java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
  1249. pstmt.setTimestamp(1, sqlDate);
  1250. pstmt.setString(2, "MESSAGES");
  1251. int i = pstmt.executeUpdate();
  1252. if (i == -1) {
  1253. System.out.println("db error : " );
  1254. }
  1255. pstmt.close();
  1256. } catch (SQLException ex3) {
  1257. ex3.printStackTrace();
  1258. }
  1259. if (t.getRequestMethod().equalsIgnoreCase("POST"))
  1260. {
  1261. InputStream is = t.getRequestBody();
  1262. String mfolder = "";
  1263. String mread = "";
  1264. stream2File fstream = new stream2File();
  1265. File tmpfile = fstream.getstream2file(is);
  1266. try {
  1267. DataSource ds = new FileDataSource(tmpfile);
  1268. FormdataMultipart forminput = new FormdataMultipart(ds);
  1269. Hashtable params = forminput.getParameters();
  1270. if (params.containsKey("bmove_folder"))
  1271. {
  1272. String[] mfolderarr = (String[])params.get("move_folder");
  1273. mfolder = mfolderarr[0];
  1274. String[] mmsgid = (String[])params.get("chkmsg");
  1275. for (int i=0; i<mmsgid.length; i++)
  1276. {
  1277. try {
  1278. String INSERT_RECORD = "UPDATE bm_mail SET folder=? WHERE msgid=?";
  1279. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1280. pstmt.setString(1, mfolder);
  1281. pstmt.setString(2, mmsgid[i]);
  1282. int d = pstmt.executeUpdate();
  1283. if (d == -1) {
  1284. System.out.println("db error : " );
  1285. }
  1286. pstmt.close();
  1287. } catch (SQLException ex3) {
  1288. ex3.printStackTrace();
  1289. }
  1290. }
  1291. }
  1292. if (params.containsKey("empty_trash"))
  1293. {
  1294. try {
  1295. String INSERT_RECORD = "DELETE FROM bm_mail WHERE folder=?";
  1296. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1297. pstmt.setString(1, "Trash");
  1298. int d = pstmt.executeUpdate();
  1299. if (d == -1) {
  1300. System.out.println("db error : " );
  1301. }
  1302. pstmt.close();
  1303. } catch (SQLException ex3) {
  1304. ex3.printStackTrace();
  1305. }
  1306. }
  1307. if (params.containsKey("bmark_read"))
  1308. {
  1309. String[] mreadarr = (String[])params.get("set_read");
  1310. mread = mreadarr[0];
  1311. String[] mmsgid = (String[])params.get("chkmsg");
  1312. for (int i=0; i<mmsgid.length; i++)
  1313. {
  1314. try {
  1315. String INSERT_RECORD = "UPDATE bm_mail SET read=? WHERE msgid=?";
  1316. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1317. pstmt.setBoolean(1, Boolean.parseBoolean(mread));
  1318. pstmt.setString(2, mmsgid[i]);
  1319. int d = pstmt.executeUpdate();
  1320. if (d == -1) {
  1321. System.out.println("db error : " );
  1322. }
  1323. pstmt.close();
  1324. } catch (SQLException ex3) {
  1325. ex3.printStackTrace();
  1326. }
  1327. }
  1328. }
  1329. if (params.containsKey("bfolder"))
  1330. {
  1331. String[] mfolderarr = (String[])params.get("folder");
  1332. mfolder = mfolderarr[0];
  1333. try {
  1334. String INSERT_RECORD = "INSERT INTO bm_mail_folders(folder) VALUES(?)";
  1335. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1336. pstmt.setString(1, mfolder);
  1337. int i = pstmt.executeUpdate();
  1338. if (i == -1) {
  1339. System.out.println("db error : " );
  1340. }
  1341. pstmt.close();
  1342. } catch (SQLException ex3) {
  1343. ex3.printStackTrace();
  1344. }
  1345. }
  1346. } catch (Exception e) {
  1347. e.printStackTrace();
  1348. }
  1349. }
  1350. HTMLBuilder html = new HTMLBuilder();
  1351. html.appendDefaultStart();
  1352. html.appendMailLeftMenu();
  1353. html.appendEndDiv();
  1354. html.appendMainStart();
  1355. @SuppressWarnings("unchecked")
  1356. Map<String, Object> params = (Map<String, Object>)t.getAttribute("parameters");
  1357. String folder = "Inbox";
  1358. if (params.containsKey("folder"))
  1359. {
  1360. folder = (String)params.get("folder");
  1361. }
  1362. int count = 0;
  1363. String csql = "SELECT COUNT(*) AS rowcount FROM bm_mail WHERE folder=?";
  1364. try {
  1365. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  1366. pstmt.setString(1, folder);
  1367. ResultSet rs = pstmt.executeQuery();
  1368. rs.next();
  1369. count = rs.getInt(1);
  1370. pstmt.close();
  1371. } catch (SQLException ex3) {
  1372. ex3.printStackTrace();
  1373. }
  1374. int maxPages = (count/100);
  1375. if (maxPages*100 < count)
  1376. {
  1377. maxPages = maxPages + 1;
  1378. }
  1379. int page = 1;
  1380. if (params.containsKey("page"))
  1381. {
  1382. String spage = (String)params.get("page");
  1383. page = Integer.parseInt(spage);
  1384. }
  1385. int offset = (page*100) - 100;
  1386. if (!folder.equals("Sent"))
  1387. {
  1388. if (folder.equals(""))
  1389. {
  1390. folder = "Inbox";
  1391. }
  1392. response = response + "<form name='move' action='/messages' method='post' enctype='multipart/form-data'>";
  1393. response = response + "<input type='submit' name='bmove_folder' value='Move selected to:'>";
  1394. response = response + "<select name='move_folder'>";
  1395. try {
  1396. ResultSet dbq = db.query("SELECT folder FROM bm_mail_folders");
  1397. Object o = null;
  1398. for (; dbq.next(); ) {
  1399. o = dbq.getObject(1);
  1400. String mfolder = o.toString();
  1401. response = response + "<option value='" + mfolder + "'>" + mfolder + "</option>";
  1402. }
  1403. db.st.close();
  1404. } catch (SQLException ex3) {
  1405. ex3.printStackTrace();
  1406. }
  1407. response = response + "</select>";
  1408. response = response + "<input type='submit' name='bmark_read' value='Mark selected:'>";
  1409. response = response + "<select name='set_read'>";
  1410. response = response + "<option value='true'>Read</option>";
  1411. response = response + "<option value='false'>Unread</option>";
  1412. response = response + "</select>";
  1413. response = response + "<input type='submit' name='empty_trash' value='Empty Trash'>";
  1414. response = response + "<table width=\"100%\"><thead><th><input align='left' type='checkbox' onClick='toggle(this)' name='chkmsg'></th><th>Sender</th><th>Subject</th><th>Received at</th></thead><tbody>";
  1415. int i = 0;
  1416. try {
  1417. String query = "SELECT msgid, read, subject, fromaddress, dtstamp FROM bm_mail WHERE folder='" + folder + "' ORDER BY dtstamp DESC LIMIT 100 OFFSET " + Integer.toString(offset) + "";
  1418. ResultSet dbq = db.query(query);
  1419. Object o = null;
  1420. for (; dbq.next(); ) {
  1421. response = response + "<tr>";
  1422. String meh = "";
  1423. o = dbq.getObject(1);
  1424. String ref = o.toString();
  1425. response = response + "<td><input type='checkbox' name='chkmsg' value='" + ref + "'></td>";
  1426. o = dbq.getObject(2);
  1427. Boolean mread = (Boolean)o;
  1428. o = dbq.getObject(4);
  1429. meh = o.toString();
  1430. response = response + "<td><a href='/message?msgid=" + ref + "'>";
  1431. if (!mread)
  1432. {
  1433. response = response + "<b>";
  1434. }
  1435. response = response + meh;
  1436. if (!mread)
  1437. {
  1438. response = response + "</b>";
  1439. }
  1440. response = response + "</a></td>";
  1441. o = dbq.getObject(3);
  1442. meh = o.toString();
  1443. byte[] decoded = Base64.decodeBase64(meh);
  1444. String meh2 = null;
  1445. try {
  1446. meh2 = new String(decoded, "UTF-8");
  1447. } catch (Exception e) {
  1448. e.printStackTrace();
  1449. }
  1450. response = response + "<td><a href='/message?msgid=" + ref + "'>";
  1451. if (!mread)
  1452. {
  1453. response = response + "<b>";
  1454. }
  1455. meh2 = meh2.replaceAll("<", "<");
  1456. meh2 = meh2.replaceAll(">", ">");
  1457. response = response + meh2;
  1458. if (!mread)
  1459. {
  1460. response = response + "</b>";
  1461. }
  1462. response = response + "</a></td>";
  1463. o = dbq.getObject(5);
  1464. meh = o.toString();
  1465. response = response + "<td width='150px'><a href='/message?msgid=" + ref + "'>";
  1466. if (!mread)
  1467. {
  1468. response = response + "<b>";
  1469. }
  1470. response = response + meh;
  1471. if (!mread)
  1472. {
  1473. response = response + "</b>";
  1474. }
  1475. response = response + "</a></td>";
  1476. response = response + "</tr>";
  1477. i++;
  1478. }
  1479. db.st.close();
  1480. } catch (SQLException ex3) {
  1481. ex3.printStackTrace();
  1482. }
  1483. } else {
  1484. if (folder.equals(""))
  1485. {
  1486. folder = "Inbox";
  1487. }
  1488. response = response + "<form name='move' action='/messages' method='post' enctype='multipart/form-data'>";
  1489. response = response + "<input type='submit' name='bmove_folder' value='Move selected to:'>";
  1490. response = response + "<select name='move_folder'>";
  1491. try {
  1492. ResultSet dbq = db.query("SELECT folder FROM bm_mail_folders");
  1493. Object o = null;
  1494. for (; dbq.next(); ) {
  1495. o = dbq.getObject(1);
  1496. String mfolder = o.toString();
  1497. response = response + "<option value='" + mfolder + "'>" + mfolder + "</option>";
  1498. }
  1499. db.st.close();
  1500. } catch (SQLException ex3) {
  1501. ex3.printStackTrace();
  1502. }
  1503. response = response + "</select>";
  1504. response = response + "<input type='submit' name='bmark_read' value='Mark selected:'>";
  1505. response = response + "<select name='set_read'>";
  1506. response = response + "<option value='true'>Read</option>";
  1507. response = response + "<option value='false'>Unread</option>";
  1508. response = response + "</select>";
  1509. response = response + "<input type='submit' name='empty_trash' value='Empty Trash'>";
  1510. response = response + "<table width=\"100%\"><thead><th><input align='left' type='checkbox' onClick='toggle(this)' name='chkmsg'></th><th>Sender</th><th>Subject</th><th>Received at</th></thead><tbody>";
  1511. int i = 0;
  1512. try {
  1513. String query = "SELECT msgid, read, subject, fromaddress, dtstamp, ackdata FROM bm_mail WHERE folder='" + folder + "' ORDER BY dtstamp DESC LIMIT 100 OFFSET " + Integer.toString(offset) + "";
  1514. ResultSet dbq = db.query(query);
  1515. Object o = null;
  1516. for (; dbq.next(); ) {
  1517. response = response + "<tr>";
  1518. String meh = "";
  1519. o = dbq.getObject(1);
  1520. String ref = o.toString();
  1521. o = dbq.getObject(6);
  1522. String ref2 = o.toString();
  1523. if (!ref.equals("null"))
  1524. {
  1525. response = response + "<td><input type='checkbox' name='chkmsg' value='" + ref + "'></td>";
  1526. } else {
  1527. response = response + "<td></td>";
  1528. }
  1529. o = dbq.getObject(2);
  1530. Boolean mread = (Boolean)o;
  1531. o = dbq.getObject(4);
  1532. meh = o.toString();
  1533. response = response + "<td>";
  1534. if (!ref.equals("null"))
  1535. {
  1536. response = response + "<a href='/message?msgid=" + ref + "'>";
  1537. }
  1538. if (!mread)
  1539. {
  1540. response = response + "<b>";
  1541. }
  1542. response = response + meh;
  1543. if (!mread)
  1544. {
  1545. response = response + "</b>";
  1546. }
  1547. if (!ref.equals("null"))
  1548. {
  1549. response = response + "</a>";
  1550. }
  1551. response = response + "</td>";
  1552. o = dbq.getObject(3);
  1553. meh = o.toString();
  1554. byte[] decoded = Base64.decodeBase64(meh);
  1555. String meh2 = null;
  1556. try {
  1557. meh2 = new String(decoded, "UTF-8");
  1558. } catch (Exception e) {
  1559. e.printStackTrace();
  1560. }
  1561. response = response + "<td>";
  1562. if (!ref.equals("null"))
  1563. {
  1564. response = response + "<a href='/message?msgid=" + ref + "'>";
  1565. }
  1566. if (!mread)
  1567. {
  1568. response = response + "<b>";
  1569. }
  1570. meh2 = meh2.replaceAll("<", "<");
  1571. meh2 = meh2.replaceAll(">", ">");
  1572. response = response + meh2;
  1573. if (!mread)
  1574. {
  1575. response = response + "</b>";
  1576. }
  1577. if (!ref.equals("null"))
  1578. {
  1579. response = response + "</a>";
  1580. }
  1581. response = response + "</td>";
  1582. o = dbq.getObject(5);
  1583. meh = o.toString();
  1584. response = response + "<td width='150px'>";
  1585. if (!ref.equals("null"))
  1586. {
  1587. response = response + "<a href='/message?msgid=" + ref + "'>";
  1588. }
  1589. if (!mread)
  1590. {
  1591. response = response + "<b>";
  1592. }
  1593. response = response + meh;
  1594. if (!mread)
  1595. {
  1596. response = response + "</b>";
  1597. }
  1598. if (!ref.equals("null"))
  1599. {
  1600. response = response + "</a>";
  1601. }
  1602. response = response + "</td>";
  1603. response = response + "</tr>";
  1604. i++;
  1605. }
  1606. db.st.close();
  1607. } catch (SQLException ex3) {
  1608. ex3.printStackTrace();
  1609. }
  1610. }
  1611. response = response + "</tbody></table>";
  1612. response = response + "</form>";
  1613. response = response + "<p style=\"text-align:center\">";
  1614. if (page > 1)
  1615. {
  1616. response = response + "<a href='/messages?folder=" + folder + "&page=1'>First</a> ";
  1617. response = response + "<a href='/messages?folder=" + folder + "&page=" + (page - 1) + "'>Previous</a> ";
  1618. }
  1619. int opage = page;
  1620. while ((opage <= page + 9) && (opage <= maxPages))
  1621. {
  1622. response = response + "<a href='/messages?folder=" + folder + "&page=" + opage + "'>" + opage + "</a> ";
  1623. opage = opage + 1;
  1624. }
  1625. if (page < maxPages)
  1626. {
  1627. response = response + "<a href='/messages?folder=" + folder + "&page=" + (page + 1) + "'>Next</a> ";
  1628. }
  1629. response = response + "<a href='/messages?folder=" + folder + "&page=" + maxPages +"'>Last</a> ";
  1630. response = response + "</p>";
  1631. response = response + "</div>";
  1632. response = response + "</body></html>";
  1633. html.append(response);
  1634. t.sendResponseHeaders(200, html.getHTML().length());
  1635. OutputStream os = t.getResponseBody();
  1636. os.write(html.getHTML().getBytes());
  1637. os.close();
  1638. }
  1639. }
  1640. static class MessageHandler implements HttpHandler
  1641. {
  1642. private ActivityStreamdb db = null;
  1643. public MessageHandler(ActivityStreamdb db) {
  1644. this.db = db;
  1645. }
  1646. public void handle(HttpExchange t) throws IOException {
  1647. String response = "";
  1648. String msgid="";
  1649. @SuppressWarnings("unchecked")
  1650. Map<String, Object> params = (Map<String, Object>)t.getAttribute("parameters");
  1651. msgid = (String)params.get("msgid");
  1652. if (t.getRequestMethod().equalsIgnoreCase("POST"))
  1653. {
  1654. InputStream is = t.getRequestBody();
  1655. String mfolder = "";
  1656. stream2File fstream = new stream2File();
  1657. File tmpfile = fstream.getstream2file(is);
  1658. try {
  1659. DataSource ds = new FileDataSource(tmpfile);
  1660. FormdataMultipart forminput = new FormdataMultipart(ds);
  1661. Hashtable paramsa = forminput.getParameters();
  1662. if (paramsa.containsKey("bmove_folder"))
  1663. {
  1664. String[] mfolderarr = (String[])paramsa.get("move_folder");
  1665. mfolder = mfolderarr[0];
  1666. String INSERT_RECORD = "UPDATE bm_mail SET folder=? WHERE msgid=?";
  1667. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1668. pstmt.setString(1, mfolder);
  1669. pstmt.setString(2, msgid);
  1670. int d = pstmt.executeUpdate();
  1671. if (d == -1) {
  1672. System.out.println("db error : " );
  1673. }
  1674. pstmt.close();
  1675. }
  1676. if (paramsa.containsKey("add_address"))
  1677. {
  1678. String[] addressarr = (String[])paramsa.get("address");
  1679. String address = addressarr[0];
  1680. String INSERT_RECORD = "INSERT INTO bm_profiles(address,following,follower,dtstamp) VALUES(?,?,?,?)";
  1681. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  1682. pstmt.setString(1, address);
  1683. pstmt.setBoolean(2, false);
  1684. pstmt.setBoolean(3, false);
  1685. java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
  1686. pstmt.setTimestamp(4, sqlDate);
  1687. int d = pstmt.executeUpdate();
  1688. if (d == -1) {
  1689. System.out.println("db error : " );
  1690. }
  1691. pstmt.close();
  1692. }
  1693. } catch (Exception e) {
  1694. e.printStackTrace();
  1695. }
  1696. }
  1697. try {
  1698. String UPDATE_RECORD = "UPDATE bm_mail SET read=? WHERE msgid=?";
  1699. PreparedStatement pstmtu = db.conn.prepareStatement(UPDATE_RECORD);
  1700. pstmtu.setBoolean(1, true);
  1701. pstmtu.setString(2, msgid);
  1702. int du = pstmtu.executeUpdate();
  1703. if (du == -1) {
  1704. System.out.println("db error : " );
  1705. }
  1706. pstmtu.close();
  1707. } catch (Exception e) {
  1708. e.printStackTrace();
  1709. }
  1710. processMessages processor = new processMessages(db);
  1711. processor.process();
  1712. HTMLBuilder html = new HTMLBuilder();
  1713. html.appendDefaultStart();
  1714. html.appendMailLeftMenu();
  1715. html.appendEndDiv();
  1716. html.appendMainStart();
  1717. response = response + "<table><tr><td>";
  1718. response = response + "<form name='send' action='/send_message' method='post' enctype='multipart/form-data'>";
  1719. response = response + "<input type='hidden' name='msgid' value='" + msgid + "'>";
  1720. response = response + "<input type='submit' name='send' value='Reply'>";
  1721. response = response + "<input type='submit' name='send' value='Forward'>";
  1722. response = response + "</form><td>";
  1723. response = response + "<td><form name='move' action='/message?msgid=" + msgid + "' method='post' enctype='multipart/form-data'>";
  1724. response = response + "<input type='submit' name='bmove_folder' value='Move selected to:'>";
  1725. response = response + "<select name='move_folder'>";
  1726. try {
  1727. ResultSet dbq = db.query("SELECT folder FROM bm_mail_folders");
  1728. Object o = null;
  1729. for (; dbq.next(); ) {
  1730. o = dbq.getObject(1);
  1731. String mfolder = o.toString();
  1732. response = response + "<option value='" + mfolder + "'>" + mfolder + "</option>";
  1733. }
  1734. db.st.close();
  1735. } catch (SQLException ex3) {
  1736. ex3.printStackTrace();
  1737. }
  1738. response = response + "</select>";
  1739. response = response + "</form></td>";
  1740. response = response + "</tr></table>";
  1741. try {
  1742. String qstring = "SELECT toaddress, fromaddress, subject, message FROM bm_mail WHERE msgid='" + msgid + "'";
  1743. ResultSet dbq = db.query(qstring);
  1744. Object o = null;
  1745. for (; dbq.next(); ) {
  1746. response = response + "<div>TO: ";
  1747. o = dbq.getObject(1);
  1748. String meh = o.toString();
  1749. response = response + meh + "</div><br>";
  1750. response = response + "<div>FROM: ";
  1751. o = dbq.getObject(2);
  1752. meh = o.toString();
  1753. response = response + meh + "</div>";
  1754. int count = 0;
  1755. String csql = "SELECT COUNT(*) AS rowcount FROM bm_profiles WHERE address=?";
  1756. try {
  1757. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  1758. pstmt.setString(1, meh);
  1759. ResultSet rs = pstmt.executeQuery();
  1760. rs.next();
  1761. count = rs.getInt(1);
  1762. pstmt.close();
  1763. } catch (SQLException ex3) {
  1764. ex3.printStackTrace();
  1765. }
  1766. if (count == 0)
  1767. {
  1768. response = response + "<form name='profile' action='/message?msgid=" + msgid + "' method='post' enctype='multipart/form-data'>";
  1769. response = response + "<input type='hidden' name='address' value='" + meh + "'>";
  1770. response = response + "<input type='submit' name='add_address' value='Add to address book'>";
  1771. response = response + "</form>";
  1772. }
  1773. response = response + "<br>";
  1774. response = response + "<div>SUBJECT: ";
  1775. o = dbq.getObject(3);
  1776. meh = o.toString();
  1777. byte[] decoded = Base64.decodeBase64(meh);
  1778. String meh2 = null;
  1779. try {
  1780. meh2 = new String(decoded, "UTF-8");
  1781. } catch (Exception e) {
  1782. e.printStackTrace();
  1783. }
  1784. response = response + meh2 + "</div><br>";
  1785. response = response + "<div>MESSAGE: <pre>";
  1786. o = dbq.getObject(4);
  1787. meh = o.toString();
  1788. decoded = Base64.decodeBase64(meh);
  1789. meh2 = null;
  1790. try {
  1791. meh2 = new String(decoded, "UTF-8");
  1792. } catch (Exception e) {
  1793. e.printStackTrace();
  1794. }
  1795. meh2 = meh2.replace("&", "&");
  1796. meh2 = meh2.replace("\"", """);
  1797. meh2 = meh2.replace("<", "<");
  1798. meh2 = meh2.replace(">", ">");
  1799. response = response + meh2 + "</pre></div><br>";
  1800. }
  1801. db.st.close();
  1802. } catch (SQLException ex3) {
  1803. ex3.printStackTrace();
  1804. }
  1805. response = response + "</div></body></html>";
  1806. html.append(response);
  1807. t.sendResponseHeaders(200, html.getHTML().length());
  1808. OutputStream os = t.getResponseBody();
  1809. os.write(html.getHTML().getBytes());
  1810. os.close();
  1811. }
  1812. }
  1813. static class SendMessageHandler implements HttpHandler
  1814. {
  1815. private ActivityStreamdb db = null;
  1816. public SendMessageHandler(ActivityStreamdb db) {
  1817. this.db = db;
  1818. }
  1819. public void handle(HttpExchange t) throws IOException {
  1820. String To = "";
  1821. String From = "";
  1822. String Subject = "";
  1823. String Message = "";
  1824. @SuppressWarnings("unchecked")
  1825. Map<String, Object> params = (Map<String, Object>)t.getAttribute("parameters");
  1826. if (t.getRequestMethod().equalsIgnoreCase("GET"))
  1827. {
  1828. if (params.size() > 0)
  1829. {
  1830. To = (String)params.get("To");
  1831. From = (String)params.get("From");
  1832. Subject = (String)params.get("Subject");
  1833. Message = (String)params.get("Message");
  1834. }
  1835. }
  1836. if (t.getRequestMethod().equalsIgnoreCase("POST"))
  1837. {
  1838. InputStream is = t.getRequestBody();
  1839. stream2File fstream = new stream2File();
  1840. File tmpfile = fstream.getstream2file(is);
  1841. try {
  1842. DataSource ds = new FileDataSource(tmpfile);
  1843. FormdataMultipart forminput = new FormdataMultipart(ds);
  1844. Hashtable paramsa = forminput.getParameters();
  1845. if (paramsa.containsKey("send"))
  1846. {
  1847. try {
  1848. String[] msgida = (String[])paramsa.get("msgid");
  1849. String[] senda = (String[])paramsa.get("send");
  1850. String qstring = "SELECT toaddress, fromaddress, subject, message FROM bm_mail WHERE msgid='" + msgida[0] + "'";
  1851. ResultSet dbq = db.query(qstring);
  1852. Object o = null;
  1853. for (; dbq.next(); ) {
  1854. if (senda[0].equals("Reply"))
  1855. {
  1856. o = dbq.getObject(2);
  1857. To = o.toString();
  1858. }
  1859. o = dbq.getObject(3);
  1860. String meh = o.toString();
  1861. byte[] decoded = Base64.decodeBase64(meh);
  1862. Subject = null;
  1863. try {
  1864. Subject = new String(decoded, "UTF-8");
  1865. } catch (Exception e) {
  1866. e.printStackTrace();
  1867. }
  1868. o = dbq.getObject(4);
  1869. meh = o.toString();
  1870. decoded = Base64.decodeBase64(meh);
  1871. Message = null;
  1872. try {
  1873. Message = new String(decoded, "UTF-8");
  1874. } catch (Exception e) {
  1875. e.printStackTrace();
  1876. }
  1877. }
  1878. db.st.close();
  1879. } catch (SQLException ex3) {
  1880. ex3.printStackTrace();
  1881. }
  1882. }
  1883. } catch (Exception e) {
  1884. e.printStackTrace();
  1885. }
  1886. }
  1887. processMessages processor = new processMessages(db);
  1888. processor.process();
  1889. String response = "";
  1890. HTMLBuilder html = new HTMLBuilder();
  1891. html.appendDefaultStart();
  1892. html.appendMailLeftMenu();
  1893. html.appendEndDiv();
  1894. html.appendMainStart();
  1895. response = response + "<form name='share' action='/send' method='post' enctype='multipart/form-data'><table>";
  1896. if (!To.equals(""))
  1897. {
  1898. response = response + "<tr><td><td>To:</td><td><input name = 'To' style='width:538px' value='" + To + "'></td></tr>";
  1899. } else {
  1900. response = response + "<tr><td><td>To:</td><td><select name = 'To' style='width:538px' multiple size=5>";
  1901. try {
  1902. String query = "SELECT address, label FROM bm_profiles ORDER BY dtstamp DESC";
  1903. ResultSet dbq = db.query(query);
  1904. Object o = null;
  1905. int count = 0;
  1906. for (; dbq.next(); ) {
  1907. o = dbq.getObject(1);
  1908. String address = (String)o;
  1909. o = dbq.getObject(2);
  1910. String label = (String)o;
  1911. if (label != null)
  1912. {
  1913. response = response + "<option value='" + address + "'>" + label + "</option>";
  1914. } else {
  1915. response = response + "<option value='" + address + "'>" + address + "</option>";
  1916. }
  1917. }
  1918. db.st.close();
  1919. } catch (SQLException ex3) {
  1920. ex3.printStackTrace();
  1921. }
  1922. response = response + "</select></td></tr>";
  1923. }
  1924. response = response + "<tr><td><td>From:</td><td><select name = 'From' style='width:538px'>";
  1925. APIcall apicall = new APIcall();
  1926. String xml = "<?xml version='1.0'?><methodCall><methodName>listAddresses</methodName></methodCall>";
  1927. String response2 = apicall.getAPIcall(xml);
  1928. try {
  1929. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  1930. DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  1931. Document doc = dBuilder.parse(new ByteArrayInputStream(response2.getBytes()));
  1932. doc.getDocumentElement().normalize();
  1933. NodeList nList = doc.getElementsByTagName("param");
  1934. for (int temp = 0; temp < nList.getLength(); temp++)
  1935. {
  1936. Node nNode = nList.item(temp);
  1937. if (nNode.getNodeType() == Node.ELEMENT_NODE)
  1938. {
  1939. Element eElement = (Element) nNode;
  1940. response2 = eElement.getElementsByTagName("string").item(0).getTextContent();
  1941. }
  1942. JSONParser parser1 = new JSONParser();
  1943. JSONParser parser2 = new JSONParser();
  1944. JSONParser parser3 = new JSONParser();
  1945. JSONParser parser4 = new JSONParser();
  1946. KeyFinder finder1 = new KeyFinder();
  1947. KeyFinder finder2 = new KeyFinder();
  1948. KeyFinder finder3 = new KeyFinder();
  1949. KeyFinder finder4 = new KeyFinder();
  1950. finder1.setMatchKey("label");
  1951. finder2.setMatchKey("address");
  1952. finder3.setMatchKey("stream");
  1953. finder4.setMatchKey("enabled");
  1954. try {
  1955. while(!finder1.isEnd())
  1956. {
  1957. parser1.parse(response2, finder1, true);
  1958. parser2.parse(response2, finder2, true);
  1959. parser3.parse(response2, finder3, true);
  1960. parser4.parse(response2, finder4, true);
  1961. if(finder1.isFound())
  1962. {
  1963. finder1.setFound(false);
  1964. String label = (String)finder1.getValue();
  1965. String address = (String)finder2.getValue();
  1966. long streaml = (long)finder3.getValue();
  1967. int stream = (int)streaml;
  1968. Boolean enabled = (Boolean)finder4.getValue();
  1969. if (enabled)
  1970. {
  1971. response = response + "<option value='" + address + "'>";
  1972. if (!label.equals(""))
  1973. {
  1974. response = response + label + "</option>";
  1975. } else {
  1976. response = response + address + "</option>";
  1977. }
  1978. }
  1979. } else {
  1980. finder1.endJSON();
  1981. }
  1982. }
  1983. } catch(ParseException pe) {
  1984. pe.printStackTrace();
  1985. }
  1986. }
  1987. } catch (Exception e) {
  1988. e.printStackTrace();
  1989. }
  1990. response = response + "</select></td></tr>";
  1991. response = response + "<tr><td><td>Subject:</td><td><input name = 'Subject' style='width:538px' value='" + Subject + "'></td></tr>";
  1992. response = response + "<tr><td><td>Message:</td><td><textarea cols=50 name='Message' rows=6 style='height:170px;width:538px'>" + Message + "</textarea></td></tr>";
  1993. response = response + "</table><input type='submit' value='Send'><input type = 'button' value = 'Choose image' onclick ='javascript:document.getElementById(\"imagefile\").click();'><input id = 'imagefile' type='file' style='visibility: hidden;' name='File' accept='image/*' onchange=\"loadImageFile();\"></form>";
  1994. response = response + "<div id='imagePreview'></div>";
  1995. html.append(response);
  1996. html.appendEndDiv();
  1997. html.appendEndBody();
  1998. t.sendResponseHeaders(200, html.getHTML().length());
  1999. OutputStream os = t.getResponseBody();
  2000. os.write(html.getHTML().getBytes());
  2001. os.close();
  2002. }
  2003. }
  2004. static class SendHandler implements HttpHandler
  2005. {
  2006. private ActivityStreamdb db = null;
  2007. public SendHandler(ActivityStreamdb db) {
  2008. this.db = db;
  2009. }
  2010. public void handle(HttpExchange t) throws IOException {
  2011. String response = "";
  2012. InputStream is = t.getRequestBody();
  2013. if (t.getRequestMethod().equalsIgnoreCase("POST"))
  2014. {
  2015. String toaddress = "";
  2016. String fromaddress = "";
  2017. String subject = "";
  2018. String message = "";
  2019. stream2File fstream = new stream2File();
  2020. File tmpfile = fstream.getstream2file(is);
  2021. try {
  2022. DataSource ds = new FileDataSource(tmpfile);
  2023. FormdataMultipart forminput = new FormdataMultipart(ds);
  2024. Hashtable params = forminput.getParameters();
  2025. String[] toarr = (String[])params.get("To");
  2026. for (int a=0; a<toarr.length; a++)
  2027. {
  2028. toaddress = toarr[a];
  2029. String[] fromarr = (String[])params.get("From");
  2030. fromaddress = fromarr[0];
  2031. String[] subarr = (String[])params.get("Subject");
  2032. base64processor encoded = new base64processor();
  2033. subject = encoded.toString(subarr[0].getBytes());
  2034. String[] messarr = (String[])params.get("Message");
  2035. message = messarr[0];
  2036. for (int i=0; i< forminput.getCount(); i++)
  2037. {
  2038. BodyPart bodprt = forminput.getBodyPart(i);
  2039. DataHandler blah = bodprt.getDataHandler();
  2040. InputStream is4 = blah.getInputStream();
  2041. response = response + "\n";
  2042. response = "<img src=\"data:" + blah.getContentType() + ";base64,";
  2043. response = response + encoded.toString(IOUtils.toByteArray(is4));
  2044. response = response + "\"";
  2045. response = response + " alt=\"" + blah.getName() + "\" /";
  2046. response = response + ">\n";
  2047. }
  2048. message = message + response;
  2049. message = encoded.toString(message.getBytes());
  2050. Send sender = new Send(toaddress, fromaddress, subject, message);
  2051. String response2 = sender.sendMessage();
  2052. System.out.println("Actkdata from send " + response2);
  2053. try {
  2054. String INSERT_RECORD = "INSERT INTO bm_mail(ackdata,read,folder,toaddress,fromaddress,subject,message,encodingtype,dtstamp,msgid) VALUES(?,?,?,?,?,?,?,?,?,?)";
  2055. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2056. pstmt.setString(1, response2);
  2057. pstmt.setBoolean(2, true);
  2058. pstmt.setString(3, "Sent");
  2059. pstmt.setString(4, toaddress);
  2060. pstmt.setString(5, fromaddress);
  2061. pstmt.setString(6, subject);
  2062. pstmt.setString(7, message);
  2063. pstmt.setInt(8, 2);
  2064. java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
  2065. pstmt.setTimestamp(9, sqlDate);
  2066. pstmt.setString(10, "null");
  2067. int d = pstmt.executeUpdate();
  2068. if (d == -1) {
  2069. System.out.println("db error : " );
  2070. }
  2071. pstmt.close();
  2072. } catch (SQLException ex3) {
  2073. ex3.printStackTrace();
  2074. }
  2075. }
  2076. } catch (Exception e) {
  2077. e.printStackTrace();
  2078. }
  2079. }
  2080. processOutMessages processor = new processOutMessages(db);
  2081. processor.process();
  2082. response = "<!DOCTYPE HTML>";
  2083. response = response + "<html lang=\"en-US\">";
  2084. response = response + " <head>";
  2085. response = response + " <meta charset=\"UTF-8\">";
  2086. response = response + " <meta http-equiv=\"refresh\" content=\"1;url=http://localhost:8000/messages\">";
  2087. response = response + " <script type=\"text/javascript\">";
  2088. response = response + " window.location.href = \"http://localhost:8000/messages\"";
  2089. response = response + " </script>";
  2090. response = response + " <title>Page Redirection</title>";
  2091. response = response + " </head>";
  2092. response = response + " <body>";
  2093. response = response + " </body>";
  2094. response = response + "</html>";
  2095. t.sendResponseHeaders(200, response.length());
  2096. OutputStream os = t.getResponseBody();
  2097. os.write(response.getBytes());
  2098. os.close();
  2099. }
  2100. }
  2101. static class ProfilesHandler implements HttpHandler
  2102. {
  2103. private ActivityStreamdb db = null;
  2104. public ProfilesHandler(ActivityStreamdb db) {
  2105. this.db = db;
  2106. }
  2107. public void handle(HttpExchange t) throws IOException {
  2108. String response = "";
  2109. String page = "follower";
  2110. @SuppressWarnings("unchecked")
  2111. Map<String, Object> params = (Map<String, Object>)t.getAttribute("parameters");
  2112. if (params.containsKey("page"))
  2113. {
  2114. page = (String)params.get("page");
  2115. }
  2116. if (t.getRequestMethod().equalsIgnoreCase("POST"))
  2117. {
  2118. InputStream is = t.getRequestBody();
  2119. stream2File fstream = new stream2File();
  2120. File tmpfile = fstream.getstream2file(is);
  2121. try {
  2122. DataSource ds = new FileDataSource(tmpfile);
  2123. FormdataMultipart forminput = new FormdataMultipart(ds);
  2124. Hashtable paramsa = forminput.getParameters();
  2125. if (paramsa.containsKey("add_address"))
  2126. {
  2127. String[] addressarr = (String[])paramsa.get("address");
  2128. String address = addressarr[0];
  2129. String[] followerarr = (String[])paramsa.get("follower");
  2130. String follower = followerarr[0];
  2131. String[] followingarr = (String[])paramsa.get("following");
  2132. String following = followingarr[0];
  2133. int count = 0;
  2134. String csql = "SELECT COUNT(*) AS rowcount FROM bm_profiles WHERE address=?";
  2135. try {
  2136. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  2137. pstmt.setString(1, address);
  2138. ResultSet rs = pstmt.executeQuery();
  2139. rs.next();
  2140. count = rs.getInt(1);
  2141. pstmt.close();
  2142. } catch (SQLException ex3) {
  2143. ex3.printStackTrace();
  2144. }
  2145. if (count == 0)
  2146. {
  2147. String INSERT_RECORD = "INSERT INTO bm_profiles(address,follower,following) VALUES(?,?,?)";
  2148. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2149. pstmt.setString(1, address);
  2150. pstmt.setBoolean(2, Boolean.parseBoolean(follower));
  2151. pstmt.setBoolean(3, Boolean.parseBoolean(following));
  2152. int i = pstmt.executeUpdate();
  2153. if (i == -1) {
  2154. System.out.println("db error : " );
  2155. }
  2156. pstmt.close();
  2157. }
  2158. if (Boolean.parseBoolean(following))
  2159. {
  2160. Follow follow = new Follow(address);
  2161. follow.follow();
  2162. }
  2163. }
  2164. if (paramsa.containsKey("add_list"))
  2165. {
  2166. String[] listarr = (String[])paramsa.get("list_name");
  2167. String list = listarr[0];
  2168. String INSERT_RECORD = "INSERT INTO bm_profiles_lists(list,address) VALUES(?,?)";
  2169. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2170. pstmt.setString(1, list);
  2171. pstmt.setString(2, "dummy");
  2172. int i = pstmt.executeUpdate();
  2173. if (i == -1) {
  2174. System.out.println("db error : " );
  2175. }
  2176. pstmt.close();
  2177. }
  2178. if (paramsa.containsKey("del_list"))
  2179. {
  2180. String[] listarr = (String[])paramsa.get("list_name");
  2181. String list = listarr[0];
  2182. String INSERT_RECORD = "DELETE FROM bm_profiles_lists WHERE list=?";
  2183. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2184. pstmt.setString(1, list);
  2185. int i = pstmt.executeUpdate();
  2186. if (i == -1) {
  2187. System.out.println("db error : " );
  2188. }
  2189. pstmt.close();
  2190. }
  2191. } catch (Exception e) {
  2192. e.printStackTrace();
  2193. }
  2194. }
  2195. processMessages processor = new processMessages(db);
  2196. processor.process();
  2197. try {
  2198. String INSERT_RECORD = "UPDATE bm_lastclick SET dtstamp=? WHERE wpage=?";
  2199. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2200. java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
  2201. pstmt.setTimestamp(1, sqlDate);
  2202. pstmt.setString(2, "FOLLOWERS");
  2203. int i = pstmt.executeUpdate();
  2204. if (i == -1) {
  2205. System.out.println("db error : " );
  2206. }
  2207. pstmt.close();
  2208. } catch (SQLException ex3) {
  2209. ex3.printStackTrace();
  2210. }
  2211. HTMLBuilder html = new HTMLBuilder();
  2212. html.appendDefaultStart();
  2213. html.appendProfilesLeftMenu();
  2214. html.appendEndDiv();
  2215. html.appendMainStart();
  2216. int offset = 0;
  2217. if (page.equals("follower") || page.equals("following"))
  2218. {
  2219. if (page.equals("following"))
  2220. {
  2221. response = response + "<form name='add_profile' action='/followers?page=" + page + "' method='post' enctype='multipart/form-data'>";
  2222. response = response + "Address:<br><input name=address><br>";
  2223. response = response + "<input type=hidden name='follower' value='false'>";
  2224. response = response + "<input type=hidden name='following' value='true'>";
  2225. response = response + "<input type=submit name='add_address' value='Follow Address'>";
  2226. response = response + "</form>";
  2227. }
  2228. try {
  2229. String query = "SELECT address, label FROM bm_profiles WHERE " + page + "=true ORDER BY dtstamp DESC LIMIT 100 OFFSET " + Integer.toString(offset) + "";
  2230. System.out.println("Retreive " + page + " details");
  2231. ResultSet dbq = db.query(query);
  2232. Object o = null;
  2233. int count = 0;
  2234. response = response + "<table>";
  2235. for (; dbq.next(); ) {
  2236. count++;
  2237. if (count == 1)
  2238. {
  2239. response = response + "<tr>";
  2240. }
  2241. o = dbq.getObject(1);
  2242. String address = (String)o;
  2243. o = dbq.getObject(2);
  2244. String label = (String)o;
  2245. response = response + "<td>";
  2246. response = response + label + "<br>";
  2247. response = response + "<a href='/profile?address=" + address + "'>"+ address + "</a>";
  2248. response = response + "</td>";
  2249. if (count == 3)
  2250. {
  2251. response = response + "</tr>";
  2252. count = 0;
  2253. }
  2254. }
  2255. if ((count == 1) || (count == 2))
  2256. {
  2257. response = response + "</tr>";
  2258. }
  2259. response = response + "</table>";
  2260. db.st.close();
  2261. } catch (SQLException ex3) {
  2262. ex3.printStackTrace();
  2263. }
  2264. }
  2265. if (page.equals("mail_contacts"))
  2266. {
  2267. response = response + "<form name='add_profile' action='/followers?page=" + page + "' method='post' enctype='multipart/form-data'>";
  2268. response = response + "Address:<br><input name=address><br>";
  2269. response = response + "<input type=hidden name='follower' value='false'>";
  2270. response = response + "<input type=hidden name='following' value='false'>";
  2271. response = response + "<input type=submit name='add_address' value='Add Address'>";
  2272. response = response + "</form>";
  2273. try {
  2274. String query = "SELECT address, label FROM bm_profiles WHERE follower=false AND following=false ORDER BY dtstamp DESC LIMIT 100 OFFSET " + Integer.toString(offset) + "";
  2275. System.out.println("Retreive " + page + " details");
  2276. ResultSet dbq = db.query(query);
  2277. Object o = null;
  2278. int count = 0;
  2279. response = response + "<table>";
  2280. for (; dbq.next(); ) {
  2281. count++;
  2282. if (count == 1)
  2283. {
  2284. response = response + "<tr>";
  2285. }
  2286. o = dbq.getObject(1);
  2287. String address = (String)o;
  2288. o = dbq.getObject(2);
  2289. String label = (String)o;
  2290. response = response + "<td>";
  2291. response = response + label + "<br>";
  2292. response = response + "<a href='/profile?address=" + address + "'>"+ address + "</a>";
  2293. response = response + "</td>";
  2294. if (count == 3)
  2295. {
  2296. response = response + "</tr>";
  2297. count = 0;
  2298. }
  2299. }
  2300. if ((count == 1) || (count == 2))
  2301. {
  2302. response = response + "</tr>";
  2303. }
  2304. response = response + "</table>";
  2305. db.st.close();
  2306. } catch (SQLException ex3) {
  2307. ex3.printStackTrace();
  2308. }
  2309. }
  2310. if (page.equals("lists"))
  2311. {
  2312. response = response + "<form name='add_list' action='/followers?page=" + page + "' method='post' enctype='multipart/form-data'>";
  2313. response = response + "List Name:<br><input name=list_name><br>";
  2314. response = response + "<input type=submit name='add_list' value='Add List'>";
  2315. response = response + "</form>";
  2316. response = response + "<br>";
  2317. response = response + "<form name='del_list' action='/followers?page=" + page + "' method='post' enctype='multipart/form-data'>";
  2318. response = response + "List Name:<br><select name=list_name>";
  2319. try {
  2320. String query = "SELECT DISTINCT list FROM bm_profiles_lists";
  2321. System.out.println("Retreive list of follower lists");
  2322. ResultSet dbq = db.query(query);
  2323. Object o = null;
  2324. for (; dbq.next(); ) {
  2325. o = dbq.getObject(1);
  2326. String list = (String)o;
  2327. response = response + "<option value='" + list + "'>" + list + "</option>";
  2328. }
  2329. } catch (SQLException ex3) {
  2330. ex3.printStackTrace();
  2331. }
  2332. response = response + "</select>";
  2333. response = response + "<br><input type=submit name='del_list' value='Delete List'>";
  2334. response = response + "</form>";
  2335. }
  2336. response = response + "</div></body></html>";
  2337. html.append(response);
  2338. t.sendResponseHeaders(200, html.getHTML().length());
  2339. OutputStream os = t.getResponseBody();
  2340. os.write(html.getHTML().getBytes());
  2341. os.close();
  2342. }
  2343. }
  2344. static class ProfileHandler implements HttpHandler
  2345. {
  2346. private ActivityStreamdb db = null;
  2347. public ProfileHandler(ActivityStreamdb db) {
  2348. this.db = db;
  2349. }
  2350. public void handle(HttpExchange t) throws IOException {
  2351. String response = "";
  2352. @SuppressWarnings("unchecked")
  2353. Map<String, Object> params = (Map<String, Object>)t.getAttribute("parameters");
  2354. String address = (String)params.get("address");
  2355. if (t.getRequestMethod().equalsIgnoreCase("POST"))
  2356. {
  2357. InputStream is = t.getRequestBody();
  2358. stream2File fstream = new stream2File();
  2359. File tmpfile = fstream.getstream2file(is);
  2360. try {
  2361. DataSource ds = new FileDataSource(tmpfile);
  2362. FormdataMultipart forminput = new FormdataMultipart(ds);
  2363. Hashtable paramsa = forminput.getParameters();
  2364. if (paramsa.containsKey("update"))
  2365. {
  2366. String[] labelarr = (String[])paramsa.get("label");
  2367. String label = labelarr[0];
  2368. String[] notesarr = (String[])paramsa.get("notes");
  2369. String notes = notesarr[0];
  2370. String INSERT_RECORD = "UPDATE bm_profiles SET label=?, notes=? WHERE address=?";
  2371. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2372. pstmt.setString(1, label);
  2373. pstmt.setString(2, notes);
  2374. pstmt.setString(3, address);
  2375. int d = pstmt.executeUpdate();
  2376. if (d == -1) {
  2377. System.out.println("db error : " );
  2378. }
  2379. pstmt.close();
  2380. }
  2381. if (paramsa.containsKey("follow"))
  2382. {
  2383. Follow follow = new Follow(address);
  2384. follow.follow();
  2385. }
  2386. if (paramsa.containsKey("unfollow"))
  2387. {
  2388. Follow follow = new Follow(address);
  2389. follow.unfollow();
  2390. }
  2391. if (paramsa.containsKey("delete"))
  2392. {
  2393. Follow follow = new Follow(address);
  2394. follow.unfollow();
  2395. String INSERT_RECORD = "DELETE FROM bm_profiles WHERE address=?";
  2396. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2397. pstmt.setString(1, address);
  2398. int d = pstmt.executeUpdate();
  2399. if (d == -1) {
  2400. System.out.println("db error : " );
  2401. }
  2402. pstmt.close();
  2403. }
  2404. if (paramsa.containsKey("add_to_list"))
  2405. {
  2406. String[] listarr = (String[])paramsa.get("list_name");
  2407. String list = listarr[0];
  2408. String INSERT_RECORD = "INSERT INTO bm_profiles_lists(list, address) VALUES(?,?)";
  2409. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2410. pstmt.setString(1, list);
  2411. pstmt.setString(2, address);
  2412. int i = pstmt.executeUpdate();
  2413. if (i == -1) {
  2414. System.out.println("db error : " );
  2415. }
  2416. pstmt.close();
  2417. }
  2418. if (paramsa.containsKey("del_from_list"))
  2419. {
  2420. String[] listarr = (String[])paramsa.get("list_name");
  2421. String list = listarr[0];
  2422. String INSERT_RECORD = "DELETE FROM bm_profiles_lists WHERE list=? AND address=?";
  2423. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2424. pstmt.setString(1, list);
  2425. pstmt.setString(2, address);
  2426. int i = pstmt.executeUpdate();
  2427. if (i == -1) {
  2428. System.out.println("db error : " );
  2429. }
  2430. pstmt.close();
  2431. }
  2432. } catch (Exception e) {
  2433. e.printStackTrace();
  2434. }
  2435. }
  2436. processMessages processor = new processMessages(db);
  2437. processor.process();
  2438. HTMLBuilder html = new HTMLBuilder();
  2439. html.appendDefaultStart();
  2440. html.appendProfilesLeftMenu();
  2441. html.appendEndDiv();
  2442. html.appendMainStart();
  2443. String label = "";
  2444. String notes = "";
  2445. Boolean follower = false;
  2446. Boolean following = false;
  2447. try {
  2448. String query = "SELECT label, notes, follower, following FROM bm_profiles WHERE address='" + address + "'";
  2449. System.out.println("Retrieving address details");
  2450. ResultSet dbq = db.query(query);
  2451. Object o = null;
  2452. int count = 0;
  2453. response = response + "<table>";
  2454. for (; dbq.next(); ) {
  2455. count++;
  2456. if (count == 1)
  2457. {
  2458. response = response + "<tr>";
  2459. }
  2460. o = dbq.getObject(1);
  2461. label = (String)o;
  2462. o = dbq.getObject(2);
  2463. notes = (String)o;
  2464. o = dbq.getObject(3);
  2465. follower = (Boolean)o;
  2466. o = dbq.getObject(4);
  2467. following = (Boolean)o;
  2468. }
  2469. db.st.close();
  2470. } catch (SQLException ex3) {
  2471. ex3.printStackTrace();
  2472. }
  2473. response = response + "<div>" + address + "</div>";
  2474. if (follower)
  2475. {
  2476. response = response + "<div>(Follower)</div>";
  2477. }
  2478. response = response + "<form name='update_profile' action='/profile?address=" + address + "' method='post' enctype='multipart/form-data'>";
  2479. response = response + "Label:<br><input name=label value='" + label + "'><br>";
  2480. response = response + "Notes:<br><textarea cols=50 name='notes' rows=6 style='height:170px;width:538px'>" + notes + "</textarea><br>";
  2481. response = response + "<input type=submit name='update' value='Update Profile'>";
  2482. response = response + "</form>";
  2483. response = response + "<form name='following' action='/send_message' method='get'>";
  2484. response = response + "<input type=hidden name='To' value='" + address + "'>";
  2485. response = response + "<input type=hidden name='From' value=' '>";
  2486. response = response + "<input type=hidden name='Subject' value=' '>";
  2487. response = response + "<input type=hidden name='Message' value=' '>";
  2488. response = response + "<input type=submit name='send' value='Send Message'>";
  2489. response = response + "</form>";
  2490. response = response + "</div></body></html>";
  2491. if (follower)
  2492. {
  2493. ArrayList<String> addlist = new ArrayList<String>();
  2494. ArrayList<String> dellist = new ArrayList<String>();
  2495. try {
  2496. String query = "SELECT list FROM bm_profiles_lists WHERE address='" + address + "'";
  2497. System.out.println("Checking follower list "+ address + " belongs to");
  2498. ResultSet dbq = db.query(query);
  2499. Object o = null;
  2500. for (; dbq.next(); ) {
  2501. o = dbq.getObject(1);
  2502. String list = (String)o;
  2503. dellist.add(list);
  2504. }
  2505. } catch (SQLException ex3) {
  2506. ex3.printStackTrace();
  2507. }
  2508. try {
  2509. String query = "SELECT DISTINCT list FROM bm_profiles_lists";
  2510. System.out.println("Checking available lists");
  2511. ResultSet dbq = db.query(query);
  2512. Object o = null;
  2513. for (; dbq.next(); ) {
  2514. o = dbq.getObject(1);
  2515. String list = (String)o;
  2516. if (!dellist.contains(list))
  2517. {
  2518. addlist.add(list);
  2519. }
  2520. }
  2521. } catch (SQLException ex3) {
  2522. ex3.printStackTrace();
  2523. }
  2524. response = response + "<form name='add_to_list' action='/profile?address=" + address + "' method='post' enctype='multipart/form-data'>";
  2525. response = response + "<input type=submit name='add_to_list' value='Add to list:'>";
  2526. response = response + "<select name=list_name>";
  2527. for (int i=0; i<addlist.size(); i++)
  2528. {
  2529. response = response + "<option value='" + addlist.get(i) + "'>" + addlist.get(i) + "</option>";
  2530. }
  2531. response = response + "</select>";
  2532. response = response + "</form>";
  2533. response = response + "<form name='del_from_list' action='/profile?address=" + address + "' method='post' enctype='multipart/form-data'>";
  2534. response = response + "<input type=submit name='del_from_list' value='Delete from list:'>";
  2535. response = response + "<select name=list_name>";
  2536. for (int i=0; i<dellist.size(); i++)
  2537. {
  2538. response = response + "<option value='" + dellist.get(i) + "'>" + dellist.get(i) + "</option>";
  2539. }
  2540. response = response + "</select>";
  2541. response = response + "</form>";
  2542. if (!following)
  2543. {
  2544. response = response + "<form name='following' action='/profile?address=" + address + "' method='post' enctype='multipart/form-data'>";
  2545. response = response + "<input type=submit name='follow' value='Follow'>";
  2546. response = response + "</form>";
  2547. }
  2548. }
  2549. if (following)
  2550. {
  2551. response = response + "<form name='following' action='/profile?address=" + address + "' method='post' enctype='multipart/form-data'>";
  2552. response = response + "<input type=submit name='unfollow' value='Unfollow'>";
  2553. response = response + "</form>";
  2554. }
  2555. if (!follower)
  2556. {
  2557. response = response + "<form name='following' action='/profile?address=" + address + "' method='post' enctype='multipart/form-data'>";
  2558. response = response + "<input type=submit name='delete' value='Delete'>";
  2559. response = response + "</form>";
  2560. }
  2561. response = response + "</div></body></html>";
  2562. html.append(response);
  2563. t.sendResponseHeaders(200, html.getHTML().length());
  2564. OutputStream os = t.getResponseBody();
  2565. os.write(html.getHTML().getBytes());
  2566. os.close();
  2567. }
  2568. }
  2569. static class Send {
  2570. private String toAddress = "";
  2571. private String fromAddress = "";
  2572. private String Subject = "";
  2573. private String Message = "";
  2574. public Send(String toAddress, String fromAddress, String Subject, String Message)
  2575. {
  2576. this.toAddress = toAddress;
  2577. this.fromAddress = fromAddress;
  2578. this.Subject = Subject;
  2579. this.Message = Message;
  2580. }
  2581. public String sendMessage()
  2582. {
  2583. String xml = "<?xml version='1.0'?><methodCall><methodName>sendMessage</methodName><params><param><value><string>" + toAddress + "</string></value></param><param><value><string>" + fromAddress + "</string></value></param><param><value><string>" + Subject + "</string></value></param><param><value><string>" + Message + "</string></value></param></params></methodCall>";
  2584. APIcall sendCall = new APIcall();
  2585. String response2 = sendCall.getAPIcall(xml);
  2586. try {
  2587. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  2588. DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  2589. Document doc = dBuilder.parse(new ByteArrayInputStream(response2.getBytes()));
  2590. doc.getDocumentElement().normalize();
  2591. NodeList nList = doc.getElementsByTagName("param");
  2592. for (int temp = 0; temp < nList.getLength(); temp++)
  2593. {
  2594. Node nNode = nList.item(temp);
  2595. if (nNode.getNodeType() == Node.ELEMENT_NODE)
  2596. {
  2597. Element eElement = (Element) nNode;
  2598. response2 = eElement.getElementsByTagName("string").item(0).getTextContent();
  2599. }
  2600. }
  2601. } catch (Exception e) {
  2602. e.printStackTrace();
  2603. }
  2604. return response2;
  2605. }
  2606. }
  2607. static class Follow
  2608. {
  2609. String address = "";
  2610. String user = "";
  2611. public Follow(String address) {
  2612. this.address = address;
  2613. bmasAddresses useraddress = new bmasAddresses();
  2614. this.user = useraddress.getUser();
  2615. }
  2616. public void follow()
  2617. {
  2618. try {
  2619. String INSERT_RECORD = "UPDATE bm_profiles SET following=? WHERE address=?";
  2620. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2621. pstmt.setBoolean(1, true);
  2622. pstmt.setString(2, address);
  2623. int d = pstmt.executeUpdate();
  2624. if (d == -1) {
  2625. System.out.println("db error : " );
  2626. }
  2627. pstmt.close();
  2628. } catch (Exception e) {
  2629. e.printStackTrace();
  2630. }
  2631. base64processor encoded = new base64processor();
  2632. String subjectp = "[BM-ActivityStream]";
  2633. String subject = encoded.toString(subjectp.getBytes());
  2634. String messagep = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>";
  2635. String uuid = UUID.randomUUID().toString();
  2636. messagep = messagep + "<activity><to><objectType>person</objectType><id>" + address + "</id></to><actor><objectType>person</objectType><id>" + user + "</id></actor><target><objectType>followers</objectType><id>" + uuid + "</id></target><verb>follow</verb><object><objectType>person</objectType><id>" + address + "</id></object></activity>";
  2637. String message = encoded.toString(messagep.getBytes());
  2638. Send sender = new Send(address, user, subject, message);
  2639. sender.sendMessage();
  2640. try {
  2641. String INSERT_RECORD = "INSERT INTO bm_table(msgid,address,application,message,dtstamp) VALUES(?,?,?,?,?)";
  2642. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2643. pstmt.setString(1, uuid);
  2644. pstmt.setString(2, user);
  2645. pstmt.setString(3, "followers");
  2646. pstmt.setString(4, messagep);
  2647. java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
  2648. System.out.println(sqlDate);
  2649. pstmt.setTimestamp(5, sqlDate);
  2650. int i = pstmt.executeUpdate();
  2651. if (i == -1) {
  2652. System.out.println("db error : " );
  2653. }
  2654. pstmt.close();
  2655. } catch (SQLException e) {
  2656. e.printStackTrace();
  2657. }
  2658. }
  2659. public void unfollow()
  2660. {
  2661. base64processor encoded = new base64processor();
  2662. String subjectp = "[BM-ActivityStream]";
  2663. String subject = encoded.toString(subjectp.getBytes());
  2664. String messagep = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>";
  2665. String uuid = UUID.randomUUID().toString();
  2666. messagep = messagep + "<activity><to><objectType>person</objectType><id>" + address + "</id></to><actor><objectType>person</objectType><id>" + user + "</id></actor><target><objectType>followers</objectType><id>" + uuid + "</id></target><verb>unfollow</verb><object><objectType>person</objectType><id>" + address + "</id></object></activity>";
  2667. String message = encoded.toString(messagep.getBytes());
  2668. Send sender = new Send(address, user, subject, message);
  2669. sender.sendMessage();
  2670. try {
  2671. String INSERT_RECORD = "UPDATE bm_profiles SET following=? WHERE address=?";
  2672. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2673. pstmt.setBoolean(1, false);
  2674. pstmt.setString(2, address);
  2675. int d = pstmt.executeUpdate();
  2676. if (d == -1) {
  2677. System.out.println("db error : " );
  2678. }
  2679. pstmt.close();
  2680. } catch (Exception e) {
  2681. e.printStackTrace();
  2682. }
  2683. try {
  2684. String INSERT_RECORD = "INSERT INTO bm_table(msgid,address,application,message,dtstamp) VALUES(?,?,?,?,?)";
  2685. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2686. pstmt.setString(1, uuid);
  2687. pstmt.setString(2, user);
  2688. pstmt.setString(3, "followers");
  2689. pstmt.setString(4, messagep);
  2690. java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
  2691. System.out.println(sqlDate);
  2692. pstmt.setTimestamp(5, sqlDate);
  2693. int i = pstmt.executeUpdate();
  2694. if (i == -1) {
  2695. System.out.println("db error : " );
  2696. }
  2697. pstmt.close();
  2698. } catch (SQLException e) {
  2699. e.printStackTrace();
  2700. }
  2701. }
  2702. }
  2703. static class Follower
  2704. {
  2705. String address = "";
  2706. public Follower(String address) {
  2707. this.address = address;
  2708. }
  2709. public void followed()
  2710. {
  2711. try {
  2712. System.out.println("Setting follower to true for " + address);
  2713. String INSERT_RECORD = "UPDATE bm_profiles SET follower=? WHERE address=?";
  2714. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2715. pstmt.setBoolean(1, true);
  2716. pstmt.setString(2, address);
  2717. int d = pstmt.executeUpdate();
  2718. if (d == -1) {
  2719. System.out.println("db error : " );
  2720. }
  2721. pstmt.close();
  2722. } catch (Exception e) {
  2723. e.printStackTrace();
  2724. }
  2725. }
  2726. public void unfollowed()
  2727. {
  2728. try {
  2729. System.out.println("Setting follower to false for " + address);
  2730. String INSERT_RECORD = "UPDATE bm_profiles SET follower=? WHERE address=?";
  2731. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  2732. pstmt.setBoolean(1, false);
  2733. pstmt.setString(2, address);
  2734. int d = pstmt.executeUpdate();
  2735. if (d == -1) {
  2736. System.out.println("db error : " );
  2737. }
  2738. pstmt.close();
  2739. } catch (Exception e) {
  2740. e.printStackTrace();
  2741. }
  2742. }
  2743. }
  2744. static class Like
  2745. {
  2746. Node activity = null;
  2747. String address = "";
  2748. String targetid = "";
  2749. String replyid = "";
  2750. String user = "";
  2751. public Like(Node activity, String address, String targetid, String replyid) {
  2752. this.activity = activity;
  2753. this.address = address;
  2754. this.targetid = targetid;
  2755. this.replyid = replyid;
  2756. bmasAddresses useraddress = new bmasAddresses();
  2757. this.user = useraddress.getUser();
  2758. }
  2759. public void like()
  2760. {
  2761. String messagep = "";
  2762. ArrayList<String> recipients = new ArrayList<String>();
  2763. if ((!recipients.contains(address)) && (!address.equals(user)))
  2764. {
  2765. recipients.add(address);
  2766. }
  2767. Element activityE = (Element) activity;
  2768. NodeList toNL = activityE.getElementsByTagName("to");
  2769. for (int z = 0; z<toNL.getLength(); z++)
  2770. {
  2771. Node toN = toNL.item(z);
  2772. Element toE = (Element) toN;
  2773. String addressee = toE.getElementsByTagName("id").item(0).getTextContent();
  2774. if ((!recipients.contains(addressee)) && (!addressee.equals(user)))
  2775. {
  2776. recipients.add(addressee);
  2777. }
  2778. }
  2779. base64processor encoded = new base64processor();
  2780. String subjectp = "[BM-ActivityStream]";
  2781. String subject = encoded.toString(subjectp.getBytes());
  2782. messagep = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>";
  2783. messagep = messagep + "<activity>";
  2784. for (int y =0; y<recipients.size(); y++)
  2785. {
  2786. messagep = messagep + "<to><objectType>person</objectType><id>" + recipients.get(y) + "</id></to>";
  2787. }
  2788. messagep = messagep + "<actor><objectType>person</objectType><id>" + user + "</id></actor><target><objectType>news</objectType><id>" + targetid + "</id></target><verb>like</verb><object><inReplyTo>" + replyid + "</inReplyTo><id>" + replyid + "." + UUID.randomUUID().toString() + "</id></object></activity>";
  2789. String message = encoded.toString(messagep.getBytes());
  2790. for (int y =0; y<recipients.size(); y++)
  2791. {
  2792. Send sender = new Send(recipients.get(y), user, subject, message);
  2793. sender.sendMessage();
  2794. }
  2795. try {
  2796. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  2797. DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  2798. Document doc = dBuilder.parse(new ByteArrayInputStream(messagep.getBytes()));
  2799. doc.getDocumentElement().normalize();
  2800. Node activityNode = doc.getElementsByTagName("activity").item(0);
  2801. long receivedTime = new java.util.Date().getTime();
  2802. NewsProcessor newsprocess = new NewsProcessor(user, receivedTime/1000L, activityNode, messagep);
  2803. newsprocess.process();
  2804. } catch (Exception e) {
  2805. e.printStackTrace();
  2806. }
  2807. }
  2808. }
  2809. static class Comment
  2810. {
  2811. Node activity = null;
  2812. String address = "";
  2813. String targetid = "";
  2814. String replyid = "";
  2815. String user = "";
  2816. String comment = "";
  2817. String comment_type = "";
  2818. public Comment(Node activity, String address, String targetid, String replyid, String comment, String comment_type) {
  2819. this.activity = activity;
  2820. this.address = address;
  2821. this.targetid = targetid;
  2822. this.replyid = replyid;
  2823. bmasAddresses useraddress = new bmasAddresses();
  2824. this.user = useraddress.getUser();
  2825. this.comment = comment;
  2826. this.comment_type = comment_type;
  2827. }
  2828. public void comment()
  2829. {
  2830. String messagep = "";
  2831. ArrayList<String> recipients = new ArrayList<String>();
  2832. if ((!recipients.contains(address)) && (!address.equals(user)))
  2833. {
  2834. recipients.add(address);
  2835. }
  2836. Element activityE = (Element) activity;
  2837. NodeList toNL = activityE.getElementsByTagName("to");
  2838. for (int z = 0; z<toNL.getLength(); z++)
  2839. {
  2840. Node toN = toNL.item(z);
  2841. Element toE = (Element) toN;
  2842. String addressee = toE.getElementsByTagName("id").item(0).getTextContent();
  2843. if ((!recipients.contains(addressee)) && (!addressee.equals(user)))
  2844. {
  2845. recipients.add(addressee);
  2846. }
  2847. }
  2848. base64processor encoded = new base64processor();
  2849. String subjectp = "[BM-ActivityStream]";
  2850. String subject = encoded.toString(subjectp.getBytes());
  2851. messagep = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>";
  2852. messagep = messagep + "<activity>";
  2853. for (int y =0; y<recipients.size(); y++)
  2854. {
  2855. messagep = messagep + "<to><objectType>person</objectType><id>" + recipients.get(y) + "</id></to>";
  2856. }
  2857. messagep = messagep + "<actor><objectType>person</objectType><id>" + user + "</id></actor><target><objectType>news</objectType><id>" + targetid + "</id></target><verb>comment</verb><object><inReplyTo>" + replyid + "</inReplyTo><id>" + replyid + "." + UUID.randomUUID().toString() + "</id><content>" + comment + "</content></object></activity>";
  2858. String message = encoded.toString(messagep.getBytes());
  2859. if (comment_type.equals("Anonymous"))
  2860. {
  2861. bmasAddresses chanaddress = new bmasAddresses();
  2862. this.user = chanaddress.getChan();
  2863. }
  2864. for (int y =0; y<recipients.size(); y++)
  2865. {
  2866. Send sender = new Send(recipients.get(y), user, subject, message);
  2867. sender.sendMessage();
  2868. }
  2869. try {
  2870. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  2871. DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  2872. Document doc = dBuilder.parse(new ByteArrayInputStream(messagep.getBytes()));
  2873. doc.getDocumentElement().normalize();
  2874. Node activityNode = doc.getElementsByTagName("activity").item(0);
  2875. long receivedTime = new java.util.Date().getTime();
  2876. NewsProcessor newsprocess = new NewsProcessor(user, receivedTime/1000L, activityNode, messagep);
  2877. newsprocess.process();
  2878. } catch (Exception e) {
  2879. e.printStackTrace();
  2880. }
  2881. }
  2882. }
  2883. static class Post
  2884. {
  2885. String addresstype = "";
  2886. String[] addressees = null;
  2887. String content = "";
  2888. ArrayList<String> images = new ArrayList<String>();
  2889. String user = "";
  2890. String comment = "";
  2891. public Post(String addresstype, String[] addressees, String content, ArrayList<String> images) {
  2892. this.addresstype = addresstype;
  2893. this.addressees = addressees;
  2894. this.content = content;
  2895. this.images = images;
  2896. bmasAddresses useraddress = new bmasAddresses();
  2897. this.user = useraddress.getUser();
  2898. }
  2899. public void post()
  2900. {
  2901. String messagep = "";
  2902. ArrayList<String> recipients = new ArrayList<String>();
  2903. if (addresstype.equals("Followers"))
  2904. {
  2905. for (int z = 0; z<addressees.length; z++)
  2906. {
  2907. recipients.add(addressees[z]);
  2908. }
  2909. }
  2910. if (addresstype.equals("Lists"))
  2911. {
  2912. for (int z = 0; z<addressees.length; z++)
  2913. {
  2914. try {
  2915. String query = "SELECT address FROM bm_profiles_lists WHERE list='" + addressees[z] + "'";
  2916. ResultSet dbq = db.query(query);
  2917. Object o = null;
  2918. for (; dbq.next(); ) {
  2919. o = dbq.getObject(1);
  2920. String address = (String)o;
  2921. recipients.add(address);
  2922. }
  2923. } catch (SQLException ex3) {
  2924. ex3.printStackTrace();
  2925. }
  2926. }
  2927. }
  2928. if (addresstype.equals("Public"))
  2929. {
  2930. bmasAddresses getaddress = new bmasAddresses();
  2931. recipients.add(getaddress.getChan());
  2932. if (addressees[0].equals("Anonymous"))
  2933. {
  2934. this.user = getaddress.getChan();
  2935. }
  2936. }
  2937. if (recipients.size() > 0)
  2938. {
  2939. base64processor encoded = new base64processor();
  2940. String subjectp = "[BM-ActivityStream]";
  2941. String subject = encoded.toString(subjectp.getBytes());
  2942. messagep = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>";
  2943. messagep = messagep + "<activity>";
  2944. for (int y =0; y<recipients.size(); y++)
  2945. {
  2946. messagep = messagep + "<to><objectType>person</objectType><id>" + recipients.get(y) + "</id></to>";
  2947. }
  2948. messagep = messagep + "<actor><objectType>person</objectType><id>" + user + "</id></actor><target><objectType>news</objectType><id>" + UUID.randomUUID().toString() + "</id></target><verb>post</verb><object><content>" + content + "</content>";
  2949. if (images.size() > 0)
  2950. {
  2951. messagep = messagep + "<image>" + images.get(0) + "</image>";
  2952. }
  2953. messagep = messagep + "</object></activity>";
  2954. String message = encoded.toString(messagep.getBytes());
  2955. for (int y =0; y<recipients.size(); y++)
  2956. {
  2957. Send sender = new Send(recipients.get(y), user, subject, message);
  2958. sender.sendMessage();
  2959. }
  2960. try {
  2961. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  2962. DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  2963. Document doc = dBuilder.parse(new ByteArrayInputStream(messagep.getBytes()));
  2964. doc.getDocumentElement().normalize();
  2965. Node activityNode = doc.getElementsByTagName("activity").item(0);
  2966. long receivedTime = new java.util.Date().getTime();
  2967. NewsProcessor newsprocess = new NewsProcessor(user, receivedTime, activityNode, messagep);
  2968. newsprocess.process();
  2969. } catch (Exception e) {
  2970. e.printStackTrace();
  2971. }
  2972. }
  2973. }
  2974. }
  2975. static class bmasAddresses {
  2976. public bmasAddresses()
  2977. {
  2978. }
  2979. public String getUser()
  2980. {
  2981. String user = "";
  2982. APIcall apicall = new APIcall();
  2983. String xml = "<?xml version='1.0'?><methodCall><methodName>listAddresses</methodName></methodCall>";
  2984. String response2 = apicall.getAPIcall(xml);
  2985. try {
  2986. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  2987. DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  2988. Document doc = dBuilder.parse(new ByteArrayInputStream(response2.getBytes()));
  2989. doc.getDocumentElement().normalize();
  2990. NodeList nList = doc.getElementsByTagName("param");
  2991. for (int temp = 0; temp < nList.getLength(); temp++)
  2992. {
  2993. Node nNode = nList.item(temp);
  2994. if (nNode.getNodeType() == Node.ELEMENT_NODE)
  2995. {
  2996. Element eElement = (Element) nNode;
  2997. response2 = eElement.getElementsByTagName("string").item(0).getTextContent();
  2998. }
  2999. JSONParser parser1 = new JSONParser();
  3000. JSONParser parser2 = new JSONParser();
  3001. JSONParser parser3 = new JSONParser();
  3002. JSONParser parser4 = new JSONParser();
  3003. KeyFinder finder1 = new KeyFinder();
  3004. KeyFinder finder2 = new KeyFinder();
  3005. KeyFinder finder3 = new KeyFinder();
  3006. KeyFinder finder4 = new KeyFinder();
  3007. finder1.setMatchKey("label");
  3008. finder2.setMatchKey("address");
  3009. finder3.setMatchKey("stream");
  3010. finder4.setMatchKey("enabled");
  3011. try {
  3012. while(!finder1.isEnd())
  3013. {
  3014. parser1.parse(response2, finder1, true);
  3015. parser2.parse(response2, finder2, true);
  3016. parser3.parse(response2, finder3, true);
  3017. parser4.parse(response2, finder4, true);
  3018. if(finder1.isFound())
  3019. {
  3020. finder1.setFound(false);
  3021. String label = (String)finder1.getValue();
  3022. String address = (String)finder2.getValue();
  3023. long streaml = (long)finder3.getValue();
  3024. int stream = (int)streaml;
  3025. Boolean enabled = (Boolean)finder4.getValue();
  3026. if (enabled)
  3027. {
  3028. if (label.equals("BM-ActivityStream-User"))
  3029. {
  3030. user = address;
  3031. }
  3032. }
  3033. } else {
  3034. finder1.endJSON();
  3035. }
  3036. }
  3037. } catch(ParseException pe) {
  3038. pe.printStackTrace();
  3039. }
  3040. }
  3041. } catch (Exception e) {
  3042. e.printStackTrace();
  3043. }
  3044. return user;
  3045. }
  3046. public String getChan()
  3047. {
  3048. String user = "";
  3049. APIcall apicall = new APIcall();
  3050. String xml = "<?xml version='1.0'?><methodCall><methodName>listAddresses</methodName></methodCall>";
  3051. String response2 = apicall.getAPIcall(xml);
  3052. try {
  3053. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  3054. DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  3055. Document doc = dBuilder.parse(new ByteArrayInputStream(response2.getBytes()));
  3056. doc.getDocumentElement().normalize();
  3057. NodeList nList = doc.getElementsByTagName("param");
  3058. for (int temp = 0; temp < nList.getLength(); temp++)
  3059. {
  3060. Node nNode = nList.item(temp);
  3061. if (nNode.getNodeType() == Node.ELEMENT_NODE)
  3062. {
  3063. Element eElement = (Element) nNode;
  3064. response2 = eElement.getElementsByTagName("string").item(0).getTextContent();
  3065. }
  3066. JSONParser parser1 = new JSONParser();
  3067. JSONParser parser2 = new JSONParser();
  3068. JSONParser parser3 = new JSONParser();
  3069. JSONParser parser4 = new JSONParser();
  3070. KeyFinder finder1 = new KeyFinder();
  3071. KeyFinder finder2 = new KeyFinder();
  3072. KeyFinder finder3 = new KeyFinder();
  3073. KeyFinder finder4 = new KeyFinder();
  3074. finder1.setMatchKey("label");
  3075. finder2.setMatchKey("address");
  3076. finder3.setMatchKey("stream");
  3077. finder4.setMatchKey("enabled");
  3078. try {
  3079. while(!finder1.isEnd())
  3080. {
  3081. parser1.parse(response2, finder1, true);
  3082. parser2.parse(response2, finder2, true);
  3083. parser3.parse(response2, finder3, true);
  3084. parser4.parse(response2, finder4, true);
  3085. if(finder1.isFound())
  3086. {
  3087. finder1.setFound(false);
  3088. String label = (String)finder1.getValue();
  3089. String address = (String)finder2.getValue();
  3090. long streaml = (long)finder3.getValue();
  3091. int stream = (int)streaml;
  3092. Boolean enabled = (Boolean)finder4.getValue();
  3093. if (enabled)
  3094. {
  3095. if (label.equals("BM-ActivityStream-Chan-General"))
  3096. {
  3097. user = address;
  3098. }
  3099. }
  3100. } else {
  3101. finder1.endJSON();
  3102. }
  3103. }
  3104. } catch(ParseException pe) {
  3105. pe.printStackTrace();
  3106. }
  3107. }
  3108. } catch (Exception e) {
  3109. e.printStackTrace();
  3110. }
  3111. return user;
  3112. }
  3113. }
  3114. static class processMessages {
  3115. private ActivityStreamdb db = null;
  3116. public processMessages(ActivityStreamdb db)
  3117. {
  3118. this.db = db;
  3119. }
  3120. public void process()
  3121. {
  3122. processInMessages inProcessor = new processInMessages(db);
  3123. inProcessor.process();
  3124. processOutMessages outProcessor = new processOutMessages(db);
  3125. outProcessor.process();
  3126. }
  3127. }
  3128. static class processInMessages {
  3129. private ActivityStreamdb db = null;
  3130. public processInMessages(ActivityStreamdb db)
  3131. {
  3132. this.db = db;
  3133. }
  3134. public void process()
  3135. {
  3136. String bmapi_client = "";
  3137. try {
  3138. String query = "SELECT value FROM bm_settings WHERE setting='bmapi_client'";
  3139. ResultSet dbq = db.query(query);
  3140. Object o = null;
  3141. for (; dbq.next(); ) {
  3142. o = dbq.getObject(1);
  3143. bmapi_client = (String)o;
  3144. }
  3145. } catch (SQLException ex3) {
  3146. ex3.printStackTrace();
  3147. }
  3148. Boolean bm_as_processed = true;
  3149. while (bm_as_processed)
  3150. {
  3151. bm_as_processed = false;
  3152. APIcall apicall = new APIcall();
  3153. String xml = "<?xml version='1.0'?><methodCall><methodName>getAllInboxMessages</methodName></methodCall>";
  3154. String response = apicall.getAPIcall(xml);
  3155. try {
  3156. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  3157. DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  3158. Document doc = dBuilder.parse(new ByteArrayInputStream(response.getBytes()));
  3159. doc.getDocumentElement().normalize();
  3160. NodeList nList = doc.getElementsByTagName("param");
  3161. for (int temp = 0; temp < nList.getLength(); temp++)
  3162. {
  3163. Node nNode = nList.item(temp);
  3164. if (nNode.getNodeType() == Node.ELEMENT_NODE)
  3165. {
  3166. Element eElement = (Element) nNode;
  3167. response = eElement.getElementsByTagName("string").item(0).getTextContent();
  3168. }
  3169. JSONParser parser1 = new JSONParser();
  3170. JSONParser parser2 = new JSONParser();
  3171. JSONParser parser3 = new JSONParser();
  3172. JSONParser parser4 = new JSONParser();
  3173. JSONParser parser5 = new JSONParser();
  3174. JSONParser parser6 = new JSONParser();
  3175. JSONParser parser7 = new JSONParser();
  3176. KeyFinder finder1 = new KeyFinder();
  3177. KeyFinder finder2 = new KeyFinder();
  3178. KeyFinder finder3 = new KeyFinder();
  3179. KeyFinder finder4 = new KeyFinder();
  3180. KeyFinder finder5 = new KeyFinder();
  3181. KeyFinder finder6 = new KeyFinder();
  3182. KeyFinder finder7 = new KeyFinder();
  3183. finder1.setMatchKey("msgid");
  3184. finder2.setMatchKey("toAddress");
  3185. finder3.setMatchKey("fromAddress");
  3186. finder4.setMatchKey("subject");
  3187. finder5.setMatchKey("message");
  3188. finder6.setMatchKey("encodingType");
  3189. finder7.setMatchKey("receivedTime");
  3190. try {
  3191. while(!finder1.isEnd())
  3192. {
  3193. parser1.parse(response, finder1, true);
  3194. parser2.parse(response, finder2, true);
  3195. parser3.parse(response, finder3, true);
  3196. parser4.parse(response, finder4, true);
  3197. parser5.parse(response, finder5, true);
  3198. parser6.parse(response, finder6, true);
  3199. parser7.parse(response, finder7, true);
  3200. if(finder1.isFound())
  3201. {
  3202. finder1.setFound(false);
  3203. String msgid = (String)finder1.getValue();
  3204. String toAddress = (String)finder2.getValue();
  3205. String fromAddress = (String)finder3.getValue();
  3206. String ecSubject = (String)finder4.getValue();
  3207. byte[] bdcSubject = Base64.decodeBase64(ecSubject);
  3208. String subject = new String(bdcSubject, "UTF-8");
  3209. String ecMessage = (String)finder5.getValue();
  3210. long encodingTypel = (Long)finder6.getValue();
  3211. int encodingType = (int)encodingTypel;
  3212. long receivedTime = Long.valueOf((String)finder7.getValue()).longValue();
  3213. if (!subject.startsWith("[BM-ActivityStream]"))
  3214. {
  3215. if (bmapi_client.equals("true"))
  3216. {
  3217. try {
  3218. String INSERT_RECORD = "INSERT INTO bm_mail(msgid,read,folder,toaddress,fromaddress,subject,message,encodingtype,dtstamp) VALUES(?,?,?,?,?,?,?,?,?)";
  3219. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  3220. pstmt.setString(1, msgid);
  3221. pstmt.setBoolean(2, false);
  3222. pstmt.setString(3, "Inbox");
  3223. pstmt.setString(4, toAddress);
  3224. pstmt.setString(5, fromAddress);
  3225. pstmt.setString(6, ecSubject);
  3226. pstmt.setString(7, ecMessage);
  3227. pstmt.setInt(8, encodingType);
  3228. java.sql.Timestamp sqlDate = new java.sql.Timestamp(receivedTime*1000L);
  3229. pstmt.setTimestamp(9, sqlDate);
  3230. int d = pstmt.executeUpdate();
  3231. if (d == -1) {
  3232. System.out.println("db error : " );
  3233. } else {
  3234. String xml2 = "<?xml version='1.0'?><methodCall><methodName>trashMessage</methodName><params><param><value><string>" + msgid + "</string></value></param></params></methodCall>";
  3235. String response2 = apicall.getAPIcall(xml2);
  3236. }
  3237. pstmt.close();
  3238. } catch (SQLException ex3) {
  3239. ex3.printStackTrace();
  3240. }
  3241. }
  3242. } else {
  3243. System.out.println("Activity Stream Message");
  3244. byte[] bdcMessage = Base64.decodeBase64(ecMessage);
  3245. String message = new String(bdcMessage, "UTF-8");
  3246. DocumentBuilderFactory dbFactory2 = DocumentBuilderFactory.newInstance();
  3247. DocumentBuilder dBuilder2 = dbFactory2.newDocumentBuilder();
  3248. Document doc2 = dBuilder2.parse(new ByteArrayInputStream(message.getBytes()));
  3249. doc2.getDocumentElement().normalize();
  3250. NodeList nList2 = doc2.getElementsByTagName("activity");
  3251. String application = "";
  3252. for (int temp2 = 0; temp2 < nList2.getLength(); temp2++)
  3253. {
  3254. Node nNode2 = nList2.item(temp2);
  3255. if (nNode2.getNodeType() == Node.ELEMENT_NODE)
  3256. {
  3257. Element eElement = (Element) nNode2;
  3258. Node targetNode = eElement.getElementsByTagName("target").item(0);
  3259. Element targetElement = (Element) targetNode;
  3260. application = targetElement.getElementsByTagName("objectType").item(0).getTextContent();
  3261. if (application.equals("followers"))
  3262. {
  3263. bmasAddresses bmasaddresses = new bmasAddresses();
  3264. String useraddress = bmasaddresses.getUser();
  3265. String chanaddress = bmasaddresses.getChan();
  3266. if (toAddress.equals(useraddress))
  3267. {
  3268. FollowersProcessor followprocess = new FollowersProcessor(fromAddress, receivedTime, nNode2, message);
  3269. Boolean processed = followprocess.process();
  3270. if (processed)
  3271. {
  3272. APIcall apicall2 = new APIcall();
  3273. String xml2 = "<?xml version='1.0'?><methodCall><methodName>trashMessage</methodName><params><param><value><string>" + msgid + "</string></value></param></params></methodCall>";
  3274. String apiout = apicall2.getAPIcall(xml2);
  3275. bm_as_processed = true;
  3276. }
  3277. }
  3278. }
  3279. if (application.equals("news"))
  3280. {
  3281. bmasAddresses bmasaddresses = new bmasAddresses();
  3282. String useraddress = bmasaddresses.getUser();
  3283. String chanaddress = bmasaddresses.getChan();
  3284. if ((toAddress.equals(useraddress)) || (toAddress.equals(chanaddress)))
  3285. {
  3286. NewsProcessor newsprocess = new NewsProcessor(fromAddress, receivedTime, nNode2, message);
  3287. Boolean processed = newsprocess.process();
  3288. if (processed)
  3289. {
  3290. APIcall apicall2 = new APIcall();
  3291. String xml2 = "<?xml version='1.0'?><methodCall><methodName>trashMessage</methodName><params><param><value><string>" + msgid + "</string></value></param></params></methodCall>";
  3292. String apiout = apicall2.getAPIcall(xml2);
  3293. bm_as_processed = true;
  3294. }
  3295. }
  3296. }
  3297. }
  3298. }
  3299. }
  3300. } else {
  3301. finder1.endJSON();
  3302. }
  3303. }
  3304. } catch(ParseException pe) {
  3305. pe.printStackTrace();
  3306. }
  3307. }
  3308. } catch (Exception e) {
  3309. e.printStackTrace();
  3310. }
  3311. }
  3312. }
  3313. }
  3314. static class processOutMessages {
  3315. private ActivityStreamdb db = null;
  3316. public processOutMessages(ActivityStreamdb db)
  3317. {
  3318. this.db = db;
  3319. }
  3320. public void process()
  3321. {
  3322. APIcall apicall = new APIcall();
  3323. String xml = "<?xml version='1.0'?><methodCall><methodName>getAllSentMessages</methodName></methodCall>";
  3324. String response = apicall.getAPIcall(xml);
  3325. try {
  3326. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  3327. DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  3328. Document doc = dBuilder.parse(new ByteArrayInputStream(response.getBytes()));
  3329. doc.getDocumentElement().normalize();
  3330. NodeList nList = doc.getElementsByTagName("param");
  3331. for (int temp = 0; temp < nList.getLength(); temp++)
  3332. {
  3333. Node nNode = nList.item(temp);
  3334. if (nNode.getNodeType() == Node.ELEMENT_NODE)
  3335. {
  3336. Element eElement = (Element) nNode;
  3337. response = eElement.getElementsByTagName("string").item(0).getTextContent();
  3338. }
  3339. JSONParser parser1 = new JSONParser();
  3340. JSONParser parser2 = new JSONParser();
  3341. JSONParser parser3 = new JSONParser();
  3342. JSONParser parser4 = new JSONParser();
  3343. JSONParser parser5 = new JSONParser();
  3344. JSONParser parser6 = new JSONParser();
  3345. JSONParser parser7 = new JSONParser();
  3346. JSONParser parser8 = new JSONParser();
  3347. JSONParser parser9 = new JSONParser();
  3348. KeyFinder finder1 = new KeyFinder();
  3349. KeyFinder finder2 = new KeyFinder();
  3350. KeyFinder finder3 = new KeyFinder();
  3351. KeyFinder finder4 = new KeyFinder();
  3352. KeyFinder finder5 = new KeyFinder();
  3353. KeyFinder finder6 = new KeyFinder();
  3354. KeyFinder finder7 = new KeyFinder();
  3355. KeyFinder finder8 = new KeyFinder();
  3356. KeyFinder finder9 = new KeyFinder();
  3357. finder1.setMatchKey("msgid");
  3358. finder2.setMatchKey("toAddress");
  3359. finder3.setMatchKey("fromAddress");
  3360. finder4.setMatchKey("subject");
  3361. finder5.setMatchKey("message");
  3362. finder6.setMatchKey("encodingType");
  3363. finder7.setMatchKey("lastActionTime");
  3364. finder8.setMatchKey("status");
  3365. finder9.setMatchKey("ackData");
  3366. try {
  3367. while(!finder1.isEnd())
  3368. {
  3369. parser1.parse(response, finder1, true);
  3370. parser2.parse(response, finder2, true);
  3371. parser3.parse(response, finder3, true);
  3372. parser4.parse(response, finder4, true);
  3373. parser5.parse(response, finder5, true);
  3374. parser6.parse(response, finder6, true);
  3375. parser7.parse(response, finder7, true);
  3376. parser8.parse(response, finder8, true);
  3377. parser9.parse(response, finder9, true);
  3378. if(finder1.isFound())
  3379. {
  3380. finder1.setFound(false);
  3381. String msgid = (String)finder1.getValue();
  3382. String toAddress = (String)finder2.getValue();
  3383. String fromAddress = (String)finder3.getValue();
  3384. String ecSubject = (String)finder4.getValue();
  3385. byte[] bdcSubject = Base64.decodeBase64(ecSubject);
  3386. String subject = new String(bdcSubject, "UTF-8");
  3387. String ecMessage = (String)finder5.getValue();
  3388. long encodingTypel = (long)finder6.getValue();
  3389. int encodingType = (int)encodingTypel;
  3390. long receivedTime = (long)finder7.getValue();
  3391. String status = (String)finder8.getValue();
  3392. String ackdata = (String)finder9.getValue();
  3393. if (!msgid.equals(""))
  3394. {
  3395. try {
  3396. String INSERT_RECORD = "UPDATE bm_mail SET msgid=? WHERE ackdata=?";
  3397. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  3398. pstmt.setString(1, msgid);
  3399. pstmt.setString(2, ackdata);
  3400. int d = pstmt.executeUpdate();
  3401. if (d == -1) {
  3402. System.out.println("db error : " );
  3403. } else {
  3404. APIcall apicall2 = new APIcall();
  3405. String xml2 = "<?xml version='1.0'?><methodCall><methodName>trashMessage</methodName><params><param><value><string>" + msgid + "</string></value></param></params></methodCall>";
  3406. String apiout = apicall2.getAPIcall(xml2);
  3407. }
  3408. pstmt.close();
  3409. } catch (SQLException ex3) {
  3410. ex3.printStackTrace();
  3411. }
  3412. }
  3413. } else {
  3414. finder1.endJSON();
  3415. }
  3416. }
  3417. } catch(ParseException pe) {
  3418. pe.printStackTrace();
  3419. }
  3420. }
  3421. } catch (Exception e) {
  3422. e.printStackTrace();
  3423. }
  3424. }
  3425. }
  3426. static class FollowersProcessor {
  3427. private Node nNode2;
  3428. private String fromAddress = "";
  3429. private long receivedTime = 0;
  3430. private String inMessage = "";
  3431. public FollowersProcessor(String fromAddress, long receivedTime, Node nNode2, String inMessage)
  3432. {
  3433. this.fromAddress = fromAddress;
  3434. this.receivedTime = receivedTime;
  3435. this.nNode2 = nNode2;
  3436. this.inMessage = inMessage;
  3437. }
  3438. public Boolean process()
  3439. {
  3440. Boolean processed = false;
  3441. String verb = "";
  3442. String id = "";
  3443. if (nNode2.getNodeType() == Node.ELEMENT_NODE)
  3444. {
  3445. Element eElement = (Element) nNode2;
  3446. verb = eElement.getElementsByTagName("verb").item(0).getTextContent();
  3447. Node targetNode = eElement.getElementsByTagName("target").item(0);
  3448. Element targetElement = (Element) targetNode;
  3449. id = targetElement.getElementsByTagName("id").item(0).getTextContent();
  3450. }
  3451. System.out.println("Processing follower message");
  3452. if (verb.equals("follow"))
  3453. {
  3454. System.out.println("Follower message verb follow");
  3455. int mcount = 0;
  3456. String csql = "SELECT COUNT(*) AS rowcount FROM bm_profiles WHERE address=?";
  3457. try {
  3458. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  3459. pstmt.setString(1, fromAddress);
  3460. ResultSet rs = pstmt.executeQuery();
  3461. rs.next();
  3462. mcount = rs.getInt(1);
  3463. // System.out.println(mcount);
  3464. pstmt.close();
  3465. } catch (SQLException ex3) {
  3466. ex3.printStackTrace();
  3467. }
  3468. if (mcount == 0)
  3469. {
  3470. mcount = 0;
  3471. csql = "SELECT COUNT(*) AS rowcount FROM bm_table WHERE msgid=?";
  3472. try {
  3473. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  3474. pstmt.setString(1, id);
  3475. ResultSet rs = pstmt.executeQuery();
  3476. rs.next();
  3477. mcount = rs.getInt(1);
  3478. // System.out.println(mcount);
  3479. pstmt.close();
  3480. } catch (SQLException ex3) {
  3481. ex3.printStackTrace();
  3482. }
  3483. if (mcount == 0)
  3484. {
  3485. System.out.println("Address not found in profiles - creating");
  3486. try {
  3487. String INSERT_RECORD = "INSERT INTO bm_profiles(address,follower,following,dtstamp) VALUES(?,?,?,?,?)";
  3488. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  3489. pstmt.setString(1, fromAddress);
  3490. pstmt.setBoolean(2, true);
  3491. pstmt.setBoolean(3, false);
  3492. java.sql.Timestamp sqlDate = new java.sql.Timestamp(receivedTime*1000L);
  3493. System.out.println(sqlDate);
  3494. pstmt.setTimestamp(4, sqlDate);
  3495. int i = pstmt.executeUpdate();
  3496. if (i == -1) {
  3497. System.out.println("db error : " );
  3498. }
  3499. pstmt.close();
  3500. } catch (SQLException e) {
  3501. e.printStackTrace();
  3502. }
  3503. System.out.println("Message not seen before adding message to bm_table");
  3504. try {
  3505. String INSERT_RECORD = "INSERT INTO bm_table(msgid,address,application,message,dtstamp) VALUES(?,?,?,?,?)";
  3506. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  3507. pstmt.setString(1, id);
  3508. pstmt.setString(2, fromAddress);
  3509. pstmt.setString(3, "followers");
  3510. pstmt.setString(4, inMessage);
  3511. java.sql.Timestamp sqlDate = new java.sql.Timestamp(receivedTime*1000L);
  3512. System.out.println(sqlDate);
  3513. pstmt.setTimestamp(5, sqlDate);
  3514. int i = pstmt.executeUpdate();
  3515. if (i == -1) {
  3516. System.out.println("db error : " );
  3517. }
  3518. pstmt.close();
  3519. } catch (SQLException e) {
  3520. e.printStackTrace();
  3521. }
  3522. }
  3523. processed = true;
  3524. } else {
  3525. System.out.println("Address found in profiles - processing");
  3526. mcount = 0;
  3527. csql = "SELECT COUNT(*) AS rowcount FROM bm_profiles WHERE address=? AND follower=?";
  3528. try {
  3529. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  3530. pstmt.setString(1, fromAddress);
  3531. pstmt.setBoolean(2, false);
  3532. ResultSet rs = pstmt.executeQuery();
  3533. rs.next();
  3534. mcount = rs.getInt(1);
  3535. pstmt.close();
  3536. } catch (SQLException ex3) {
  3537. ex3.printStackTrace();
  3538. }
  3539. if (mcount == 1)
  3540. {
  3541. mcount = 0;
  3542. csql = "SELECT COUNT(*) AS rowcount FROM bm_table WHERE msgid=?";
  3543. try {
  3544. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  3545. pstmt.setString(1, id);
  3546. ResultSet rs = pstmt.executeQuery();
  3547. rs.next();
  3548. mcount = rs.getInt(1);
  3549. // System.out.println(mcount);
  3550. pstmt.close();
  3551. } catch (SQLException ex3) {
  3552. ex3.printStackTrace();
  3553. }
  3554. if (mcount == 0)
  3555. {
  3556. System.out.println("Address not a follower - updating to be");
  3557. Follower follower = new Follower(fromAddress);
  3558. follower.followed();
  3559. System.out.println("Message not seen before adding message to bm_table");
  3560. try {
  3561. String INSERT_RECORD = "INSERT INTO bm_table(msgid,address,application,message,dtstamp) VALUES(?,?,?,?,?)";
  3562. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  3563. pstmt.setString(1, id);
  3564. pstmt.setString(2, fromAddress);
  3565. pstmt.setString(3, "followers");
  3566. pstmt.setString(4, inMessage);
  3567. java.sql.Timestamp sqlDate = new java.sql.Timestamp(receivedTime*1000L);
  3568. System.out.println(sqlDate);
  3569. pstmt.setTimestamp(5, sqlDate);
  3570. int i = pstmt.executeUpdate();
  3571. if (i == -1) {
  3572. System.out.println("db error : " );
  3573. }
  3574. pstmt.close();
  3575. } catch (SQLException e) {
  3576. e.printStackTrace();
  3577. }
  3578. }
  3579. processed = true;
  3580. }
  3581. }
  3582. }
  3583. if (verb.equals("unfollow"))
  3584. {
  3585. System.out.println("Follower message verb unfollow");
  3586. int mcount = 0;
  3587. String csql = "SELECT COUNT(*) AS rowcount FROM bm_profiles WHERE address=? AND follower=?";
  3588. try {
  3589. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  3590. pstmt.setString(1, fromAddress);
  3591. pstmt.setBoolean(2, true);
  3592. ResultSet rs = pstmt.executeQuery();
  3593. rs.next();
  3594. mcount = rs.getInt(1);
  3595. // System.out.println(mcount);
  3596. pstmt.close();
  3597. } catch (SQLException ex3) {
  3598. ex3.printStackTrace();
  3599. }
  3600. if (mcount == 1)
  3601. {
  3602. System.out.println("Address is a follower - updating to not be");
  3603. Follower follower = new Follower(fromAddress);
  3604. follower.unfollowed();
  3605. }
  3606. mcount = 0;
  3607. csql = "SELECT COUNT(*) AS rowcount FROM bm_table WHERE msgid=?";
  3608. try {
  3609. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  3610. pstmt.setString(1, id);
  3611. ResultSet rs = pstmt.executeQuery();
  3612. rs.next();
  3613. mcount = rs.getInt(1);
  3614. // System.out.println(mcount);
  3615. pstmt.close();
  3616. } catch (SQLException ex3) {
  3617. ex3.printStackTrace();
  3618. }
  3619. System.out.println("mcount " + mcount);
  3620. if (mcount == 0)
  3621. {
  3622. System.out.println("Message not seen before adding message to bm_table");
  3623. try {
  3624. String INSERT_RECORD = "INSERT INTO bm_table(msgid,address,application,message,dtstamp) VALUES(?,?,?,?,?)";
  3625. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  3626. pstmt.setString(1, id);
  3627. pstmt.setString(2, fromAddress);
  3628. pstmt.setString(3, "followers");
  3629. pstmt.setString(4, inMessage);
  3630. java.sql.Timestamp sqlDate = new java.sql.Timestamp(receivedTime*1000L);
  3631. pstmt.setTimestamp(5, sqlDate);
  3632. int i = pstmt.executeUpdate();
  3633. if (i == -1) {
  3634. System.out.println("db error : " );
  3635. }
  3636. pstmt.close();
  3637. } catch (SQLException e) {
  3638. e.printStackTrace();
  3639. }
  3640. }
  3641. processed = true;
  3642. }
  3643. return processed;
  3644. }
  3645. }
  3646. static class NewsProcessor {
  3647. private Node nNode2;
  3648. private String fromAddress = "";
  3649. private long receivedTime = 0;
  3650. private String inMessage = "";
  3651. public NewsProcessor(String fromAddress, long receivedTime, Node nNode2, String inMessage)
  3652. {
  3653. this.fromAddress = fromAddress;
  3654. this.receivedTime = receivedTime;
  3655. this.nNode2 = nNode2;
  3656. this.inMessage = inMessage;
  3657. }
  3658. public Boolean process()
  3659. {
  3660. Boolean processed = false;
  3661. String verb = "";
  3662. String id = "";
  3663. String object = "";
  3664. String postactor = "";
  3665. if (nNode2.getNodeType() == Node.ELEMENT_NODE)
  3666. {
  3667. Element eElement = (Element) nNode2;
  3668. verb = eElement.getElementsByTagName("verb").item(0).getTextContent();
  3669. object = eElement.getElementsByTagName("object").item(0).getTextContent();
  3670. Node targetNode = eElement.getElementsByTagName("target").item(0);
  3671. Element targetElement = (Element) targetNode;
  3672. id = targetElement.getElementsByTagName("id").item(0).getTextContent();
  3673. Node actorNode = eElement.getElementsByTagName("actor").item(0);
  3674. Element actorElement = (Element) actorNode;
  3675. postactor = actorElement.getElementsByTagName("id").item(0).getTextContent();
  3676. }
  3677. if (verb.equals("post"))
  3678. {
  3679. int mcount = 0;
  3680. String csql = "SELECT COUNT(*) AS rowcount FROM bm_table WHERE msgid=?";
  3681. try {
  3682. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  3683. pstmt.setString(1, id);
  3684. ResultSet rs = pstmt.executeQuery();
  3685. rs.next();
  3686. mcount = rs.getInt(1);
  3687. pstmt.close();
  3688. } catch (SQLException ex3) {
  3689. ex3.printStackTrace();
  3690. }
  3691. if (mcount == 0)
  3692. {
  3693. int count = 0;
  3694. String csql2 = "SELECT COUNT(*) AS rowcount FROM bm_profiles WHERE address=? AND following=?";
  3695. try {
  3696. PreparedStatement pstmt = db.conn.prepareStatement(csql2);
  3697. pstmt.setString(1, fromAddress);
  3698. pstmt.setBoolean(2, true);
  3699. ResultSet rs = pstmt.executeQuery();
  3700. rs.next();
  3701. count = rs.getInt(1);
  3702. // System.out.println(count);
  3703. pstmt.close();
  3704. } catch (SQLException ex3) {
  3705. ex3.printStackTrace();
  3706. }
  3707. boolean containsHashTag = false;
  3708. if (count == 0)
  3709. {
  3710. Element eElementa = (Element) nNode2;
  3711. Node objectNode = eElementa.getElementsByTagName("object").item(0);
  3712. Element objectElement = (Element) objectNode;
  3713. String postContent = objectElement.getElementsByTagName("content").item(0).getTextContent();
  3714. try {
  3715. String query = "SELECT value FROM bm_settings WHERE setting='hashtag'";
  3716. ResultSet dbq = db.query(query);
  3717. Object o = null;
  3718. for (; dbq.next(); ) {
  3719. o = dbq.getObject(1);
  3720. String hashtag = (String)o;
  3721. hashtag = hashtag + " ";
  3722. if (postContent.indexOf(hashtag) > -1)
  3723. {
  3724. containsHashTag = true;
  3725. }
  3726. }
  3727. db.st.close();
  3728. } catch (SQLException ex3) {
  3729. ex3.printStackTrace();
  3730. }
  3731. }
  3732. System.out.println("Contains hashtag: " + containsHashTag);
  3733. bmasAddresses bmasaddresses = new bmasAddresses();
  3734. String useraddress = bmasaddresses.getUser();
  3735. if ((count == 1) || (containsHashTag) || useraddress.equals(fromAddress))
  3736. {
  3737. try {
  3738. String INSERT_RECORD = "INSERT INTO bm_table(msgid,address,application,message,dtstamp) VALUES(?,?,?,?,?)";
  3739. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  3740. pstmt.setString(1, id);
  3741. pstmt.setString(2, fromAddress);
  3742. pstmt.setString(3, "news");
  3743. pstmt.setString(4, inMessage);
  3744. java.sql.Timestamp sqlDate = new java.sql.Timestamp(receivedTime*1000L);
  3745. pstmt.setTimestamp(5, sqlDate);
  3746. int i = pstmt.executeUpdate();
  3747. if (i == -1) {
  3748. System.out.println("db error : " );
  3749. }
  3750. pstmt.close();
  3751. } catch (SQLException e) {
  3752. e.printStackTrace();
  3753. }
  3754. }
  3755. }
  3756. processed = true;
  3757. }
  3758. if (verb.equals("comment"))
  3759. {
  3760. System.out.println("Processing Comment");
  3761. Element eElementa = (Element) nNode2;
  3762. Node objectNode = eElementa.getElementsByTagName("object").item(0);
  3763. Element objectElement = (Element) objectNode;
  3764. String inReplyTo = objectElement.getElementsByTagName("inReplyTo").item(0).getTextContent();
  3765. String commentID = objectElement.getElementsByTagName("id").item(0).getTextContent();
  3766. String commentContent = objectElement.getElementsByTagName("content").item(0).getTextContent();
  3767. try {
  3768. String query = "SELECT message FROM bm_table WHERE msgid='" + id + "'";
  3769. ResultSet dbq = db.query(query);
  3770. Object o = null;
  3771. for (; dbq.next(); ) {
  3772. o = dbq.getObject(1);
  3773. String message = o.toString();
  3774. try {
  3775. DocumentBuilderFactory dbFactory2 = DocumentBuilderFactory.newInstance();
  3776. DocumentBuilder dBuilder2 = dbFactory2.newDocumentBuilder();
  3777. Document doc2 = dBuilder2.parse(new ByteArrayInputStream(message.getBytes()));
  3778. doc2.getDocumentElement().normalize();
  3779. NodeList nList2 = doc2.getElementsByTagName("activity");
  3780. for (int temp2 = 0; temp2 < nList2.getLength(); temp2++)
  3781. {
  3782. Node nNode2 = nList2.item(temp2);
  3783. if (nNode2.getNodeType() == Node.ELEMENT_NODE)
  3784. {
  3785. Element eElement = (Element) nNode2;
  3786. NodeList objectNodeList = eElement.getElementsByTagName("object");
  3787. for (int temp3 = 0; temp3 < objectNodeList.getLength(); temp3++)
  3788. {
  3789. Node objectCNode = objectNodeList.item(temp3);
  3790. if (objectCNode.getNodeType() == Node.ELEMENT_NODE)
  3791. {
  3792. Element cElement = (Element) objectCNode;
  3793. if (id.equals(inReplyTo))
  3794. {
  3795. System.out.println("Object in reply to found");
  3796. NodeList objectCNodeList = cElement.getElementsByTagName("comments");
  3797. if (objectCNodeList.getLength() == 0)
  3798. {
  3799. Element comments = doc2.createElement("comments");
  3800. Element commentcount = doc2.createElement("totalItems");
  3801. commentcount.appendChild(doc2.createTextNode("0"));
  3802. Element commentItems = doc2.createElement("items");
  3803. comments.appendChild(commentcount);
  3804. comments.appendChild(commentItems);
  3805. objectCNode.appendChild(comments);
  3806. }
  3807. Node commentsN = cElement.getElementsByTagName("comments").item(0);
  3808. Element commentsE = (Element) commentsN;
  3809. Node commentCountN = commentsE.getElementsByTagName("totalItems").item(0);
  3810. Element commentCountE = (Element) commentCountN;
  3811. Node commentItemsN = commentsE.getElementsByTagName("items").item(0);
  3812. Element commentItemsE = (Element) commentItemsN;
  3813. NodeList commentItemL = commentItemsE.getChildNodes();
  3814. int found = 0;
  3815. for (int itemno = 0; itemno < commentItemL.getLength(); itemno++)
  3816. {
  3817. Node itemN = commentItemL.item(itemno);
  3818. Element itemE = (Element) itemN;
  3819. NodeList itemNL = itemE.getChildNodes();
  3820. for (int itemno2 = 0; itemno2 < itemNL.getLength(); itemno2++)
  3821. {
  3822. Node cnode = itemNL.item(itemno2);
  3823. if (cnode.getNodeName().equals("id"))
  3824. {
  3825. String itemid = itemNL.item(itemno2).getTextContent();
  3826. if (itemid.equals(commentID))
  3827. {
  3828. found++;
  3829. }
  3830. }
  3831. }
  3832. }
  3833. if (found > 0)
  3834. {
  3835. System.out.println("Comment has been previously processed");
  3836. processed = true;
  3837. }
  3838. if (!processed)
  3839. {
  3840. System.out.println("Comment has not been previously processed");
  3841. int commentCount = Integer.parseInt(commentsE.getElementsByTagName("totalItems").item(0).getTextContent());
  3842. commentCount = commentCount + 1;
  3843. commentCountN.setTextContent(Integer.toString(commentCount));
  3844. Element commentItem = doc2.createElement("item");
  3845. Element actorItem = doc2.createElement("actor");
  3846. Element objectTypeItem = doc2.createElement("objectType");
  3847. objectTypeItem.appendChild(doc2.createTextNode("person"));
  3848. Element actorIdItem = doc2.createElement("id");
  3849. actorIdItem.appendChild(doc2.createTextNode(fromAddress));
  3850. actorItem.appendChild(objectTypeItem);
  3851. actorItem.appendChild(actorIdItem);
  3852. Element idItem = doc2.createElement("id");
  3853. idItem.appendChild(doc2.createTextNode(commentID));
  3854. Element inReplyToItem = doc2.createElement("inReplyTo");
  3855. inReplyToItem.appendChild(doc2.createTextNode(inReplyTo));
  3856. Element contentItem = doc2.createElement("content");
  3857. contentItem.appendChild(doc2.createTextNode(commentContent));
  3858. commentItem.appendChild(actorItem);
  3859. commentItem.appendChild(idItem);
  3860. commentItem.appendChild(inReplyToItem);
  3861. commentItem.appendChild(contentItem);
  3862. commentItemsE.appendChild(commentItem);
  3863. bmasAddresses bmasaddresses = new bmasAddresses();
  3864. String useraddress = bmasaddresses.getUser();
  3865. if ((!useraddress.equals(fromAddress)) && (useraddress.equals(postactor)))
  3866. {
  3867. try {
  3868. String msg = fromAddress + " commented on your post";
  3869. String INSERT_RECORD = "INSERT INTO bm_alerts(msgid,message,dtstamp) VALUES(?,?,?)";
  3870. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  3871. pstmt.setString(1, id);
  3872. pstmt.setString(2, msg);
  3873. java.sql.Timestamp sqlDate = new java.sql.Timestamp(receivedTime*1000L);
  3874. pstmt.setTimestamp(3, sqlDate);
  3875. int i = pstmt.executeUpdate();
  3876. if (i == -1) {
  3877. System.out.println("db error : " );
  3878. }
  3879. pstmt.close();
  3880. } catch (SQLException ex3) {
  3881. ex3.printStackTrace();
  3882. }
  3883. }
  3884. processed = true;
  3885. }
  3886. } else {
  3887. NodeList commentsNL = cElement.getElementsByTagName("comments");
  3888. if (commentsNL.getLength() > 0)
  3889. {
  3890. Node commentsN = cElement.getElementsByTagName("comments").item(0);
  3891. Element commentsE = (Element) commentsN;
  3892. Node commentCountN = commentsE.getElementsByTagName("totalItems").item(0);
  3893. Element commentCountE = (Element) commentCountN;
  3894. Node commentItemsN = commentsE.getElementsByTagName("items").item(0);
  3895. Element commentItemsE = (Element) commentItemsN;
  3896. NodeList commentItemL = commentItemsE.getChildNodes();
  3897. for (int itemno = 0; itemno < commentItemL.getLength() && !processed; itemno++)
  3898. {
  3899. Node itemo = commentItemL.item(itemno);
  3900. processed = processComment(processed, itemo, doc2, commentID, inReplyTo, commentContent, id);
  3901. }
  3902. }
  3903. }
  3904. }
  3905. }
  3906. }
  3907. }
  3908. TransformerFactory tf = TransformerFactory.newInstance();
  3909. Transformer transformer = tf.newTransformer();
  3910. // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
  3911. // transformer.setOutputProperty(OutputKeys.CDATA-SECTION-ELEMENTS, "content");
  3912. StringWriter writer = new StringWriter();
  3913. transformer.transform(new DOMSource(doc2), new StreamResult(writer));
  3914. String output = writer.getBuffer().toString();
  3915. try {
  3916. String INSERT_RECORD = "UPDATE bm_table SET message=? WHERE msgid=?";
  3917. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  3918. pstmt.setString(1, output);
  3919. pstmt.setString(2, id);
  3920. int i = pstmt.executeUpdate();
  3921. if (i == -1) {
  3922. System.out.println("db error : " );
  3923. }
  3924. pstmt.close();
  3925. } catch (SQLException ex3) {
  3926. ex3.printStackTrace();
  3927. }
  3928. } catch (Exception e) {
  3929. e.printStackTrace();
  3930. }
  3931. }
  3932. db.st.close();
  3933. } catch (SQLException ex3) {
  3934. ex3.printStackTrace();
  3935. }
  3936. }
  3937. if (verb.equals("like"))
  3938. {
  3939. System.out.println("Processing Like");
  3940. Element eElementa = (Element) nNode2;
  3941. Node objectNode = eElementa.getElementsByTagName("object").item(0);
  3942. Element objectElement = (Element) objectNode;
  3943. String inReplyTo = objectElement.getElementsByTagName("inReplyTo").item(0).getTextContent();
  3944. String likeID = objectElement.getElementsByTagName("id").item(0).getTextContent();
  3945. try {
  3946. String query = "SELECT message FROM bm_table WHERE msgid='" + id + "'";
  3947. ResultSet dbq = db.query(query);
  3948. Object o = null;
  3949. for (; dbq.next(); ) {
  3950. o = dbq.getObject(1);
  3951. String message = o.toString();
  3952. try {
  3953. DocumentBuilderFactory dbFactory2 = DocumentBuilderFactory.newInstance();
  3954. DocumentBuilder dBuilder2 = dbFactory2.newDocumentBuilder();
  3955. Document doc2 = dBuilder2.parse(new ByteArrayInputStream(message.getBytes()));
  3956. doc2.getDocumentElement().normalize();
  3957. NodeList nList2 = doc2.getElementsByTagName("activity");
  3958. String totalItems = "";
  3959. String item = "";
  3960. for (int temp2 = 0; temp2 < nList2.getLength(); temp2++)
  3961. {
  3962. Node nNode2 = nList2.item(temp2);
  3963. if (nNode2.getNodeType() == Node.ELEMENT_NODE)
  3964. {
  3965. Element eElement = (Element) nNode2;
  3966. NodeList objectNodeList = eElement.getElementsByTagName("object");
  3967. for (int temp3 = 0; temp3 < objectNodeList.getLength(); temp3++)
  3968. {
  3969. Node objectCNode = objectNodeList.item(temp3);
  3970. if (objectCNode.getNodeType() == Node.ELEMENT_NODE)
  3971. {
  3972. Element cElement = (Element) objectCNode;
  3973. if (id.equals(inReplyTo))
  3974. {
  3975. System.out.println("Object in reply to found");
  3976. NodeList objectCNodeList = cElement.getElementsByTagName("likes");
  3977. if (objectCNodeList.getLength() == 0)
  3978. {
  3979. Element likes = doc2.createElement("likes");
  3980. Element likecount = doc2.createElement("totalItems");
  3981. likecount.appendChild(doc2.createTextNode("0"));
  3982. Element likeItems = doc2.createElement("items");
  3983. likes.appendChild(likecount);
  3984. likes.appendChild(likeItems);
  3985. objectCNode.appendChild(likes);
  3986. }
  3987. Node likesN = cElement.getElementsByTagName("likes").item(0);
  3988. Element likesE = (Element) likesN;
  3989. Node likeCountN = likesE.getElementsByTagName("totalItems").item(0);
  3990. Element likeCountE = (Element) likeCountN;
  3991. Node likeItemsN = likesE.getElementsByTagName("items").item(0);
  3992. Element likeItemsE = (Element) likeItemsN;
  3993. NodeList likeItemL = likeItemsE.getChildNodes();
  3994. int found = 0;
  3995. for (int temp4 = 0; temp4 < likeItemL.getLength(); temp4++)
  3996. {
  3997. Node itemN = likeItemL.item(temp4);
  3998. Element itemE = (Element) itemN;
  3999. Node actorN = itemE.getElementsByTagName("actor").item(0);
  4000. Element actorE = (Element) actorN;
  4001. String liker = actorE.getElementsByTagName("id").item(0).getTextContent();
  4002. System.out.println("Previous liker " + liker + " comparing to " + fromAddress);
  4003. if (liker.equals(fromAddress))
  4004. {
  4005. System.out.println("Liked by Address previously");
  4006. found++;
  4007. }
  4008. NodeList itemNL = itemE.getChildNodes();
  4009. for (int itemno2 = 0; itemno2 < itemNL.getLength(); itemno2++)
  4010. {
  4011. Node cnode = itemNL.item(itemno2);
  4012. if (cnode.getNodeName().equals("id"))
  4013. {
  4014. String itemid = itemNL.item(itemno2).getTextContent();
  4015. System.out.println("Previous itemid " + itemid + " comparing to " + likeID);
  4016. if (itemid.equals(likeID))
  4017. {
  4018. System.out.println("Previously processed itemid " + itemid);
  4019. found++;
  4020. }
  4021. }
  4022. }
  4023. }
  4024. if (found > 0)
  4025. {
  4026. System.out.println("Like has been previously processed");
  4027. processed = true;
  4028. }
  4029. if (found == 0)
  4030. {
  4031. System.out.println("Like has not been previously processed");
  4032. int likeCount = Integer.parseInt(likesE.getElementsByTagName("totalItems").item(0).getTextContent());
  4033. likeCount = likeCount + 1;
  4034. likeCountN.setTextContent(Integer.toString(likeCount));
  4035. Element likeItem = doc2.createElement("item");
  4036. Element actorItem = doc2.createElement("actor");
  4037. Element objectTypeItem = doc2.createElement("objectType");
  4038. objectTypeItem.appendChild(doc2.createTextNode("person"));
  4039. Element actorIdItem = doc2.createElement("id");
  4040. actorIdItem.appendChild(doc2.createTextNode(fromAddress));
  4041. actorItem.appendChild(objectTypeItem);
  4042. actorItem.appendChild(actorIdItem);
  4043. Element idItem = doc2.createElement("id");
  4044. idItem.appendChild(doc2.createTextNode(likeID));
  4045. Element inReplyToItem = doc2.createElement("inReplyTo");
  4046. inReplyToItem.appendChild(doc2.createTextNode(inReplyTo));
  4047. likeItem.appendChild(actorItem);
  4048. likeItem.appendChild(idItem);
  4049. likeItem.appendChild(inReplyToItem);
  4050. likeItemsE.appendChild(likeItem);
  4051. bmasAddresses bmasaddresses = new bmasAddresses();
  4052. String useraddress = bmasaddresses.getUser();
  4053. if ((!useraddress.equals(fromAddress)) && (useraddress.equals(postactor)))
  4054. {
  4055. try {
  4056. String msg = fromAddress + " liked your post";
  4057. String INSERT_RECORD = "INSERT INTO bm_alerts(msgid,message,dtstamp) VALUES(?,?,?)";
  4058. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  4059. pstmt.setString(1, id);
  4060. pstmt.setString(2, msg);
  4061. java.sql.Timestamp sqlDate = new java.sql.Timestamp(receivedTime*1000L);
  4062. pstmt.setTimestamp(3, sqlDate);
  4063. int i = pstmt.executeUpdate();
  4064. if (i == -1) {
  4065. System.out.println("db error : " );
  4066. }
  4067. pstmt.close();
  4068. } catch (SQLException ex3) {
  4069. ex3.printStackTrace();
  4070. }
  4071. }
  4072. processed = true;
  4073. }
  4074. } else {
  4075. NodeList objectCNodeList = cElement.getElementsByTagName("comments");
  4076. if (objectCNodeList.getLength() != 0)
  4077. {
  4078. Node commentsN = cElement.getElementsByTagName("comments").item(0);
  4079. Element commentsE = (Element) commentsN;
  4080. Node commentCountN = commentsE.getElementsByTagName("totalItems").item(0);
  4081. Element commentCountE = (Element) commentCountN;
  4082. Node commentItemsN = commentsE.getElementsByTagName("items").item(0);
  4083. Element commentItemsE = (Element) commentItemsN;
  4084. NodeList commentItemL = commentItemsE.getChildNodes();
  4085. for (int z = 0; z<commentItemL.getLength() && !processed; z++)
  4086. {
  4087. Node itemo = commentItemL.item(z);
  4088. processed = processLike(processed, itemo, doc2, likeID, inReplyTo, id);
  4089. }
  4090. }
  4091. }
  4092. }
  4093. }
  4094. }
  4095. }
  4096. TransformerFactory tf = TransformerFactory.newInstance();
  4097. Transformer transformer = tf.newTransformer();
  4098. // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
  4099. StringWriter writer = new StringWriter();
  4100. transformer.transform(new DOMSource(doc2), new StreamResult(writer));
  4101. String output = writer.getBuffer().toString();
  4102. try {
  4103. String INSERT_RECORD = "UPDATE bm_table SET message=? WHERE msgid=?";
  4104. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  4105. pstmt.setString(1, output);
  4106. pstmt.setString(2, id);
  4107. int i = pstmt.executeUpdate();
  4108. if (i == -1) {
  4109. System.out.println("db error : " );
  4110. }
  4111. pstmt.close();
  4112. } catch (SQLException ex3) {
  4113. ex3.printStackTrace();
  4114. }
  4115. } catch (Exception e) {
  4116. e.printStackTrace();
  4117. }
  4118. }
  4119. db.st.close();
  4120. } catch (SQLException ex3) {
  4121. ex3.printStackTrace();
  4122. }
  4123. }
  4124. return processed;
  4125. }
  4126. public Boolean processComment(Boolean processed, Node objectCNode, Document doc2, String commentID, String inReplyTo, String commentContent, String msgid)
  4127. {
  4128. String id = "";
  4129. NodeList objectCNodeNL = objectCNode.getChildNodes();
  4130. for (int i = 0; i<objectCNodeNL.getLength(); i++)
  4131. {
  4132. Node cnode = objectCNodeNL.item(i);
  4133. if (cnode.getNodeName().equals("id"))
  4134. {
  4135. id = cnode.getTextContent();
  4136. }
  4137. }
  4138. Element cElement = (Element) objectCNode;
  4139. Node actorNode = cElement.getElementsByTagName("actor").item(0);
  4140. Element actorElement = (Element) actorNode;
  4141. String postactor = actorElement.getElementsByTagName("id").item(0).getTextContent();
  4142. if (id.equals(inReplyTo))
  4143. {
  4144. System.out.println("Object in reply to found");
  4145. NodeList objectCNodeList = cElement.getElementsByTagName("comments");
  4146. if (objectCNodeList.getLength() == 0)
  4147. {
  4148. Element comments = doc2.createElement("comments");
  4149. Element commentcount = doc2.createElement("totalItems");
  4150. commentcount.appendChild(doc2.createTextNode("0"));
  4151. Element commentItems = doc2.createElement("items");
  4152. comments.appendChild(commentcount);
  4153. comments.appendChild(commentItems);
  4154. objectCNode.appendChild(comments);
  4155. }
  4156. Node commentsN = cElement.getElementsByTagName("comments").item(0);
  4157. Element commentsE = (Element) commentsN;
  4158. Node commentCountN = commentsE.getElementsByTagName("totalItems").item(0);
  4159. Element commentCountE = (Element) commentCountN;
  4160. Node commentItemsN = commentsE.getElementsByTagName("items").item(0);
  4161. Element commentItemsE = (Element) commentItemsN;
  4162. NodeList commentItemL = commentItemsE.getChildNodes();
  4163. int found = 0;
  4164. for (int itemno = 0; itemno < commentItemL.getLength(); itemno++)
  4165. {
  4166. Node itemN = commentItemL.item(itemno);
  4167. Element itemE = (Element) itemN;
  4168. NodeList itemNL = itemE.getChildNodes();
  4169. for (int itemno2 = 0; itemno2 < itemNL.getLength(); itemno2++)
  4170. {
  4171. Node cnode = itemNL.item(itemno2);
  4172. if (cnode.getNodeName().equals("id"))
  4173. {
  4174. String itemid = itemNL.item(itemno2).getTextContent();
  4175. if (itemid.equals(commentID))
  4176. {
  4177. found++;
  4178. }
  4179. }
  4180. }
  4181. }
  4182. if (found > 0)
  4183. {
  4184. System.out.println("Comment has been previously processed");
  4185. processed = true;
  4186. }
  4187. if (!processed)
  4188. {
  4189. System.out.println("Comment has not been previously processed");
  4190. int commentCount = Integer.parseInt(commentsE.getElementsByTagName("totalItems").item(0).getTextContent());
  4191. commentCount = commentCount + 1;
  4192. commentCountN.setTextContent(Integer.toString(commentCount));
  4193. Element commentItem = doc2.createElement("item");
  4194. Element actorItem = doc2.createElement("actor");
  4195. Element objectTypeItem = doc2.createElement("objectType");
  4196. objectTypeItem.appendChild(doc2.createTextNode("person"));
  4197. Element actorIdItem = doc2.createElement("id");
  4198. actorIdItem.appendChild(doc2.createTextNode(fromAddress));
  4199. actorItem.appendChild(objectTypeItem);
  4200. actorItem.appendChild(actorIdItem);
  4201. Element idItem = doc2.createElement("id");
  4202. idItem.appendChild(doc2.createTextNode(commentID));
  4203. Element inReplyToItem = doc2.createElement("inReplyTo");
  4204. inReplyToItem.appendChild(doc2.createTextNode(inReplyTo));
  4205. Element contentItem = doc2.createElement("content");
  4206. contentItem.appendChild(doc2.createTextNode(commentContent));
  4207. commentItem.appendChild(actorItem);
  4208. commentItem.appendChild(idItem);
  4209. commentItem.appendChild(inReplyToItem);
  4210. commentItem.appendChild(contentItem);
  4211. commentItemsE.appendChild(commentItem);
  4212. bmasAddresses bmasaddresses = new bmasAddresses();
  4213. String useraddress = bmasaddresses.getUser();
  4214. if ((!useraddress.equals(fromAddress)) && (useraddress.equals(postactor)))
  4215. {
  4216. try {
  4217. String msg = fromAddress + " commented on your comment";
  4218. String INSERT_RECORD = "INSERT INTO bm_alerts(msgid,message,dtstamp) VALUES(?,?,?)";
  4219. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  4220. pstmt.setString(1, msgid);
  4221. pstmt.setString(2, msg);
  4222. java.sql.Timestamp sqlDate = new java.sql.Timestamp(receivedTime*1000L);
  4223. pstmt.setTimestamp(3, sqlDate);
  4224. int i = pstmt.executeUpdate();
  4225. if (i == -1) {
  4226. System.out.println("db error : " );
  4227. }
  4228. pstmt.close();
  4229. } catch (SQLException ex3) {
  4230. ex3.printStackTrace();
  4231. }
  4232. }
  4233. processed = true;
  4234. }
  4235. } else {
  4236. NodeList commentsNL = cElement.getElementsByTagName("comments");
  4237. if (commentsNL.getLength() > 0)
  4238. {
  4239. Node commentsN = cElement.getElementsByTagName("comments").item(0);
  4240. Element commentsE = (Element) commentsN;
  4241. Node commentCountN = commentsE.getElementsByTagName("totalItems").item(0);
  4242. Element commentCountE = (Element) commentCountN;
  4243. Node commentItemsN = commentsE.getElementsByTagName("items").item(0);
  4244. Element commentItemsE = (Element) commentItemsN;
  4245. NodeList commentItemL = commentItemsE.getChildNodes();
  4246. for (int itemno = 0; itemno < commentItemL.getLength() && !processed; itemno++)
  4247. {
  4248. Node itemo = commentItemL.item(itemno);
  4249. Boolean processedo = processComment(processed, itemo, doc2, commentID, inReplyTo, commentContent, msgid);
  4250. processed = processedo;
  4251. }
  4252. }
  4253. }
  4254. return processed;
  4255. }
  4256. public Boolean processLike(Boolean processed, Node objectCNode, Document doc2, String likeID, String inReplyTo, String msgid)
  4257. {
  4258. String id = "";
  4259. NodeList objectCNodeNL = objectCNode.getChildNodes();
  4260. for (int i = 0; i<objectCNodeNL.getLength(); i++)
  4261. {
  4262. Node cnode = objectCNodeNL.item(i);
  4263. if (cnode.getNodeName().equals("id"))
  4264. {
  4265. id = cnode.getTextContent();
  4266. }
  4267. }
  4268. Element cElement = (Element) objectCNode;
  4269. Node actorNode = cElement.getElementsByTagName("actor").item(0);
  4270. Element actorElement = (Element) actorNode;
  4271. String postactor = actorElement.getElementsByTagName("id").item(0).getTextContent();
  4272. if (id.equals(inReplyTo))
  4273. {
  4274. NodeList objectCNodeList = cElement.getElementsByTagName("likes");
  4275. if (objectCNodeList.getLength() == 0)
  4276. {
  4277. Element likes = doc2.createElement("likes");
  4278. Element likecount = doc2.createElement("totalItems");
  4279. likecount.appendChild(doc2.createTextNode("0"));
  4280. Element likeItems = doc2.createElement("items");
  4281. likes.appendChild(likecount);
  4282. likes.appendChild(likeItems);
  4283. objectCNode.appendChild(likes);
  4284. }
  4285. Node likesN = cElement.getElementsByTagName("likes").item(0);
  4286. Element likesE = (Element) likesN;
  4287. Node likeCountN = likesE.getElementsByTagName("totalItems").item(0);
  4288. Element likeCountE = (Element) likeCountN;
  4289. Node likeItemsN = likesE.getElementsByTagName("items").item(0);
  4290. Element likeItemsE = (Element) likeItemsN;
  4291. NodeList likeItemL = likeItemsE.getChildNodes();
  4292. int found = 0;
  4293. for (int temp4 = 0; temp4 < likeItemL.getLength(); temp4++)
  4294. {
  4295. Node itemN = likeItemL.item(temp4);
  4296. Element itemE = (Element) itemN;
  4297. Node actorN = itemE.getElementsByTagName("actor").item(0);
  4298. Element actorE = (Element) actorN;
  4299. String liker = actorE.getElementsByTagName("id").item(0).getTextContent();
  4300. System.out.println("Previous liker " + liker + " comparing to " + fromAddress);
  4301. if (liker.equals(fromAddress))
  4302. {
  4303. System.out.println("Liked by address previously");
  4304. found++;
  4305. }
  4306. NodeList itemNL = itemE.getChildNodes();
  4307. for (int itemno2 = 0; itemno2 < itemNL.getLength(); itemno2++)
  4308. {
  4309. Node cnode = itemNL.item(itemno2);
  4310. if (cnode.getNodeName().equals("id"))
  4311. {
  4312. String itemid = itemNL.item(itemno2).getTextContent();
  4313. System.out.println("Previous itemid " + itemid + " comparing to " + likeID);
  4314. if (itemid.equals(likeID))
  4315. {
  4316. System.out.println("Previously processed itemid");
  4317. found++;
  4318. }
  4319. }
  4320. }
  4321. }
  4322. if (found > 0)
  4323. {
  4324. System.out.println("Like has been previously processed");
  4325. processed = true;
  4326. }
  4327. if (found == 0)
  4328. {
  4329. System.out.println("Like has not been previously processed");
  4330. int likeCount = Integer.parseInt(likesE.getElementsByTagName("totalItems").item(0).getTextContent());
  4331. likeCount = likeCount + 1;
  4332. likeCountN.setTextContent(Integer.toString(likeCount));
  4333. Element likeItem = doc2.createElement("item");
  4334. Element actorItem = doc2.createElement("actor");
  4335. Element objectTypeItem = doc2.createElement("objectType");
  4336. objectTypeItem.appendChild(doc2.createTextNode("person"));
  4337. Element actorIdItem = doc2.createElement("id");
  4338. actorIdItem.appendChild(doc2.createTextNode(fromAddress));
  4339. actorItem.appendChild(objectTypeItem);
  4340. actorItem.appendChild(actorIdItem);
  4341. Element idItem = doc2.createElement("id");
  4342. idItem.appendChild(doc2.createTextNode(likeID));
  4343. Element inReplyToItem = doc2.createElement("inReplyTo");
  4344. inReplyToItem.appendChild(doc2.createTextNode(inReplyTo));
  4345. likeItem.appendChild(actorItem);
  4346. likeItem.appendChild(idItem);
  4347. likeItem.appendChild(inReplyToItem);
  4348. likeItemsE.appendChild(likeItem);
  4349. bmasAddresses bmasaddresses = new bmasAddresses();
  4350. String useraddress = bmasaddresses.getUser();
  4351. if ((!useraddress.equals(fromAddress)) && (useraddress.equals(postactor)))
  4352. {
  4353. try {
  4354. String msg = fromAddress + " liked your comment";
  4355. String INSERT_RECORD = "INSERT INTO bm_alerts(msgid,message,dtstamp) VALUES(?,?,?)";
  4356. PreparedStatement pstmt = db.conn.prepareStatement(INSERT_RECORD);
  4357. pstmt.setString(1, msgid);
  4358. pstmt.setString(2, msg);
  4359. java.sql.Timestamp sqlDate = new java.sql.Timestamp(receivedTime*1000L);
  4360. pstmt.setTimestamp(3, sqlDate);
  4361. int i = pstmt.executeUpdate();
  4362. if (i == -1) {
  4363. System.out.println("db error : " );
  4364. }
  4365. pstmt.close();
  4366. } catch (SQLException ex3) {
  4367. ex3.printStackTrace();
  4368. }
  4369. }
  4370. processed = true;
  4371. }
  4372. } else {
  4373. NodeList objectCNodeList = cElement.getElementsByTagName("comments");
  4374. if (objectCNodeList.getLength() != 0)
  4375. {
  4376. Node commentsN = cElement.getElementsByTagName("comments").item(0);
  4377. Element commentsE = (Element) commentsN;
  4378. Node commentCountN = commentsE.getElementsByTagName("totalItems").item(0);
  4379. Element commentCountE = (Element) commentCountN;
  4380. Node commentItemsN = commentsE.getElementsByTagName("items").item(0);
  4381. Element commentItemsE = (Element) commentItemsN;
  4382. NodeList commentItemL = commentItemsE.getChildNodes();
  4383. for (int z = 0; z<commentItemL.getLength() && !processed; z++)
  4384. {
  4385. Node itemo = commentItemL.item(z);
  4386. processed = processLike(processed, itemo, doc2, likeID, inReplyTo, msgid);
  4387. }
  4388. }
  4389. }
  4390. return processed;
  4391. }
  4392. }
  4393. static class APIcall {
  4394. public APIcall() {
  4395. }
  4396. public String getAPIcall(String xml)
  4397. {
  4398. String response = "";
  4399. String bmapi_ip = "";
  4400. String bmapi_port = "";
  4401. String bmapi_user = "";
  4402. String bmapi_password = "";
  4403. try {
  4404. String query = "SELECT value FROM bm_settings WHERE setting='bmapi_ip'";
  4405. ResultSet dbq = db.query(query);
  4406. Object o = null;
  4407. for (; dbq.next(); ) {
  4408. o = dbq.getObject(1);
  4409. bmapi_ip = (String)o;
  4410. }
  4411. } catch (SQLException ex3) {
  4412. ex3.printStackTrace();
  4413. }
  4414. try {
  4415. String query = "SELECT value FROM bm_settings WHERE setting='bmapi_port'";
  4416. ResultSet dbq = db.query(query);
  4417. Object o = null;
  4418. for (; dbq.next(); ) {
  4419. o = dbq.getObject(1);
  4420. bmapi_port = (String)o;
  4421. }
  4422. } catch (SQLException ex3) {
  4423. ex3.printStackTrace();
  4424. }
  4425. try {
  4426. String query = "SELECT value FROM bm_settings WHERE setting='bmapi_user'";
  4427. ResultSet dbq = db.query(query);
  4428. Object o = null;
  4429. for (; dbq.next(); ) {
  4430. o = dbq.getObject(1);
  4431. bmapi_user = (String)o;
  4432. }
  4433. } catch (SQLException ex3) {
  4434. ex3.printStackTrace();
  4435. }
  4436. try {
  4437. String query = "SELECT value FROM bm_settings WHERE setting='bmapi_password'";
  4438. ResultSet dbq = db.query(query);
  4439. Object o = null;
  4440. for (; dbq.next(); ) {
  4441. o = dbq.getObject(1);
  4442. bmapi_password = (String)o;
  4443. }
  4444. } catch (SQLException ex3) {
  4445. ex3.printStackTrace();
  4446. }
  4447. if (bmapi_user.equals("default") && bmapi_password.equals("default"))
  4448. {
  4449. System.out.println("The api user and password are not set");
  4450. }
  4451. String strURL = "http://" + bmapi_ip + ":" + bmapi_port + "/";
  4452. HttpPost post = new HttpPost(strURL);
  4453. try {
  4454. DefaultHttpClient httpclient = new DefaultHttpClient();
  4455. String auth = bmapi_user + ":" + bmapi_password;
  4456. String encoding = Base64.encodeBase64String(auth.getBytes());
  4457. post.setHeader("Authorization", "Basic " + encoding);
  4458. StringEntity requestEntity = new StringEntity(xml);
  4459. post.setEntity(requestEntity);
  4460. HttpResponse result = httpclient.execute(post);
  4461. HttpEntity resulte = result.getEntity();
  4462. String responsestring = EntityUtils.toString(resulte, "UTF-8");
  4463. response = responsestring;
  4464. HttpEntity poster = post.getEntity();
  4465. try {
  4466. EntityUtils.consume(poster);
  4467. } finally {
  4468. post.releaseConnection();
  4469. }
  4470. } catch (IOException e) {
  4471. e.printStackTrace();
  4472. } finally {
  4473. post.releaseConnection();
  4474. }
  4475. return response;
  4476. }
  4477. }
  4478. static class StringHash {
  4479. public StringHash()
  4480. {
  4481. }
  4482. public byte[] byteArrayHash(String input) throws NoSuchAlgorithmException {
  4483. MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
  4484. byte[] inputBytes = input.getBytes();
  4485. byte[] inputHash = sha256.digest(inputBytes);
  4486. return inputHash;
  4487. }
  4488. public String stringHash(String input) throws NoSuchAlgorithmException {
  4489. MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
  4490. byte[] inputBytes = input.getBytes();
  4491. byte[] inputHash = sha256.digest(inputBytes);
  4492. StringBuffer sb = new StringBuffer();
  4493. for (int i = 0; i < inputHash.length; i++) {
  4494. sb.append(Integer.toString((inputHash[i] & 0xff) + 0x100, 16).substring(1));
  4495. }
  4496. return sb.toString();
  4497. }
  4498. }
  4499. static class HTMLBuilder {
  4500. private String response = "";
  4501. public HTMLBuilder() {
  4502. }
  4503. public String getHTML()
  4504. {
  4505. return response;
  4506. }
  4507. public void append(String in)
  4508. {
  4509. response = response + in;
  4510. }
  4511. public void appendHTMLHead()
  4512. {
  4513. HTMLHead temp = new HTMLHead();
  4514. response = response + temp.getHTMLHead();
  4515. }
  4516. public void appendHTMLHeadEnd()
  4517. {
  4518. HTMLHeadEnd temp = new HTMLHeadEnd();
  4519. response = response + temp.getHTMLHeadEnd();
  4520. }
  4521. public void appendHTMLHeadEndNews()
  4522. {
  4523. HTMLHeadEndNews temp = new HTMLHeadEndNews();
  4524. response = response + temp.getHTMLHeadEndNews();
  4525. }
  4526. public void appendHTMLStyle()
  4527. {
  4528. HTMLStyle temp = new HTMLStyle();
  4529. response = response + temp.getHTMLStyle();
  4530. }
  4531. public void appendHTMLScript()
  4532. {
  4533. HTMLScript temp = new HTMLScript();
  4534. response = response + temp.getHTMLScript();
  4535. }
  4536. public void appendNAVBar()
  4537. {
  4538. NAVBar temp = new NAVBar();
  4539. response = response + temp.getNAVBar();
  4540. }
  4541. public void appendMainStart()
  4542. {
  4543. MainStart temp = new MainStart();
  4544. response = response + temp.getMainStart();
  4545. }
  4546. public void appendMainLeftMenu()
  4547. {
  4548. MainLeftMenu temp = new MainLeftMenu();
  4549. response = response + temp.getMainLeftMenu();
  4550. }
  4551. public void appendMailLeftMenu()
  4552. {
  4553. MailLeftMenu temp = new MailLeftMenu(db);
  4554. response = response + temp.getMailLeftMenu();
  4555. }
  4556. public void appendProfilesLeftMenu()
  4557. {
  4558. ProfilesLeftMenu temp = new ProfilesLeftMenu(db);
  4559. response = response + temp.getProfilesLeftMenu();
  4560. }
  4561. public void appendSettingsLeftMenu()
  4562. {
  4563. SettingsLeftMenu temp = new SettingsLeftMenu();
  4564. response = response + temp.getSettingsLeftMenu();
  4565. }
  4566. public void appendNewsPostForm()
  4567. {
  4568. NewsPostForm temp = new NewsPostForm();
  4569. response = response + temp.getNewsPostForm();
  4570. }
  4571. public void appendEndDiv()
  4572. {
  4573. EndDiv temp = new EndDiv();
  4574. response = response + temp.getEndDiv();
  4575. }
  4576. public void appendEndBody()
  4577. {
  4578. EndBody temp = new EndBody();
  4579. response = response + temp.getEndBody();
  4580. }
  4581. public void appendDefaultStart()
  4582. {
  4583. appendHTMLHead();
  4584. appendHTMLStyle();
  4585. appendHTMLScript();
  4586. appendHTMLHeadEnd();
  4587. appendNAVBar();
  4588. }
  4589. }
  4590. static class HTMLHead {
  4591. public HTMLHead() {
  4592. }
  4593. public String getHTMLHead()
  4594. {
  4595. String startDoc ="<!DOCTYPE html><html><head><meta charset='utf-8' /><meta http-equiv='X-UA-Compatible' content='IE=8'/><title>BM-ActivityStream</title>";
  4596. return startDoc;
  4597. }
  4598. }
  4599. static class HTMLHeadEnd {
  4600. public HTMLHeadEnd() {
  4601. }
  4602. public String getHTMLHeadEnd()
  4603. {
  4604. String startDoc ="</head><body>";
  4605. return startDoc;
  4606. }
  4607. }
  4608. static class HTMLHeadEndNews {
  4609. public HTMLHeadEndNews() {
  4610. }
  4611. public String getHTMLHeadEndNews()
  4612. {
  4613. String startDoc ="</head><body onload='fillCategory();'>";
  4614. return startDoc;
  4615. }
  4616. }
  4617. static class HTMLStyle {
  4618. public HTMLStyle() {
  4619. }
  4620. public String getHTMLStyle()
  4621. {
  4622. String startDoc ="<style type='text/css'>html, body{ margin:0; padding:0;}nav{background-color:black;color:white;height: 40px;width: 100%;position: fixed;}nav ul {list-style: none;}nav ul li {margin: 0 14px;}nav ul li a { display:block; color: white; font-weight: 700; letter-spacing: 0.08em; text-decoration: none; text-transform: uppercase;float: left;margin: 0 14px;}nav ul li a.norm { display:block; color: white; font-weight: 700; letter-spacing: 0.08em; text-decoration: none; text-transform: uppercase;float: left;margin: 0 14px;}nav ul li a.red { display:block; color: red; font-weight: 700; letter-spacing: 0.08em; text-decoration: none; text-transform: uppercase;float: left;margin: 0 14px;}nav ul li a.normright { display:block; color: white; font-weight: 700; letter-spacing: 0.08em; text-decoration: none; text-transform: uppercase; float: right;margin: 0 14px;}#leftmenu {width: 100px;margin-top: 55px;margin-left: 70px;margin-right: 200px;float: left;position: fixed;}#maincontent {width: 960px;margin-top: 55px;margin-left: 200px;margin-right: 200px;float: left;}#imagePreview img { border:1px solid; display: block; max-width: 825px; max-height: 825px; width; auto; height; auto; margin-top: auto; margin-bottom: auto; margin-left: 0px; margin-right: auto; visibility: hidden; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);} #newsimage img { border:1px solid; display: block; max-width: 825px; max-height: 825px; width; auto; height; auto; margin-top: auto; margin-bottom: auto; margin-left: 0px; margin-right: auto; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);} pre {display: block;white-space: pre-wrap;word-wrap: break-word;} #comment{margin-left: 10px;margin-right: 10px;border:1px solid #999;page-break-inside:avoid} #comment_form{margin-left: 10px;margin-right: 10px;page-break-inside:avoid} #post{margin-left: 0px;border:1px solid #999;page-break-inside:avoid}</style>";
  4623. return startDoc;
  4624. }
  4625. }
  4626. static class HTMLScript {
  4627. public HTMLScript() {
  4628. }
  4629. public String getHTMLScript()
  4630. {
  4631. String startDoc ="<script language='javascript'>" +
  4632. "function movecomment_form(x,y,z,a,b,c) {" +
  4633. " document.getElementById(x).appendChild(document.getElementById(y));" +
  4634. " var form = document.getElementById(z);" +
  4635. " for (var i = 0, max = form.length; i < max; i++) " +
  4636. " { " +
  4637. " if (form[i].name == 'address') " +
  4638. " { " +
  4639. " form[i].value = a; " +
  4640. " } " +
  4641. " if (form[i].name == 'targetid') " +
  4642. " { " +
  4643. " form[i].value = b; " +
  4644. " } " +
  4645. " if (form[i].name == 'inreplytoid') " +
  4646. " { " +
  4647. " form[i].value = c; " +
  4648. " } " +
  4649. " } " +
  4650. "}" +
  4651. "function toggle(x) {" +
  4652. " var allInputs = document.getElementsByName(x.name);" +
  4653. " for (var i = 0, max = allInputs.length; i < max; i++) " +
  4654. " { " +
  4655. " if (allInputs[i].type == 'checkbox')" +
  4656. " if (x.checked == true)" +
  4657. " allInputs[i].checked = true; " +
  4658. " else" +
  4659. " allInputs[i].checked = false;" +
  4660. " }" +
  4661. "}" +
  4662. "function selectAll()" +
  4663. "{" +
  4664. " var form = document.forms[0];" +
  4665. " for (var i=0; i<form.To.length; i++) {" +
  4666. " form.To.options[i].selected = true;" +
  4667. " }" +
  4668. " return true;" +
  4669. "}" +
  4670. "function fillCategory(){";
  4671. startDoc = startDoc + "var followvar = [";
  4672. try {
  4673. String query = "SELECT address FROM bm_profiles WHERE follower=true ORDER BY dtstamp DESC";
  4674. // System.out.println(query);
  4675. ResultSet dbq = db.query(query);
  4676. Object o = null;
  4677. int count = 0;
  4678. for (; dbq.next(); ) {
  4679. if (count != 0)
  4680. {
  4681. startDoc = startDoc + ", ";
  4682. }
  4683. count++;
  4684. o = dbq.getObject(1);
  4685. String address = (String)o;
  4686. startDoc = startDoc + "'" + address + "'";
  4687. }
  4688. db.st.close();
  4689. } catch (SQLException ex3) {
  4690. ex3.printStackTrace();
  4691. }
  4692. startDoc = startDoc + "];";
  4693. startDoc = startDoc + " for (var i=0; i < followvar.length;++i){ " +
  4694. " addOption(document.share.FromLB, followvar[i], followvar[i]);" +
  4695. " }";
  4696. startDoc = startDoc + "addOption(document.share.followers, 'Followers', 'Followers', '');" +
  4697. "addOption(document.share.followers, 'Lists', 'Lists', '');" +
  4698. "addOption(document.share.followers, 'Public', 'Public', '');}" +
  4699. "function SelectSubCat()" +
  4700. "{removeAllOptions(document.share.FromLB);";
  4701. startDoc = startDoc + "var followvar = [";
  4702. try {
  4703. String query = "SELECT address FROM bm_profiles WHERE follower=true ORDER BY dtstamp DESC";
  4704. // System.out.println(query);
  4705. ResultSet dbq = db.query(query);
  4706. Object o = null;
  4707. int count = 0;
  4708. for (; dbq.next(); ) {
  4709. if (count != 0)
  4710. {
  4711. startDoc = startDoc + ", ";
  4712. }
  4713. count++;
  4714. o = dbq.getObject(1);
  4715. String address = (String)o;
  4716. startDoc = startDoc + "'" + address + "'";
  4717. }
  4718. db.st.close();
  4719. } catch (SQLException ex3) {
  4720. ex3.printStackTrace();
  4721. }
  4722. startDoc = startDoc + "];";
  4723. startDoc = startDoc + "var listsvar = [";
  4724. try {
  4725. String query = "SELECT DISTINCT list FROM bm_profiles_lists";
  4726. // System.out.println(query);
  4727. ResultSet dbq = db.query(query);
  4728. Object o = null;
  4729. int count = 0;
  4730. for (; dbq.next(); ) {
  4731. if (count != 0)
  4732. {
  4733. startDoc = startDoc + ", ";
  4734. }
  4735. count++;
  4736. o = dbq.getObject(1);
  4737. String list = (String)o;
  4738. startDoc = startDoc + "'" + list + "'";
  4739. }
  4740. db.st.close();
  4741. } catch (SQLException ex3) {
  4742. ex3.printStackTrace();
  4743. }
  4744. startDoc = startDoc + "];";
  4745. startDoc = startDoc + "if(document.share.followers.value == 'Followers')" +
  4746. "{removeAllOptions(document.share.To);" +
  4747. " for (var i=0; i < followvar.length;++i){ " +
  4748. " addOption(document.share.FromLB, followvar[i], followvar[i]);" +
  4749. " }" +
  4750. "}";
  4751. startDoc = startDoc + "if(document.share.followers.value == 'Lists') " +
  4752. "{removeAllOptions(document.share.To);" +
  4753. " for (var i=0; i < listsvar.length;++i){ " +
  4754. " addOption(document.share.FromLB, listsvar[i], listsvar[i]);" +
  4755. " }" +
  4756. "}";
  4757. startDoc = startDoc + "if(document.share.followers.value == 'Public')" +
  4758. "{removeAllOptions(document.share.To);" +
  4759. "addOption(document.share.FromLB,'Signed', 'Signed');" +
  4760. "addOption(document.share.FromLB,'Anonymous', 'Anonymous');}}" +
  4761. "function removeAllOptions(selectbox){" +
  4762. " var i;" +
  4763. " for(i=selectbox.options.length-1;i>=0;i--)" +
  4764. " { selectbox.remove(i);" +
  4765. " }" +
  4766. "}" +
  4767. "function addOption(selectbox, value, text )" +
  4768. "{ var optn = document.createElement('OPTION');" +
  4769. " optn.text = text;" +
  4770. " optn.value = value;" +
  4771. " selectbox.options.add(optn);" +
  4772. "}" +
  4773. "function move(tbFrom, tbTo)" +
  4774. "{ var arrFrom = new Array();" +
  4775. " var arrTo = new Array();" +
  4776. " var arrLU = new Array();" +
  4777. "if(document.share.followers.value == 'Public')" +
  4778. "{" +
  4779. " if (tbFrom.id != 'To')" +
  4780. " {" +
  4781. " var zz; for (zz = 0; zz< tbFrom.options.length; zz++)" +
  4782. " {" +
  4783. " if (tbFrom.options[zz].selected && tbFrom.options[zz].value== 'Anonymous')" +
  4784. " {" +
  4785. " removeAllOptions(document.share.To);" +
  4786. " removeAllOptions(document.share.FromLB);" +
  4787. " addOption(document.share.FromLB,'Signed', 'Signed');" +
  4788. " addOption(document.share.To,'Anonymous', 'Anonymous');" +
  4789. " }" +
  4790. " if (tbFrom.options[zz].selected && tbFrom.options[zz].value == 'Signed')" +
  4791. " {" +
  4792. " removeAllOptions(document.share.To);" +
  4793. " removeAllOptions(document.share.FromLB);" +
  4794. " addOption(document.share.FromLB,'Anonymous', 'Anonymous');" +
  4795. " addOption(document.share.To,'Signed', 'Signed');" +
  4796. " }" +
  4797. " }" +
  4798. " }" +
  4799. "}" +
  4800. " var i; for (i = 0; i < tbTo.options.length; i++)" +
  4801. " { arrLU[tbTo.options[i].text] = tbTo.options[i].value;" +
  4802. " arrTo[i] = tbTo.options[i].text;" +
  4803. " }" +
  4804. " var fLength = 0;" +
  4805. " var tLength = arrTo.length;" +
  4806. " for(i = 0; i < tbFrom.options.length; i++)" +
  4807. " { arrLU[tbFrom.options[i].text] = tbFrom.options[i].value;" +
  4808. " if (tbFrom.options[i].selected && tbFrom.options[i].value != '')" +
  4809. " { arrTo[tLength] = tbFrom.options[i].text;" +
  4810. " tLength++;" +
  4811. " } else {" +
  4812. " arrFrom[fLength] = tbFrom.options[i].text;" +
  4813. " fLength++;" +
  4814. " }" +
  4815. "}" +
  4816. "tbFrom.length = 0;" +
  4817. "tbTo.length = 0;" +
  4818. "var ii;" +
  4819. "for(ii = 0; ii < arrFrom.length; ii++)" +
  4820. " { var no = new Option();" +
  4821. " no.value = arrLU[arrFrom[ii]];" +
  4822. " no.text = arrFrom[ii];" +
  4823. " tbFrom[ii] = no;" +
  4824. "}" +
  4825. " for(ii = 0; ii < arrTo.length; ii++)" +
  4826. " { var no = new Option();" +
  4827. " no.value = arrLU[arrTo[ii]];" +
  4828. " no.text = arrTo[ii];" +
  4829. " tbTo[ii] = no;" +
  4830. "}" +
  4831. "}" +
  4832. "var loadImageFile = (function () {" +
  4833. " if (window.FileReader) {" +
  4834. " var oPreviewImg = null, oFReader = new window.FileReader()," +
  4835. " rFilter = /^(?:image\\/" +
  4836. "bmp|image\\" +
  4837. "/cis\\-cod|image\\" +
  4838. "/gif|image\\" +
  4839. "/ief|image\\" +
  4840. "/jpeg|image\\/" +
  4841. "jpeg|image\\/" +
  4842. "jpeg|image\\/" +
  4843. "pipeg|image\\/" +
  4844. "png|" +
  4845. "image\\/" +
  4846. "svg\\+xml|image\\/" +
  4847. "tiff|image\\/" +
  4848. "x\\-cmu\\-raster|image\\/" +
  4849. "x\\-cmx|image\\/" +
  4850. "x\\-icon|image\\/" +
  4851. "x\\-portable\\-anymap|image\\/" +
  4852. "x\\-portable\\-bitmap|image" +
  4853. "\\/" +
  4854. "x\\-portable\\-graymap|image\\/" +
  4855. "x\\-portable\\-pixmap|image\\/" +
  4856. "x\\-rgb|image\\/" +
  4857. "x\\-xbitmap|image\\/" +
  4858. "x\\-xpixmap|image\\/" +
  4859. "x\\-xwindowdump)$/" +
  4860. "i;" +
  4861. " oFReader.onload = function (oFREvent) {" +
  4862. " if (!oPreviewImg) {" +
  4863. " var newPreview = document.getElementById('imagePreview');" +
  4864. " oPreviewImg = new Image();" +
  4865. " oPreviewImg.style.visibility = \"visible\";" +
  4866. " newPreview.appendChild(oPreviewImg);" +
  4867. " }" +
  4868. " oPreviewImg.src = oFREvent.target.result; }; return function () { var aFiles = document.getElementById('imagefile').files; if (aFiles.length === 0) { return; } if (!rFilter.test(aFiles[0].type)) { alert('You must select a valid image file!'); return; } oFReader.readAsDataURL(aFiles[0]); } } if (navigator.appName === 'Microsoft Internet Explorer') { return function () { document.getElementById('imagePreview').filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = document.getElementById('imagefile').value; } }})();" +
  4869. " function unloadImageFile(){" +
  4870. " var list=document.getElementById('imagePreview');" +
  4871. " list.removeChild(list.childNodes[0]);" +
  4872. " }" +
  4873. "</script>";
  4874. return startDoc;
  4875. }
  4876. }
  4877. static class NAVBar {
  4878. public NAVBar() {
  4879. }
  4880. public String getNAVBar()
  4881. {
  4882. int mcount = 0;
  4883. ResultSet rs = null;
  4884. java.sql.Timestamp msgdtstamp = new java.sql.Timestamp(new java.util.Date().getTime());
  4885. String tsql = "SELECT dtstamp FROM bm_lastclick WHERE wpage=?";
  4886. try {
  4887. PreparedStatement pstmt = db.conn.prepareStatement(tsql);
  4888. pstmt.setString(1, "MESSAGES");
  4889. rs = pstmt.executeQuery();
  4890. rs.next();
  4891. msgdtstamp = rs.getTimestamp(1);
  4892. // System.out.println("msgdtstamp " + msgdtstamp);
  4893. pstmt.close();
  4894. } catch (SQLException ex3) {
  4895. ex3.printStackTrace();
  4896. }
  4897. // System.out.println("nav query 1");
  4898. String csql = "SELECT COUNT(*) AS rowcount FROM bm_mail WHERE read=? and dtstamp>?";
  4899. try {
  4900. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  4901. pstmt.setBoolean(1, false);
  4902. pstmt.setTimestamp(2, msgdtstamp);
  4903. rs = pstmt.executeQuery();
  4904. rs.next();
  4905. mcount = rs.getInt(1);
  4906. // System.out.println("mcount " + mcount);
  4907. pstmt.close();
  4908. } catch (SQLException ex3) {
  4909. ex3.printStackTrace();
  4910. }
  4911. // System.out.println("nav query 2");
  4912. String msgclass = "norm";
  4913. if (mcount > 0)
  4914. {
  4915. msgclass = "red";
  4916. }
  4917. String startDoc ="<nav><ul><li><a class='norm' href='/'>HOME</a></li>";
  4918. startDoc = startDoc + "<li><a class='" + msgclass + "' title='" + mcount + "' href='/messages'>MESSAGES</a></li>";
  4919. int fcount = 0;
  4920. java.sql.Timestamp foldtstamp = new java.sql.Timestamp(new java.util.Date().getTime());
  4921. tsql = "SELECT dtstamp FROM bm_lastclick WHERE wpage=?";
  4922. try {
  4923. PreparedStatement pstmt = db.conn.prepareStatement(tsql);
  4924. pstmt.setString(1, "FOLLOWERS");
  4925. rs = pstmt.executeQuery();
  4926. rs.next();
  4927. foldtstamp = rs.getTimestamp(1);
  4928. // System.out.println("foldtstamp " + foldtstamp);
  4929. pstmt.close();
  4930. } catch (SQLException ex3) {
  4931. ex3.printStackTrace();
  4932. }
  4933. // System.out.println("nav query 1");
  4934. csql = "SELECT COUNT(*) AS rowcount FROM bm_profiles WHERE dtstamp>?";
  4935. try {
  4936. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  4937. pstmt.setTimestamp(1, foldtstamp);
  4938. rs = pstmt.executeQuery();
  4939. rs.next();
  4940. fcount = rs.getInt(1);
  4941. // System.out.println("fcount " + fcount);
  4942. pstmt.close();
  4943. } catch (SQLException ex3) {
  4944. ex3.printStackTrace();
  4945. }
  4946. // System.out.println("nav query 2");
  4947. String folclass = "norm";
  4948. if (fcount > 0)
  4949. {
  4950. folclass = "red";
  4951. }
  4952. startDoc = startDoc + "<li><a class='" + folclass + "' title='" + fcount + "' href='/followers'>FOLLOWERS</a></li>";
  4953. int acount = 0;
  4954. java.sql.Timestamp altdtstamp = new java.sql.Timestamp(new java.util.Date().getTime());
  4955. tsql = "SELECT dtstamp FROM bm_lastclick WHERE wpage=?";
  4956. try {
  4957. PreparedStatement pstmt = db.conn.prepareStatement(tsql);
  4958. pstmt.setString(1, "ALERTS");
  4959. rs = pstmt.executeQuery();
  4960. rs.next();
  4961. altdtstamp = rs.getTimestamp(1);
  4962. // System.out.println("altdtstamp " + altdtstamp);
  4963. pstmt.close();
  4964. } catch (SQLException ex3) {
  4965. ex3.printStackTrace();
  4966. }
  4967. // System.out.println("nav query 1");
  4968. csql = "SELECT COUNT(*) AS rowcount FROM bm_alerts WHERE dtstamp>?";
  4969. try {
  4970. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  4971. pstmt.setTimestamp(1, altdtstamp);
  4972. rs = pstmt.executeQuery();
  4973. rs.next();
  4974. acount = rs.getInt(1);
  4975. // System.out.println("acount " + acount);
  4976. pstmt.close();
  4977. } catch (SQLException ex3) {
  4978. ex3.printStackTrace();
  4979. }
  4980. // System.out.println("nav query 2");
  4981. String altclass = "norm";
  4982. if (acount > 0)
  4983. {
  4984. altclass = "red";
  4985. }
  4986. startDoc = startDoc + "<li><a class='" + altclass + "' title='" + acount + "' href='/alerts'>ALERTS</a></li>";
  4987. startDoc = startDoc + "<li><a class='normright' href='/logout'>LOGOUT</a></li><li><a class='normright' href='/settings'>SETTINGS</a></li></ul></nav>";
  4988. return startDoc;
  4989. }
  4990. }
  4991. static class MainStart {
  4992. public MainStart() {
  4993. }
  4994. public String getMainStart()
  4995. {
  4996. String startDoc ="<div id='maincontent'>";
  4997. return startDoc;
  4998. }
  4999. }
  5000. static class MainLeftMenu {
  5001. public MainLeftMenu() {
  5002. }
  5003. public String getMainLeftMenu()
  5004. {
  5005. String startDoc ="<div id='leftmenu'><a href='/?application=news'>News</a><br>";
  5006. return startDoc;
  5007. }
  5008. }
  5009. static class MailLeftMenu {
  5010. ActivityStreamdb db = null;
  5011. public MailLeftMenu(ActivityStreamdb db) {
  5012. this.db = db;
  5013. }
  5014. public String getMailLeftMenu()
  5015. {
  5016. String startDoc ="<div id='leftmenu'>";
  5017. startDoc = startDoc + "<a href='/send_message'>New Message</a><br><br>";
  5018. try {
  5019. int count = 0;
  5020. ResultSet dbq = db.query("SELECT folder FROM bm_mail_folders");
  5021. Object o = null;
  5022. for (; dbq.next(); ) {
  5023. o = dbq.getObject(1);
  5024. String folder = o.toString();
  5025. String csql = "SELECT COUNT(*) AS rowcount FROM bm_mail WHERE folder=? AND read=?";
  5026. try {
  5027. PreparedStatement pstmt = db.conn.prepareStatement(csql);
  5028. pstmt.setString(1, folder);
  5029. pstmt.setBoolean(2, false);
  5030. ResultSet rs = pstmt.executeQuery();
  5031. rs.next();
  5032. count = rs.getInt(1);
  5033. // System.out.println(count);
  5034. pstmt.close();
  5035. } catch (SQLException ex3) {
  5036. ex3.printStackTrace();
  5037. }
  5038. startDoc = startDoc + "<a href=\"/messages?folder=" + folder + "\">" + folder;
  5039. if (count > 0)
  5040. {
  5041. startDoc = startDoc + " (" + count + ")";
  5042. }
  5043. startDoc = startDoc + "</a><br>";
  5044. }
  5045. db.st.close();
  5046. } catch (SQLException ex3) {
  5047. ex3.printStackTrace();
  5048. }
  5049. startDoc = startDoc + "<br>";
  5050. startDoc = startDoc + "<form name='new_folder' action='/messages' method='post' enctype='multipart/form-data'>";
  5051. startDoc = startDoc + "<input name = 'folder' style='width:100px'>";
  5052. startDoc = startDoc + "<input name='bfolder' type='submit' value='Add Folder'>";
  5053. startDoc = startDoc + "</form>";
  5054. return startDoc;
  5055. }
  5056. }
  5057. static class ProfilesLeftMenu {
  5058. ActivityStreamdb db = null;
  5059. public ProfilesLeftMenu(ActivityStreamdb db) {
  5060. this.db = db;
  5061. }
  5062. public String getProfilesLeftMenu()
  5063. {
  5064. String startDoc ="<div id='leftmenu'>";
  5065. startDoc = startDoc + "<a href='/followers?page=follower'>Followers</a><br>";
  5066. startDoc = startDoc + "<a href='/followers?page=following'>Following</a><br>";
  5067. startDoc = startDoc + "<a href='/followers?page=lists'>Follower Lists</a><br>";
  5068. startDoc = startDoc + "<a href='/followers?page=mail_contacts'>Mail Contacts</a><br>";
  5069. return startDoc;
  5070. }
  5071. }
  5072. static class SettingsLeftMenu {
  5073. public SettingsLeftMenu() {
  5074. }
  5075. public String getSettingsLeftMenu()
  5076. {
  5077. String startDoc ="<div id='leftmenu'><a href='/settings?setting=bm_api'>BM API Settings</a><br>";
  5078. startDoc = startDoc + "<a href='/settings?setting=hashtags'>Hashtags</a><br>";
  5079. return startDoc;
  5080. }
  5081. }
  5082. static class NewsPostForm {
  5083. public NewsPostForm() {
  5084. }
  5085. public String getNewsPostForm()
  5086. {
  5087. String startDoc ="<div> Share something:</div><div id='imagePreview'></div><form name='share' action='/' method='post' enctype='multipart/form-data' onSubmit='return selectAll();'><textarea name='share_post' cols='100' rows='4'></textarea></br><div> with:</div><select name='followers' onChange='SelectSubCat();'></select><table><tr><td><select name='FromLB' mulitple size='5' style='width:150'></select></td><td align='center' valign='middle'><input type='button' onClick='move(this.form.FromLB,this.form.To)' value='->'><br /><input type='button' onClick='move(this.form.To,this.form.FromLB)' value='<-'></td><td><select id='To' name='To' multiple size='5' style='width:150'></select></td></tr></table></br><input type='submit' value='Share'><input type = 'button' value = 'Choose image' onclick ='javascript:document.getElementById(\"imagefile\").click();'><input type='reset' value='Cancel' onClick='unloadImageFile()'> <input id = 'imagefile' type='file' style='visibility: hidden;' name='File' accept='image/*' onchange=\"loadImageFile();\"></form>";
  5088. return startDoc;
  5089. }
  5090. }
  5091. static class EndDiv {
  5092. public EndDiv() {
  5093. }
  5094. public String getEndDiv()
  5095. {
  5096. String startDoc ="</div>";
  5097. return startDoc;
  5098. }
  5099. }
  5100. static class EndBody {
  5101. public EndBody() {
  5102. }
  5103. public String getEndBody()
  5104. {
  5105. String startDoc ="</body></html>";
  5106. return startDoc;
  5107. }
  5108. }
  5109. static class base64processor {
  5110. public base64processor()
  5111. {
  5112. }
  5113. public String toString(byte[] input)
  5114. {
  5115. byte[] b = Base64.encodeBase64(input);
  5116. String c = "";
  5117. try {
  5118. c = new String(b, "UTF-8");
  5119. } catch (Exception e) {
  5120. e.printStackTrace();
  5121. }
  5122. return c;
  5123. }
  5124. }
  5125. static class stream2File {
  5126. public stream2File() {
  5127. }
  5128. public File getstream2file(InputStream in) throws IOException
  5129. {
  5130. String PREFIX = "stream2file";
  5131. String SUFFIX = ".tmp";
  5132. File tempFile = File.createTempFile(PREFIX, SUFFIX);
  5133. tempFile.deleteOnExit();
  5134. try (FileOutputStream out = new FileOutputStream(tempFile)) {
  5135. IOUtils.copy(in, out);
  5136. }
  5137. return tempFile;
  5138. }
  5139. }
  5140. static class ActivityStreamdb {
  5141. Connection conn;
  5142. Statement st;
  5143. ResultSet rs;
  5144. public ActivityStreamdb(String db_file_name_prefix) throws Exception {
  5145. Class.forName("org.hsqldb.jdbcDriver");
  5146. conn = DriverManager.getConnection("jdbc:hsqldb:"
  5147. + db_file_name_prefix,
  5148. "sa",
  5149. "");
  5150. }
  5151. public void shutdown() throws SQLException {
  5152. Statement st = conn.createStatement();
  5153. st.execute("SHUTDOWN");
  5154. conn.close();
  5155. }
  5156. public synchronized ResultSet query(String expression) throws SQLException {
  5157. ResultSet rs = null;
  5158. st = conn.createStatement();
  5159. rs = st.executeQuery(expression);
  5160. return rs;
  5161. }
  5162. public synchronized void update(String expression) throws SQLException {
  5163. Statement st = null;
  5164. st = conn.createStatement();
  5165. int i = st.executeUpdate(expression);
  5166. if (i == -1) {
  5167. System.out.println("db error : " + expression);
  5168. }
  5169. st.close();
  5170. }
  5171. public static String dump(ResultSet rs) throws SQLException {
  5172. ResultSetMetaData meta = rs.getMetaData();
  5173. int colmax = meta.getColumnCount();
  5174. int i;
  5175. Object o = null;
  5176. String blah = "";
  5177. for (; rs.next(); ) {
  5178. for (i = 0; i < colmax; ++i) {
  5179. o = rs.getObject(i + 1); // Is SQL the first column is indexed
  5180. String meh = o.toString();
  5181. byte[] decoded = Base64.decodeBase64(meh);
  5182. String meh2 = null;
  5183. try {
  5184. meh2 = new String(decoded, "UTF-8");
  5185. } catch (Exception e) {
  5186. e.printStackTrace();
  5187. }
  5188. blah = blah + meh2;
  5189. }
  5190. }
  5191. return blah;
  5192. }
  5193. }
  5194. static class KeyFinder implements ContentHandler{
  5195. private Object value;
  5196. private boolean found = false;
  5197. private boolean end = false;
  5198. private String key;
  5199. private String matchKey;
  5200. public void setMatchKey(String matchKey){
  5201. this.matchKey = matchKey;
  5202. }
  5203. public Object getValue(){
  5204. return value;
  5205. }
  5206. public boolean isEnd(){
  5207. return end;
  5208. }
  5209. public void setFound(boolean found){
  5210. this.found = found;
  5211. }
  5212. public boolean isFound(){
  5213. return found;
  5214. }
  5215. public void startJSON() throws ParseException, IOException {
  5216. found = false;
  5217. end = false;
  5218. }
  5219. public void endJSON() throws ParseException, IOException {
  5220. end = true;
  5221. }
  5222. public boolean primitive(Object value) throws ParseException, IOException {
  5223. if(key != null){
  5224. if(key.equals(matchKey)){
  5225. found = true;
  5226. this.value = value;
  5227. key = null;
  5228. return false;
  5229. }
  5230. }
  5231. return true;
  5232. }
  5233. public boolean startArray() throws ParseException, IOException {
  5234. return true;
  5235. }
  5236. public boolean startObject() throws ParseException, IOException {
  5237. return true;
  5238. }
  5239. public boolean startObjectEntry(String key) throws ParseException, IOException {
  5240. this.key = key;
  5241. return true;
  5242. }
  5243. public boolean endArray() throws ParseException, IOException {
  5244. return false;
  5245. }
  5246. public boolean endObject() throws ParseException, IOException {
  5247. return true;
  5248. }
  5249. public boolean endObjectEntry() throws ParseException, IOException {
  5250. return true;
  5251. }
  5252. }
  5253. public static class FormdataMultipart extends MimeMultipart {
  5254. //logging
  5255. //instance attributes
  5256. private Hashtable<String, String[]> m_Params = new Hashtable<String, String[]>();
  5257. private boolean m_Removed = false;
  5258. /**
  5259. * Constructs a <tt>FormdataMultipart</tt> instance.<br>
  5260. * This implementation just calls the superclass constructor.
  5261. *
  5262. * @return the newly created <tt>FormdataMultipart</tt> instance.
  5263. */
  5264. public FormdataMultipart() {
  5265. super();
  5266. }//constructor
  5267. /**
  5268. * Constructs a <tt>FormdataMultipart</tt> instance.<br>
  5269. * Automatically processes the body parts to extract parameters,
  5270. * and attachments.
  5271. *
  5272. * @param DataSource to construct the Multipart from, will be a
  5273. * <tt>MultipartInputStream</tt>.
  5274. *
  5275. * @return the newly created <tt>FormdataMultipart</tt> instance.
  5276. */
  5277. public FormdataMultipart(DataSource ds)
  5278. throws MessagingException, IOException {
  5279. super(ds);
  5280. processBodyParts();
  5281. updateHeaders();
  5282. //System.out.println("Created");
  5283. }//constructor
  5284. /**
  5285. * Returns the extracted parameters (with the extrcted values)
  5286. * as <tt>Hashtable</tt>.
  5287. *
  5288. * @return the extracted parameter data as <tt>Hashtable</tt>
  5289. */
  5290. public Hashtable getParameters() {
  5291. return m_Params;
  5292. }//getParameters
  5293. /**
  5294. * Processes the body parts of the form-data.
  5295. * Extracts parameters and set values, and
  5296. * leaves over the attachments.
  5297. *
  5298. * @throws IOException if i/o operations fail.
  5299. * @throws MessagingException if parsing or part handling with
  5300. * Mail API classes fails.
  5301. */
  5302. public void processBodyParts()
  5303. throws IOException, MessagingException {
  5304. //if write out to log for debug reasons!
  5305. //ByteArrayOutputStream bout=new ByteArrayOutputStream();
  5306. //writeTo(bout);
  5307. //JwmaKernel.getReference().debugLog().write(bout.toString());
  5308. //System.out.println("Count : " + getCount());
  5309. for (int i = 0; i < getCount(); i++) {
  5310. // System.out.println("Count : " + getCount() + " " + i);
  5311. MimeBodyPart mbp = (MimeBodyPart) getBodyPart(i);
  5312. processBodyPart(mbp);
  5313. if (m_Removed) {
  5314. m_Removed = false;
  5315. //decrease index i approbiately
  5316. i--;
  5317. }
  5318. }
  5319. setSubType("mixed");
  5320. //JwmaKernel.getReference().debugLog().write(
  5321. // "Processed multipart/form-data. Attachment parts:"+getCount()
  5322. //);
  5323. }//processParts
  5324. /**
  5325. * Processes a body part of the form-data.
  5326. * Extracts parameters and set values, and
  5327. * leaves over the attachments.
  5328. *
  5329. * @param mbp the <tt>MimeBodyPart</tt> to be processed.
  5330. *
  5331. * @throws IOException if i/o operations fail.
  5332. * @throws MessagingException if parsing or part handling with
  5333. * Mail API classes fails.
  5334. */
  5335. private void processBodyPart(MimeBodyPart mbp)
  5336. throws MessagingException, IOException {
  5337. //String contenttype=new String(mbp.getContentType());
  5338. //JwmaKernel.getReference().debugLog().write("Processing "+contenttype);
  5339. //check if a content-type is given
  5340. String[] cts = mbp.getHeader("Content-Type");
  5341. if (cts == null || cts.length == 0) {
  5342. //this is a parameter, get it out and
  5343. //remove the part.
  5344. String controlname = extractName(
  5345. (mbp.getHeader("Content-Disposition"))[0]);
  5346. // System.out.println("Processing control: "+controlname);
  5347. //retrieve value observing encoding
  5348. InputStream in = mbp.getInputStream();
  5349. String[] encoding = mbp.getHeader("Content-Transfer-Encoding");
  5350. if (encoding != null && encoding.length > 0) {
  5351. in = MimeUtility.decode(in, encoding[0]);
  5352. }
  5353. String value = extractValue(in);
  5354. if (value != null || !value.trim().equals("")) {
  5355. addParameter(controlname, value);
  5356. }
  5357. //flag removal
  5358. m_Removed = true;
  5359. removeBodyPart(mbp);
  5360. } else {
  5361. String filename = extractFileName(
  5362. (mbp.getHeader("Content-Disposition"))[0]);
  5363. //normally without file the control should be not successful.
  5364. //but neither netscape nor mircosoft iexploder care much.
  5365. //the only feature is an empty filename.
  5366. if (filename.equals("")) {
  5367. //kick it out too
  5368. m_Removed = true;
  5369. removeBodyPart(mbp);
  5370. } else {
  5371. //JwmaKernel.getReference().debugLog().write("Incoming filename="+filename);
  5372. //IExploder sends files with complete path.
  5373. //jwma doesnt want this.
  5374. int lastindex = filename.lastIndexOf("\\");
  5375. if (lastindex != -1) {
  5376. filename = filename.substring(lastindex + 1, filename.length());
  5377. }
  5378. //JwmaKernel.getReference().debugLog().write("Outgoing filename="+filename);
  5379. //Observe a possible encoding
  5380. InputStream in = mbp.getInputStream();
  5381. String[] encoding = mbp.getHeader("Content-Transfer-Encoding");
  5382. if (encoding != null && encoding.length > 0) {
  5383. in = MimeUtility.decode(in, encoding[0]);
  5384. }
  5385. ByteArrayOutputStream bout = new ByteArrayOutputStream();
  5386. OutputStream out = (OutputStream) bout;
  5387. int i = 0;
  5388. while ((i = in.read()) != -1) {
  5389. //maybe more efficient in buffers, but well
  5390. out.write(i);
  5391. }
  5392. out.flush();
  5393. out.close();
  5394. //create the datasource
  5395. MimeBodyPartDataSource mbpds =
  5396. new MimeBodyPartDataSource(
  5397. // contenttype,filename,bout.toByteArray()
  5398. cts[0], filename, bout.toByteArray()
  5399. );
  5400. //Re-set the Content-Disposition header, in case
  5401. //the file name was changed
  5402. mbp.removeHeader("Content-Disposition");
  5403. mbp.addHeader(
  5404. "Content-Disposition", "attachment; filename=\"" +
  5405. filename +
  5406. "\""
  5407. );
  5408. //set a base64 transferencoding und the data handler
  5409. mbp.addHeader("Content-Transfer-Encoding", "base64");
  5410. mbp.setDataHandler(new DataHandler(mbpds));
  5411. }
  5412. }
  5413. }//processBodyPart
  5414. /**
  5415. * Returns the name of a parameter by extracting it
  5416. * from the content-disposition header line.
  5417. *
  5418. * @param disposition the content-disposition header line as
  5419. * <tt>String</tt>.
  5420. *
  5421. * @return the name of the parameter as <tt>String</tt>.
  5422. *
  5423. * @throws IOException if the header line is malformed.
  5424. */
  5425. private String extractName(String disposition)
  5426. throws IOException {
  5427. int end = 0;
  5428. int start = -1;
  5429. start = disposition.indexOf("name=\"");
  5430. end = disposition.indexOf("\"", start + 7); //offset is to skip name=\"
  5431. if (start == -1 || end == -1) {
  5432. throw new IOException("Mime header malformed.");
  5433. }
  5434. return disposition.substring(start + 6, end);
  5435. }//extractName
  5436. /**
  5437. * Returns the filename of an attachment by extracting it
  5438. * from the content-disposition header line.
  5439. *
  5440. * @param disposition the content-disposition header line as
  5441. * <tt>String</tt>.
  5442. *
  5443. * @return the filename of the attachment as <tt>String</tt>.
  5444. *
  5445. * @throws IOException if the header line is malformed.
  5446. */
  5447. private String extractFileName(String disposition)
  5448. throws IOException {
  5449. int end = 0;
  5450. int start = -1;
  5451. start = disposition.indexOf("filename=\"");
  5452. end = disposition.indexOf("\"", start + 10); //offset is to skip filename=\"
  5453. if (start == -1 || end == -1) {
  5454. throw new IOException("Mime header malformed.");
  5455. }
  5456. return disposition.substring(start + 10, end);
  5457. }//extractFileName
  5458. /**
  5459. * Returns the value of a parameter by extracting it
  5460. * from the <tt>InputStream</tt> that represents the content
  5461. * of the (parameter) part.
  5462. *
  5463. * @param in <tt>InputStream</tt> that reads from the content
  5464. * of the (parameter) part.
  5465. *
  5466. * @return the value of the parameter as <tt>String</tt>.
  5467. *
  5468. * @throws IOException if reading from the stream fails.
  5469. */
  5470. private String extractValue(InputStream in)
  5471. throws IOException {
  5472. ByteArrayOutputStream out = new ByteArrayOutputStream();
  5473. int i = 0;
  5474. while ((i = in.read()) != -1) {
  5475. out.write(i);
  5476. }
  5477. out.flush();
  5478. out.close();
  5479. in.close();
  5480. //JwmaKernel.getReference().debugLog().write("Retrieved value="+out.toString());
  5481. //apply a little bit of magic when returning
  5482. return out.toString("iso-8859-1");
  5483. }//extractValue
  5484. /**
  5485. * Adds a parameter and mapped value to the parameters collection.
  5486. * If the parameter already exists, it adds another value to
  5487. * an already existing parameter by extending the array of strings.
  5488. *
  5489. * @param name the name of the parameter as <tt>String</tt>.
  5490. * @param value the value of the parameter as <tt>String</tt>.
  5491. */
  5492. private void addParameter(String name, String value) {
  5493. String values[];
  5494. //JwmaKernel.getReference().debugLog().write("Adding "+name+"="+value);
  5495. if (m_Params.containsKey(name)) {
  5496. String oldValues[] = (String[]) m_Params.get(name);
  5497. values = new String[oldValues.length + 1];
  5498. for (int i = 0; i < oldValues.length; i++) {
  5499. values[i] = oldValues[i];
  5500. }
  5501. values[oldValues.length] = value;
  5502. } else {
  5503. values = new String[1];
  5504. values[0] = value;
  5505. }
  5506. m_Params.put(name, values);
  5507. }//addParameter
  5508. }//FormdataMultipart
  5509. public static class MimeBodyPartDataSource implements DataSource {
  5510. private String m_Type;
  5511. private String m_Name;
  5512. private byte[] m_Data;
  5513. public MimeBodyPartDataSource(String type, String name, byte[] data) {
  5514. m_Type = type;
  5515. m_Name = name;
  5516. m_Data = data;
  5517. }//constructore
  5518. public String getContentType() {
  5519. return m_Type;
  5520. }//getContentTyp
  5521. public String getName() {
  5522. return m_Name;
  5523. }//getName
  5524. public InputStream getInputStream() throws IOException {
  5525. return new ByteArrayInputStream(m_Data);
  5526. }//getInputStream
  5527. public OutputStream getOutputStream() throws IOException {
  5528. throw new IOException("Not supported.");
  5529. }//getOutputStream
  5530. }//class MimeBodyPartDataSource
  5531. public static class ParameterFilter extends Filter {
  5532. @Override
  5533. public String description() {
  5534. return "Parses the requested URI for parameters";
  5535. }
  5536. @Override
  5537. public void doFilter(HttpExchange exchange, Chain chain)
  5538. throws IOException {
  5539. parseGetParameters(exchange);
  5540. // parsePostParameters(exchange);
  5541. chain.doFilter(exchange);
  5542. }
  5543. private void parseGetParameters(HttpExchange exchange)
  5544. throws UnsupportedEncodingException {
  5545. Map<String, Object> parameters = new HashMap<String, Object>();
  5546. URI requestedUri = exchange.getRequestURI();
  5547. String query = requestedUri.getRawQuery();
  5548. parseQuery(query, parameters);
  5549. exchange.setAttribute("parameters", parameters);
  5550. }
  5551. private void parsePostParameters(HttpExchange exchange)
  5552. throws IOException {
  5553. if ("post".equalsIgnoreCase(exchange.getRequestMethod())) {
  5554. @SuppressWarnings("unchecked")
  5555. Map<String, Object> parameters =
  5556. (Map<String, Object>)exchange.getAttribute("parameters");
  5557. InputStreamReader isr =
  5558. new InputStreamReader(exchange.getRequestBody(),"utf-8");
  5559. BufferedReader br = new BufferedReader(isr);
  5560. String query = br.readLine();
  5561. parseQuery(query, parameters);
  5562. }
  5563. }
  5564. @SuppressWarnings("unchecked")
  5565. private void parseQuery(String query, Map<String, Object> parameters)
  5566. throws UnsupportedEncodingException {
  5567. if (query != null) {
  5568. String pairs[] = query.split("[&]");
  5569. for (String pair : pairs) {
  5570. String param[] = pair.split("[=]");
  5571. String key = null;
  5572. String value = null;
  5573. if (param.length > 0) {
  5574. key = URLDecoder.decode(param[0],
  5575. System.getProperty("file.encoding"));
  5576. }
  5577. if (param.length > 1) {
  5578. value = URLDecoder.decode(param[1],
  5579. System.getProperty("file.encoding"));
  5580. }
  5581. if (parameters.containsKey(key)) {
  5582. Object obj = parameters.get(key);
  5583. if(obj instanceof List<?>) {
  5584. List<String> values = (List<String>)obj;
  5585. values.add(value);
  5586. } else if(obj instanceof String) {
  5587. List<String> values = new ArrayList<String>();
  5588. values.add((String)obj);
  5589. values.add(value);
  5590. parameters.put(key, values);
  5591. }
  5592. } else {
  5593. parameters.put(key, value);
  5594. }
  5595. }
  5596. }
  5597. }
  5598. }
  5599. }

comments powered by Disqus