List of usage examples for org.json.simple JSONObject toString
@Override
public String toString()
From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsRowParser.java
/*** * Used to parse, escape and enrich Kissmetircs Json records * //from w w w. j a va 2 s . c o m * @param rawJsonRow * @param fileNameInputToMapper * @return */ public static KeyRowWrapper parseJsonRowToValidJson(Text rawJsonRow, String fileNameInputToMapper, String filePath) { String jsonString = ""; boolean wasOctalParsingNeeded = false; try { System.setProperty("file.encoding", "UTF-8"); s = rawJsonRow.toString(); Charset charSet = Charset.forName("UTF-8"); byte[] encoded = s.getBytes(charSet); decodedStrRaw = new String(encoded, charSet); // Test new Apache Lang3 // decodedStr = StringEscapeUtils.unescapeJava(decodedStr); //Replace any remaining Octal encoded Characters decodedStrParsed = replaceOctalUft8Char(decodedStrRaw); if (decodedStrParsed.compareTo(decodedStrRaw) == 0) { wasOctalParsingNeeded = false; } else { wasOctalParsingNeeded = true; } if (decodedStrParsed != null && decodedStrParsed != "") { JSONObject jsonObject = (JSONObject) jsonParser.parse(decodedStrParsed); // get email and user_id if (jsonObject.get("_p2") != null) { p2 = jsonObject.get("_p2").toString().toLowerCase(); if (p2.contains("@")) { jsonObject.put("user_email", p2); jsonObject.put("user_email_back", p2); } else if (p2 != null && p2.length() > 0) { jsonObject.put("user_km_id", p2); } } // get email and user_id if (jsonObject.get("_p") != null) { p = jsonObject.get("_p").toString().toLowerCase(); if (p.contains("@")) { jsonObject.put("user_email", p); jsonObject.put("user_email_back", p); } else if (p != null && p.length() > 0) { jsonObject.put("user_km_id", p); } } // Add Event if (jsonObject.get("_n") != null) { event = jsonObject.get("_n").toString(); if (event != null) { jsonObject.put("event", event); } } // add unix timestamp and datetime long currentDateTime = System.currentTimeMillis(); Date currentDate = new Date(currentDateTime); if (jsonObject.get("_t") == null) { return (new KeyRowWrapper(jsonString, null, TRACKING_COUNTER.INVALID_JSON_ROW, TRACKING_COUNTER.INVALID_DATE)); } long kmTimeDateMilliSeconds; long kmTimeDateMilliSecondsMobile; try { tTimestampValue = (String) jsonObject.get("_t").toString(); //See if new record with server timestamp if (jsonObject.get("_server_timestamp") != null) { serverTimestampValue = (String) jsonObject.get("_server_timestamp").toString(); } else { serverTimestampValue = "0"; } //Deal with mobile timedate cases if (jsonObject.get("_c") != null) { if (serverTimestampValue.equals("0")) { timestampValueOutput = tTimestampValue; kmTimeDateMilliSecondsMobile = 0; } else { timestampValueOutput = serverTimestampValue; mobileTimestampValueOutput = tTimestampValue; jsonObject.put("km_timestamp_mobile", mobileTimestampValueOutput); kmTimeDateMilliSecondsMobile = Long.parseLong(mobileTimestampValueOutput) * 1000; } } else {//Ignore server time //TODO Need a way to resolve mobile identify events serverTimestampValue = "0"; timestampValueOutput = tTimestampValue; kmTimeDateMilliSecondsMobile = 0; } jsonObject.put("km_timestamp", timestampValueOutput); kmTimeDateMilliSeconds = Long.parseLong(timestampValueOutput) * 1000; } catch (Exception e) { return (new KeyRowWrapper(jsonString, timestampValueOutput, TRACKING_COUNTER.INVALID_JSON_ROW, TRACKING_COUNTER.INVALID_DATE)); } Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(kmTimeDateMilliSeconds); String event_timedate = dateFormatter.format(calendar.getTime()); jsonObject.put("event_timedate", event_timedate); if (kmTimeDateMilliSecondsMobile > 0) { calendar.setTimeInMillis(kmTimeDateMilliSecondsMobile); String event_timedate_mobile = dateFormatter.format(calendar.getTime()); jsonObject.put("event_timedate_mobile", event_timedate_mobile); } // add Map Reduce json_filename jsonObject.put("filename", fileNameInputToMapper); jsonString = jsonObject.toString(); //Add bucket path jsonObject.put("bucket", filePath); jsonString = jsonObject.toString(); // TODO add the time the record was processed by Mapper: //jsonObject.put("capturedDate", capturedDate); //jsonString = jsonObject.toString(); return (new KeyRowWrapper(jsonString, timestampValueOutput, TRACKING_COUNTER.VALID_JSON_ROW, wasOctalParsingNeeded ? null : TRACKING_COUNTER.OCTAL_PARSING_NEEDED)); } } catch (Exception e) { // System.err.println(e.getMessage()); // e.printStackTrace(); StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); logger.error(errors.toString()); logger.error("log - file " + fileNameInputToMapper); System.out.println("file " + fileNameInputToMapper); logger.error("log - row content: " + rawJsonRow.toString().replace("\t", "")); System.err.println("row content: " + rawJsonRow.toString().replace("\t", "")); System.err.println("Error skipping row"); logger.error("Log - Error skipping row"); } return null; }
From source file:hoot.services.controllers.osm.MapResource.java
@GET @Path("/mbr") @Produces(MediaType.APPLICATION_JSON)//from w w w .ja v a2 s .c o m public Response getMBR(@QueryParam("mapId") String mapId) { JSONObject ret = new JSONObject(); try (Connection connection = DbUtils.createConnection()) { logger.info("Retrieving MBR for map with ID: {} ...", mapId); long mapIdNum = -2; try { mapIdNum = Long.parseLong(mapId); } catch (NumberFormatException ignored) { // } if (mapIdNum == -1) // OSM API db { // OSM API database data can't be displayed on a hoot map, due to differences // between the display code, so we arbitrarily returning roughly a CONUS bounds // here...not quite sure what else to return... ret.put("minlon", -110); ret.put("maxlon", -75); ret.put("minlat", 20); ret.put("maxlat", 50); ret.put("firstlon", 0); ret.put("firstlat", 0); ret.put("nodescount", 0); } else { mapIdNum = ModelDaoUtils.getRecordIdForInputString(mapId, connection, maps, maps.id, maps.displayName); BoundingBox queryBounds; try { queryBounds = new BoundingBox("-180,-90,180,90"); logger.debug("Query bounds area: {}", queryBounds.getArea()); } catch (Exception e) { throw new RuntimeException("Error parsing bounding box from bbox param: " + "-180,-90,180,90" + " (" + e.getMessage() + ")", e); } Map currMap = new Map(mapIdNum, connection); JSONObject extents = currMap.retrieveNodesMBR(queryBounds); if ((extents.get("minlat") == null) || (extents.get("maxlat") == null) || (extents.get("minlon") == null) || (extents.get("maxlon") == null)) { throw new Exception("Map is empty."); } JSONObject anode = currMap.retrieveANode(queryBounds); long nodeCnt = currMap.getNodesCount(queryBounds); double dMinLon = (Double) extents.get("minlon"); double dMaxLon = (Double) extents.get("maxlon"); double dMinLat = (Double) extents.get("minlat"); double dMaxLat = (Double) extents.get("maxlat"); double dFirstLon = (Double) anode.get("lon"); double dFirstLat = (Double) anode.get("lat"); ret.put("minlon", dMinLon); ret.put("maxlon", dMaxLon); ret.put("minlat", dMinLat); ret.put("maxlat", dMaxLat); ret.put("firstlon", dFirstLon); ret.put("firstlat", dFirstLat); ret.put("nodescount", nodeCnt); } } catch (Exception e) { handleError(e, mapId, "-180,-90,180,90"); } return Response.ok(ret.toString()).build(); }
From source file:hoot.services.controllers.osm.MapResource.java
@POST @Path("/nodescount") @Consumes(MediaType.TEXT_PLAIN)/*from ww w . j a v a 2 s. co m*/ @Produces(MediaType.APPLICATION_JSON) public Response getTileNodesCounts(String params) { JSONObject ret = new JSONObject(); String mapId = ""; String bbox = ""; try (Connection connection = DbUtils.createConnection()) { JSONParser parser = new JSONParser(); JSONArray paramsArray = (JSONArray) parser.parse(params); long nodeCnt = 0; for (Object aParamsArray : paramsArray) { JSONObject param = (JSONObject) aParamsArray; mapId = (String) param.get("mapId"); long mapIdNum = -2; try { mapIdNum = Long.parseLong(mapId); } catch (NumberFormatException ignored) { // } // OSM API database data can't be displayed on a hoot map, due to differences // between the display code, so we return a zero count if its that layer. if (mapIdNum != -1) { logger.info("Retrieving node count for map with ID: {} ...", mapId); bbox = (String) param.get("tile"); String[] coords = bbox.split(","); if (coords.length == 4) { String sMinX = coords[0]; String sMinY = coords[1]; String sMaxX = coords[2]; String sMaxY = coords[3]; double minX = Double.parseDouble(sMinX); double minY = Double.parseDouble(sMinY); double maxX = Double.parseDouble(sMaxX); double maxY = Double.parseDouble(sMaxY); minX = (minX > 180) ? 180 : minX; minX = (minX < -180) ? -180 : minX; maxX = (maxX > 180) ? 180 : maxX; maxX = (maxX < -180) ? -180 : maxX; minY = (minY > 90) ? 90 : minY; minY = (minY < -90) ? -90 : minY; maxY = (maxY > 90) ? 90 : maxY; maxY = (maxY < -90) ? -90 : maxY; bbox = minX + "," + minY + "," + maxX + "," + maxY; } mapIdNum = ModelDaoUtils.getRecordIdForInputString(mapId, connection, maps, maps.id, maps.displayName); BoundingBox queryBounds; try { queryBounds = new BoundingBox(bbox); logger.debug("Query bounds area: {}", queryBounds.getArea()); } catch (Exception e) { throw new RuntimeException( "Error parsing bounding box from bbox param: " + bbox + " (" + e.getMessage() + ")", e); } Map currMap = new Map(mapIdNum, connection); nodeCnt += currMap.getNodesCount(queryBounds); } } ret.put("nodescount", nodeCnt); } catch (Exception e) { handleError(e, mapId, bbox); } return Response.ok(ret.toString()).build(); }
From source file:com.mycompany.demos.Servlet3a.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w ww. j a va 2 s. c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; final String DB_URL = "jdbc:mysql://localhost:3306/garbagecollectionv2"; final String USER = "root"; final String PASS = "1234"; double lat = 0, lng = 0; float fullness = 0; int locationId, binId, depotId, numOfVehicles; JSONObject bins, feature, properties, geometry; JSONArray features, coordinates; features = new JSONArray(); Connection conn = null; Statement stmt = null; try { //STEP 2: Register JDBC driver System.out.println("Loading Driver..."); Class.forName(JDBC_DRIVER); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT * FROM bins inner join locations on bins.locationId = locations.locationId;"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { lat = rs.getDouble("lat"); lng = rs.getDouble("lng"); fullness = rs.getFloat("fullness"); locationId = rs.getInt("locationId"); binId = rs.getInt("binId"); //System.out.println(fullness); coordinates = new JSONArray(); coordinates.add(lng); coordinates.add(lat); geometry = new JSONObject(); geometry.put("type", "Point"); geometry.put("coordinates", coordinates); properties = new JSONObject(); properties.put("locationId", locationId); properties.put("binId", binId); properties.put("fullness", fullness); properties.put("type", "bin"); feature = new JSONObject(); feature.put("type", "Feature"); feature.put("geometry", geometry); feature.put("properties", properties); features.add(feature); } sql = "SELECT * FROM depots inner join locations on depots.locationId = locations.locationId;"; rs = stmt.executeQuery(sql); while (rs.next()) { lat = rs.getDouble("lat"); lng = rs.getDouble("lng"); numOfVehicles = rs.getInt("numOfVehicles"); locationId = rs.getInt("locationId"); depotId = rs.getInt("depotId"); //System.out.println(fullness); coordinates = new JSONArray(); coordinates.add(lng); coordinates.add(lat); geometry = new JSONObject(); geometry.put("type", "Point"); geometry.put("coordinates", coordinates); properties = new JSONObject(); properties.put("locationId", locationId); properties.put("numOfVehicles", numOfVehicles); properties.put("depotId", depotId); properties.put("type", "depot"); feature = new JSONObject(); feature.put("type", "Feature"); feature.put("geometry", geometry); feature.put("properties", properties); features.add(feature); } rs.close(); stmt.close(); conn.close(); } catch (SQLException se) { //Handle errors for JDBC se.printStackTrace(); } catch (Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { try { if (stmt != null) { stmt.close(); } } catch (SQLException se2) { } try { if (conn != null) { conn.close(); } } catch (SQLException se) { se.printStackTrace(); } } bins = new JSONObject(); bins.put("type", "FeatureCollection"); bins.put("features", features); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(bins.toString()); System.out.println(bins.toString()); }
From source file:com.caspida.plugins.graph.EntityGraphNeo4jPlugin.java
@Name(EntityGraphConstants.API_GET_BIPARTITE_GRAPH) @Description("Get bipartite information for various entities") @PluginTarget(GraphDatabaseService.class) public String getBipartite(@Source GraphDatabaseService graphDb, @Description("Input parameters as a JSON string ") @Parameter(name = "entityTypes") List<String> entityList, @Parameter(name = "sourceEntityId", optional = true) String entityId, @Parameter(name = "sourceEntityType") String entityType, @Parameter(name = "minScore", optional = true) Integer minScoreIn) { JSONArray nodes = new JSONArray(); JSONArray edges = new JSONArray(); JSONObject response = new JSONObject(); JSONParser parser = new JSONParser(); Integer minScore = (minScoreIn != null) ? minScoreIn.intValue() : 0; Integer uniqueLinkId = 1;// ww w .jav a2s .c o m /* keep track if the caller requested to see anomalies, or not * if it did not, we have two options on what we will show, facts or only anomaly related links * if the caller asked for anomalies, then we will only show anomaly related links */ Boolean askedForAnomalies = ((entityType == EntityGraphConstants.UBER_GRAPH_THREAT_LABEL) || entityList.contains(EntityGraphConstants.UBER_GRAPH_THREAT_LABEL)) ? true : false; logger.error("Got input params entity list {} and entityId {} asked for anomalies {}", entityList, entityId, askedForAnomalies); try (Transaction txn = graphDb.beginTx()) { /* build a list of nodes that we will later expand * if entityId is present then it will be a single node * else we will need to pick a set of nodes from the entity types * specified. Should pick some nodes with low selectivity * (i.e. anomalies) if possible */ List<Node> nodeList = new ArrayList<>(); if (entityId != null && entityId.length() > 2) { // XXX better test for "" string logger.error("Looking up single node with id {}", entityId); Index<Node> nodeIndex = graphDb.index().forNodes(EntityGraphConstants.EVENT_CLASS); Node node = nodeIndex.get(EntityGraphConstants.NODE_ID, Long.parseLong(entityId)).getSingle(); if (node == null) { logger.error("Can not locate entity with provided id {}", entityId); return response.toJSONString(); } else { logger.debug("Found entity node with provided id {}", entityId); nodeList.add(node); } } else { /* map the entityType to the right label */ Label label = DynamicLabel.label(entityType); // XXX String eventType = null; /* map the entity id to the value I need for the event type */ switch (entityType) { case "caspida.device": eventType = "Device"; break; case "caspida.anomaly": eventType = "Threat"; break; case "caspida.user": eventType = "User"; break; case "caspida.url": eventType = "Url"; break; default: break; } logger.error("Got event type {}", eventType); /** XXX use the exact label to reduce the scope of the walk */ ResourceIterable<Node> iterableNodes = null; if (eventType != null) { iterableNodes = graphDb.findNodesByLabelAndProperty(eventClassLabel, EntityGraphConstants.EVENT_TYPE, eventType); } if (iterableNodes != null) { ResourceIterator<Node> it = iterableNodes.iterator(); while (it.hasNext()) { Node node = it.next(); logger.error("Adding node {} to the list", node.getId()); nodeList.add(node); } } else { logger.error("Could not find any nodes for request with entity list {}", entityList); return response.toJSONString(); } } /* at this point I have a list of nodes that I need to expand * need to make sure I do not repeat the same nodes, so use a * hash map to keep track of the ones I have visited so far */ HashMap<Node, Integer> nodeHash = new HashMap<>(); for (Node node : nodeList) { String objectType = null; String otherObjectType = null; Iterable<Relationship> rels = node.getRelationships(); /* if the current node is anomaly, skip depending on the score */ Integer score = getNodeScore(node); if (score != -1 && score < minScore) { logger.error("Dropping node due to low score"); continue; } /* now iterate all the neighbhors and put the ones to be expanded in a list * need to filter anomalies for the minScore * if we hit anomaly nodes and askedForAnomalies is false we need to "go over" them * to get to the entity on the other side * */ nodeHash.put(node, 1); List<Node> otherNodeList = new ArrayList<Node>(); for (Relationship rel : rels) { Node otherNode = (rel.getStartNode().getId() == node.getId()) ? rel.getEndNode() : rel.getStartNode(); /* if the other node is anomaly, skip depending on the score */ score = getNodeScore(otherNode); if (score != -1 && score < minScore) { logger.error("Dropping other node due to low score"); continue; } if (score != -1) { /* it is an anomaly */ if (askedForAnomalies == false) { /* need to expand the anomalies and get to its children */ Iterable<Relationship> anomalyRels = otherNode.getRelationships(); for (Relationship anomalyRel : anomalyRels) { Node otherAnomalyNode = (anomalyRel.getStartNode().getId() == otherNode.getId()) ? anomalyRel.getEndNode() : anomalyRel.getStartNode(); if (otherAnomalyNode != node && shouldInclude(otherAnomalyNode, entityList) == true && !nodeHash.containsKey(otherAnomalyNode)) { otherNodeList.add(otherAnomalyNode); nodeHash.put(otherAnomalyNode, 1); } } } else { if (shouldInclude(otherNode, entityList) == true && !nodeHash.containsKey(otherNode)) { otherNodeList.add(otherNode); nodeHash.put(otherNode, 1); } } } else { if (shouldInclude(otherNode, entityList) == true && !nodeHash.containsKey(otherNode)) { otherNodeList.add(otherNode); nodeHash.put(otherNode, 1); } } } /* I have a list of other nodes to expand now, if the list is not empty * output the local node first and then the links and other nodes * if i am going to skip remove the node from the nodeHash */ if (otherNodeList.size() == 0) { nodeHash.remove(node); continue; } logger.error("Other node list {}", otherNodeList); /* add information about the current node */ nodeHash.put(node, 1); JSONObject nodeInfo = new JSONObject(); String[] myTokens = getTokensFromFormattedString( node.getProperty(EntityGraphConstants.NODE_NAME).toString()); nodeInfo.put("nodeId", node.getId()); nodeInfo.put("entityId", node.getProperty(EntityGraphConstants.NODE_ID)); String typeStr = null; objectType = getNodeType(node); switch (objectType) { case "User": typeStr = EntityGraphConstants.UBER_GRAPH_USER_LABEL; nodeInfo.put(EntityGraphConstants.RES_LABEL_TAG, myTokens[myTokens.length - 1]); break; case "Device": Object deviceTypeObj = node.getProperty(EntityGraphConstants.DEVICE_TYPE); String deviceType = (deviceTypeObj != null) ? deviceTypeObj.toString() : "Desktop"; typeStr = EntityGraphConstants.UBER_GRAPH_DEVICE_LABEL; nodeInfo.put(EntityGraphConstants.RES_LABEL_TAG, myTokens[myTokens.length - 1]); nodeInfo.put("entitySubtype", deviceType); break; case "Application": typeStr = EntityGraphConstants.UBER_GRAPH_APPLICATION_LABEL; nodeInfo.put(EntityGraphConstants.RES_LABEL_TAG, myTokens[myTokens.length - 1]); break; case "Threat": typeStr = EntityGraphConstants.UBER_GRAPH_THREAT_LABEL; /* anomalies do not have a meaningful label */ nodeInfo.put(EntityGraphConstants.RES_LABEL_TAG, "Anomaly"); nodeInfo.put("entitySubtype", node.getProperty(EntityGraphConstants.ANOMALY_TYPE)); break; case "Url": typeStr = EntityGraphConstants.UBER_GRAPH_URL_LABEL; nodeInfo.put(EntityGraphConstants.RES_LABEL_TAG, myTokens[myTokens.length - 1]); default: break; } nodeInfo.put("entityType", typeStr); nodes.add(nodeInfo); for (Node otherNode : otherNodeList) { /* add information about the relationship */ JSONObject edgeInfo = new JSONObject(); edgeInfo.put(EntityGraphConstants.RES_SOURCE_ID_TAG, node.getId()); edgeInfo.put(EntityGraphConstants.RES_TARGET_ID_TAG, otherNode.getId()); edgeInfo.put(EntityGraphConstants.RES_LINK_ID_TAG, uniqueLinkId); uniqueLinkId += 1; edges.add(edgeInfo); /* add information about the other node */ nodeInfo = new JSONObject(); myTokens = getTokensFromFormattedString( otherNode.getProperty(EntityGraphConstants.NODE_NAME).toString()); nodeInfo.put("nodeId", otherNode.getId()); nodeInfo.put("entityId", otherNode.getProperty(EntityGraphConstants.NODE_ID)); typeStr = null; otherObjectType = getNodeType(otherNode); switch (otherObjectType) { case "User": typeStr = EntityGraphConstants.UBER_GRAPH_USER_LABEL; nodeInfo.put(EntityGraphConstants.RES_LABEL_TAG, myTokens[myTokens.length - 1]); break; case "Device": Object deviceTypeObj = otherNode.getProperty(EntityGraphConstants.DEVICE_TYPE); String deviceType = (deviceTypeObj != null) ? deviceTypeObj.toString() : "Desktop"; typeStr = EntityGraphConstants.UBER_GRAPH_DEVICE_LABEL; nodeInfo.put(EntityGraphConstants.RES_LABEL_TAG, myTokens[myTokens.length - 1]); nodeInfo.put("entitySubtype", deviceType); break; case "Application": typeStr = EntityGraphConstants.UBER_GRAPH_APPLICATION_LABEL; nodeInfo.put(EntityGraphConstants.RES_LABEL_TAG, myTokens[myTokens.length - 1]); break; case "Threat": typeStr = EntityGraphConstants.UBER_GRAPH_THREAT_LABEL; /* anomalies do not have a meaningful label */ nodeInfo.put(EntityGraphConstants.RES_LABEL_TAG, "Anomaly"); nodeInfo.put("entitySubtype", node.getProperty(EntityGraphConstants.ANOMALY_TYPE)); break; case "Url": typeStr = EntityGraphConstants.UBER_GRAPH_URL_LABEL; nodeInfo.put(EntityGraphConstants.RES_LABEL_TAG, myTokens[myTokens.length - 1]); default: break; } nodeInfo.put("entityType", typeStr); nodes.add(nodeInfo); } } } response.put("nodes", nodes); response.put("links", edges); if (logger.isDebugEnabled()) { logger.debug("Response : {}", response.toJSONString()); } return response.toString(); }
From source file:net.swas.explorer.servlet.mgt.AddHttpPolicy.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//*from w w w .j a v a2s. c o m*/ @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userID = request.getParameter("userID"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); JSONObject json = new JSONObject(); log.info("IN DATA SET PARSING SERVLET........."); if (FormFieldValidator.isLogin(request.getSession())) { log.info("session valid........."); // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); PrintWriter out = response.getWriter(); if (!isMultipart) { return; } KBConfiguration config = KBConfiguration.getInstance(getServletContext()); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(config.getUploadFolderPath())); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { // Parse the request to get file items. List<FileItem> fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator<FileItem> i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters fileName = fi.getName(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); boolean check = true; log.info("parse data set servlet called......"); log.info("File Name::" + filePath + fileName); check = Profile.parseRequestByFile(filePath + fileName, getServletContext()); if (check) { log.info("dataSet added..."); stat = "0"; msg = "Translated successfully"; json.put("status", stat); json.put("message", msg); } else { log.info("No dataSet added..."); stat = "1"; msg = "Translation UN-successfully"; json.put("status", stat); json.put("message", msg); } try { log.info("Sending Json : " + json.toString()); out.print(json.toString()); } catch (Exception ex) { System.out.println(ex); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { out.close(); } } else { stat = "2"; msg = "User Session Expired"; json.put("status", stat); json.put("message", msg); } }
From source file:net.swas.explorer.servlet.mgt.AddResourceRule.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *///from w ww . ja v a 2 s.c om protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String status = "0"; List<String> msg = new ArrayList<String>(); JSONObject json = new JSONObject(); PrintWriter out = response.getWriter(); if (FormFieldValidator.isLogin(request.getSession())) { log.info("Getting form parameters .. "); // request parameters String userID = (String) request.getSession().getAttribute("userName"); String ruleGroup = request.getParameter("ruleGroup"); String severity = request.getParameter("ruleSeverity"); String ruleTitle = request.getParameter("Title"); String message = request.getParameter("ruleMessage"); String phase = request.getParameter("rulePhase"); String action = request.getParameter("disruptiveActions"); String[] operators = request.getParameterValues("operator"); String target = request.getParameter("targets"); String conditionValue = request.getParameter("value"); String resource = request.getParameter("resource"); log.info("User ID:" + userID + "\nRule Group:" + ruleGroup + "\nSeverity:" + severity + "\nRule Title:" + ruleTitle + "\nMessage:" + message + "\nPhase:" + phase + "\nAction:" + action + "\nTarget" + target + "\nOperator:" + operators[0] + "\nCondition Value:" + conditionValue + "\nResource : " + resource); log.info("setting values to beans ..."); Rule rule = null; //ChainRule chainRule = null; response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); msg.addAll(FormFieldValidator.validateRule("simple", ruleGroup, ruleTitle, phase, action)); Resource res = null; if (msg.size() > 0) { status = "1"; } User user = SemTranslator.toUserBeans(userID, userID, ""); MetaData md = SemTranslator.toMetaDataBean("", message, "1.0", severity, null); RuleGroup group = SemTranslator.toRuleGroupBeans(ruleGroup, ""); group.setUserCreatedBy(user); Variable variable = Fetcher.toVariableBean(target, loader); Condition cond = SemTranslator.toConditionBean(false, operators[0], conditionValue, variable, null); try { res = SemTranslator.toResourceBean(resource, getServletContext()); } catch (InstantiationException | IllegalAccessException | SQLException e) { e.printStackTrace(); } int ph = Integer.parseInt(phase); rule = SemTranslator.toRuleBean(ruleTitle, md, cond, action, ph, "", group); rule.setResource(res); rule.setUserCreatedBy(user); log.info("Beans Created ..."); if (rule instanceof Rule) { if (rulehandler.add(rule) != null) { log.info("rule stored successfully ..."); status = "0"; msg.add("rule added sucessfully"); } else { status = "1"; msg.add("Rule is not stored"); } } } else { status = "2"; msg.add("User Session Expired"); } json.put("status", status); json.put("message", msg); try { log.info("Sending Json : " + json.toString()); out.print(json.toString()); } finally { out.close(); } }
From source file:net.swas.explorer.servlet.mgt.AddRuleFormGroup.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//*www .j a va2s . c o m*/ @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("Getting form parameters .. "); String name = request.getParameter("name"); String status = "", msg = ""; List<String> groupList = new ArrayList<String>(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); JSONObject json = new JSONObject(); if (FormFieldValidator.isLogin(request.getSession())) { String userID = (String) request.getSession().getAttribute("userName"); if (name.length() != 0) { log.info("Group Name : " + name); name = name.replace(" ", "_"); User user = SemTranslator.toUserBeans(userID, "", ""); RuleGroup group = SemTranslator.toRuleGroupBeans(name, ""); group.setUserCreatedBy(user); if (handler.add(group) != null) { log.info("Group stored successfully ..."); status = "0"; msg = "Group added successfully"; for (Entity entity : handler.getAll()) { RuleGroup rg = (RuleGroup) entity; groupList.add(rg.getName()); } json.put("groups", groupList); json.put("selected", name); } else { status = "1"; msg = "Un-succcesful"; } } else { status = "1"; msg = "please fill out blank field"; } } else { status = "2"; msg = "User Session Expired"; } json.put("status", status); json.put("message", msg); try { log.info("Sending Json : " + json.toString()); out.print(json.toString()); } finally { out.close(); } }
From source file:net.swas.explorer.servlet.mgt.AddSemRule.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)/*from w ww .ja v a 2 s . c o m*/ */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String status = "0"; List<String> msg = new ArrayList<String>(); JSONObject json = new JSONObject(); PrintWriter out = response.getWriter(); if (FormFieldValidator.isLogin(request.getSession())) { log.info("Getting form parameters .. "); // request parameters String userID = (String) request.getSession().getAttribute("userName"); String ruleGroup = request.getParameter("selectedGroup"); String ruleType = request.getParameter("selectedType"); String severity = request.getParameter("selectedSeverity"); String ruleTitle = request.getParameter("selectedTitle"); String revision = request.getParameter("selectedRevision"); String tags = request.getParameter("selectedTags"); String message = request.getParameter("selectedMessage"); String description = request.getParameter("selectedDescription"); String phase = request.getParameter("selectedPhase"); String action = request.getParameter("selectedAction"); String[] transformations = request.getParameterValues("selectedTransformations"); String[] transVarNames = request.getParameterValues("selectedTransVarName"); String[] transVarValues = request.getParameterValues("selectedTransVarValue"); String[] conditionValues = request.getParameterValues("selectedConditionValues"); String[] operators = request.getParameterValues("selectedOperators"); String[] expressions = request.getParameterValues("selectedExpressions"); Rule rule = null; ChainRule chainRule = null; response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); log.info( "ruleID :" + ruleGroup + "\t Severity:" + severity + "\t Title :" + ruleTitle + "\t revision :" + revision + "\n\t tags:" + tags + "\t action :" + action + "\t\n transformations :" + transformations + "\t phase :" + phase + "\t description :" + description); log.info("setting values to beans ..."); msg.addAll(FormFieldValidator.validateRule(ruleType, ruleGroup, ruleTitle, phase, action)); if (msg.size() > 0) { status = "1"; } if (status.equals("0")) { String[] tagList = tags.split(","); User user = SemTranslator.toUserBeans(userID, "", ""); MetaData md = SemTranslator.toMetaDataBean("", message, revision, severity, Arrays.asList(tagList)); RuleGroup group = SemTranslator.toRuleGroupBeans(ruleGroup, ""); group.setUserCreatedBy(user); if (ruleType.equals("SimpleRule")) { String[] transList = transformations[0].split(","); List<VariableExpression> varExpList = SemTranslator.toVariableExpBeans(expressions[0]); List<CollectionExpression> colExpList = SemTranslator.toCollectionExpBeans(expressions[0]); for (VariableExpression varExp : varExpList) { log.info("Variable Expression " + varExpList.size() + " : " + varExp.getOperator() + varExp.getVariable()); } for (CollectionExpression colExp : colExpList) { log.info("Collection Expression : " + colExpList.size() + ":" + colExp.getOperator() + colExp.getCollection() + ":" + colExp.getElement()); } Variable var = SemTranslator.toVariableBean( FormFieldValidator.normaliseTransformtions(transList), varExpList, colExpList); List<UserDefinedVariable> udvList = SemTranslator .toUserDefVariablesBeans(transVarNames[0].split(","), transVarValues[0].split(",")); Condition cond = SemTranslator.toConditionBean(false, operators[0], conditionValues[0], var, udvList); int ph = Integer.parseInt(phase); rule = SemTranslator.toRuleBean(ruleTitle, md, cond, action, ph, description, group); rule.setUserCreatedBy(user); } else { List<Condition> conditions = new ArrayList<Condition>(); for (int i = 0; i < expressions.length; i++) { String[] transList = transformations[i].split(","); List<VariableExpression> varExpList = SemTranslator.toVariableExpBeans(expressions[i]); List<CollectionExpression> colExpList = SemTranslator.toCollectionExpBeans(expressions[i]); Variable var = SemTranslator.toVariableBean( FormFieldValidator.normaliseTransformtions(transList), varExpList, colExpList); List<UserDefinedVariable> udvList = SemTranslator .toUserDefVariablesBeans(transVarNames[i].split(","), transVarValues[i].split(",")); Condition cond = SemTranslator.toConditionBean(false, operators[i], conditionValues[i], var, udvList); conditions.add(cond); } int ph = Integer.parseInt(phase); chainRule = SemTranslator.toChainRuleBean(ruleTitle, md, conditions, action, ph, description, group); chainRule.setUserCreatedBy(user); } if (rule instanceof Rule) { if (rulehandler.add(rule) != null) { log.info("rule stored successfully ..."); status = "0"; msg.add("rule added sucessfully"); } else { status = "1"; msg.add("Rule is not stored"); } } else { if (chainHandler.add(chainRule) != null) { log.info("rule stored successfully ..."); status = "0"; msg.add("rule added sucessfully"); } else { status = "1"; msg.add("Rule is not stored"); } } } } else { status = "2"; msg.add("User Session Expired"); } json.put("status", status); json.put("message", msg); try { log.info("Sending Json : " + json.toString()); out.print(json.toString()); } finally { out.close(); } }
From source file:net.swas.explorer.servlet.mgt.EditSemRule.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)/*w ww . j a v a 2 s. co m*/ */ @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); JSONObject json = new JSONObject(); String status = "0"; List<String> msg = new ArrayList<String>(); if (FormFieldValidator.isLogin(request.getSession())) { log.info("Getting form parameters .. "); // request parameters String userID = request.getParameter("userID"); String ruleID = request.getParameter("ruleID"); String ruleGroup = request.getParameter("selectedGroup"); String ruleType = request.getParameter("selectedType"); String severity = request.getParameter("selectedSeverity"); String ruleTitle = request.getParameter("selectedTitle"); String revision = request.getParameter("selectedRevision"); String tags = request.getParameter("selectedTags"); String message = request.getParameter("selectedMessage"); String description = request.getParameter("selectedDescription"); String phase = request.getParameter("selectedPhase"); String action = request.getParameter("selectedAction"); String[] transformations = request.getParameterValues("selectedTransformations"); String[] transVarNames = request.getParameterValues("selectedTransVarName"); String[] transVarValues = request.getParameterValues("selectedTransVarValue"); String[] conditionValues = request.getParameterValues("selectedConditionValues"); String[] operators = request.getParameterValues("selectedOperators"); String[] expressions = request.getParameterValues("selectedExpressions"); Rule rule = null; ChainRule chainRule = null; log.info( "ruleID :" + ruleGroup + "\t Severity:" + severity + "\t Title :" + ruleTitle + "\t revision :" + revision + "\n\t tags:" + tags + "\t action :" + action + "\t\n transformations :" + transformations + "\t phase :" + phase + "\t description :" + description); log.info("setting values to beans ..."); msg.addAll(FormFieldValidator.validateRule(ruleType, ruleGroup, ruleTitle, phase, action)); if (msg.size() > 0) { status = "1"; } if (status.equals("0")) { String[] tagList = tags.split(","); User user = SemTranslator.toUserBeans(userID, "", ""); MetaData md = SemTranslator.toMetaDataBean("", message, revision, severity, Arrays.asList(tagList)); RuleGroup group = SemTranslator.toRuleGroupBeans(ruleGroup, ""); if (ruleType.equals("SimpleRule")) { String[] transList = transformations[0].split(","); List<VariableExpression> varExpList = SemTranslator.toVariableExpBeans(expressions[0]); List<CollectionExpression> colExpList = SemTranslator.toCollectionExpBeans(expressions[0]); List<UserDefinedVariable> udvList = new ArrayList<UserDefinedVariable>(); Variable var = SemTranslator.toVariableBean( FormFieldValidator.normaliseTransformtions(transList), varExpList, colExpList); if (transVarNames[0].contains(",")) { udvList = SemTranslator.toUserDefVariablesBeans(transVarNames[0].split(","), transVarValues[0].split(",")); } else { udvList = SemTranslator.toUserDefVariablesBeans(transVarNames[0], transVarValues[0]); } Condition cond = SemTranslator.toConditionBean(false, operators[0], conditionValues[0], var, udvList); int ph = Integer.parseInt(phase); rule = SemTranslator.toRuleBean(ruleTitle, md, cond, action, ph, description, group); rule.setUserEditedBy(user); Rule preRule = (Rule) this.rulehandler.get(ruleID.split("\\.")[1]); rule.setID(preRule.getID()); rule.getMetaData().setID(preRule.getMetaData().getID()); rule.getCondition().setID(preRule.getCondition().getID()); rule.getCondition().getVariable().setID(preRule.getCondition().getVariable().getID()); } else { List<Condition> conditions = new ArrayList<Condition>(); for (int i = 0; i < expressions.length; i++) { String[] transList = transformations[i].split(","); List<VariableExpression> varExpList = SemTranslator.toVariableExpBeans(expressions[i]); List<CollectionExpression> colExpList = SemTranslator.toCollectionExpBeans(expressions[i]); List<UserDefinedVariable> udvList = new ArrayList<UserDefinedVariable>(); Variable var = SemTranslator.toVariableBean( FormFieldValidator.normaliseTransformtions(transList), varExpList, colExpList); if (transVarNames[0].contains(",")) { udvList = SemTranslator.toUserDefVariablesBeans(transVarNames[0].split(","), transVarValues[0].split(",")); } else { udvList = SemTranslator.toUserDefVariablesBeans(transVarNames[0], transVarValues[0]); } Condition cond = SemTranslator.toConditionBean(false, operators[i], conditionValues[i], var, udvList); conditions.add(cond); } int ph = Integer.parseInt(phase); chainRule = SemTranslator.toChainRuleBean(ruleTitle, md, conditions, action, ph, description, group); chainRule.setUserEditedBy(user); ChainRule preRule = (ChainRule) this.chainHandler.get(ruleID.split("\\.")[1]); chainRule.setID(preRule.getID()); chainRule.getMetaData().setID(preRule.getMetaData().getID()); } if (rule instanceof Rule) { if (rulehandler.update(rule) != null) { log.info("rule stored successfully ..."); status = "0"; msg.add("rule added sucessfully"); } else { status = "1"; msg.add("Rule is not stored"); } } else { if (chainHandler.update(chainRule) != null) { log.info("rule stored successfully ..."); status = "0"; msg.add("rule added sucessfully"); } else { status = "1"; msg.add("Rule is not stored"); } } } } else { status = "2"; msg.add("User Session Expired"); } json.put("status", status); json.put("message", msg); try { log.info("Sending Json : " + json.toString()); out.print(json.toString()); } finally { out.close(); } }