public static HashMap<String, Integer> getAnimeSearchedMAL(
      String username, String password, String anime) {
    HashMap<String, Integer> map = new HashMap<String, Integer>();

    JSONObject xmlJSONObj;
    String json = "";
    String xml = "";
    try {
      xml = searchAnimeMAL(username, password, anime);
      xmlJSONObj = XML.toJSONObject(xml);
      json = xmlJSONObj.toString(4);
    } catch (Exception e) {
      MAMUtil.writeLog(e);
      e.printStackTrace();
    }
    JsonParser parser = new JsonParser();
    JsonObject root = parser.parse(json).getAsJsonObject();
    if (root.has("anime") && root.get("anime").getAsJsonObject().get("entry").isJsonArray()) {
      JsonArray searchedAnime = root.get("anime").getAsJsonObject().get("entry").getAsJsonArray();
      for (JsonElement obj : searchedAnime) {
        String name = obj.getAsJsonObject().get("title").getAsString();
        int id = obj.getAsJsonObject().get("id").getAsInt();
        map.put(name, id);
      }
    } else if (root.has("anime")) {
      JsonObject obj = root.get("anime").getAsJsonObject().get("entry").getAsJsonObject();
      int id = obj.getAsJsonObject().get("id").getAsInt();
      map.put(anime, id);
    }
    return map;
  }
  public void LoadSeedData(String strColl, String metadatafile) throws Exception {
    try {
      InputStream is = this.getClass().getResourceAsStream(metadatafile);
      String xml;
      xml = IOUtils.toString(is);
      JSONObject rwSeed = XML.toJSONObject(xml);

      if (!rwSeed.isNull("ReferralWireSeedData")) {
        JSONObject json = rwSeed.getJSONObject("ReferralWireSeedData");
        DBCollection dbcoll = store.getColl(strColl);

        Object coll = (Object) json.get(strColl);
        if (coll instanceof JSONArray) {
          JSONArray defs = (JSONArray) coll;
          for (int i = 0; i < defs.length(); i++) {
            Object obj = (JSONObject) defs.get(i);
            dbcoll.insert((DBObject) com.mongodb.util.JSON.parse(obj.toString()));
          }
        } else {
          dbcoll.insert((DBObject) com.mongodb.util.JSON.parse(coll.toString()));
        }
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      log.debug("API Error: ", e);
    }
  }
  /**
   * This method <code>onlinePayment</code> is used for the Both M-pesa & Tigo-pesa PaymentGateways
   * to Pay the Money.
   *
   * @param requestData Containg input data in the Form of Xml/Soap .
   * @return
   */
  @POST
  @Consumes({MediaType.WILDCARD})
  @Produces({MediaType.APPLICATION_XML})
  public String onlinePayment(final String requestData) {

    try {
      final JSONObject xmlJSONObj = XML.toJSONObject(requestData);
      jsonData = this.returnJsonFromXml(xmlJSONObj);
      final CommandWrapper commandRequest =
          new CommandWrapperBuilder().createPaymentGateway().withJson(jsonData.toString()).build();
      result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
      success = "SUCCESS";
      errorDesc = "";
      errorCode = Long.valueOf(0);
      contentData = "OBSTRANSACTIONID=" + result.resourceId();
      return this.returnToServer();
    } catch (ReceiptNoDuplicateException e) {
      success = "DUPLICATE_TXN";
      errorDesc = "DUPLICATE";
      errorCode = Long.valueOf(1);
      contentData = "TXNID ALREADY EXIST";
      return this.returnToServer();
    } catch (JSONException e) {
      return e.getCause().toString();
    } catch (PlatformDataIntegrityException e) {
      return null;
    }
  }
예제 #4
0
	protected void SaveDirectory(Document doc) throws TransformerException, ParserConfigurationException {
		
		String xmlStr = OperateXMLByDOM.doc2FormatString(doc);
		AsciiSaveUtil.saveAscii(outDir+"tree.xml", xmlStr);

		// hack的方法, 给每个目录加一个空节点
		List<Node> nl2 = new ArrayList<Node>();
		nl2.add(doc.getElementsByTagName("root").item(0));
		NodeList nl = doc.getElementsByTagName("children");
		for (int i = 0; i < nl.getLength(); i++) {
			if (((Element)nl.item(i)).getAttribute("id") == "")
				nl2.add(nl.item(i));
		}
		for (Node node: nl2){
			node.appendChild(doc.createElement("children"));
		}
		
		xmlStr = OperateXMLByDOM.doc2FormatString(doc);
		JSONObject soapDatainJsonObject = XML.toJSONObject(xmlStr);
				String jsonString = soapDatainJsonObject.toString();
		
		// 通过字符替换把这些空节点去掉,以达到产生[]括号对的目的
		String tmp = jsonString.replaceAll(",\\\"\\\"", "");
		String json = "["+tmp.substring(8, tmp.length()-1)+"]";
		AsciiSaveUtil.saveAscii(outDir+"tree.json", json);
	}
예제 #5
0
  /**
   * Parses AGGREGATE results for Oskari front
   *
   * @param response WPS vec:aggregate execute results
   * @param analysisLayer analysis layer params (field/columns info)
   * @return JSON.toSting() eg. aggregate WPS results
   *     **********************************************************************
   */
  public String parseAggregateResults(String response, AnalysisLayer analysisLayer) {

    try {

      // convert xml/text String to JSON

      final JSONObject json = XML.toJSONObject(response); // all
      // Add field name
      final AggregateMethodParams aggreParams =
          (AggregateMethodParams) analysisLayer.getAnalysisMethodParams();
      String fieldName = aggreParams.getAggreField1();
      if (analysisLayer.getInputAnalysisId() != null) {
        fieldName =
            analysisDataService.SwitchField2OriginalField(
                fieldName, analysisLayer.getInputAnalysisId());
      }
      json.put("fieldName", fieldName);
      return json.toString();

    } catch (JSONException e) {
      log.error(e, "XML to JSON failed", response);
    }

    return "{}";
  }
예제 #6
0
 /**
  * Parses an XML config file.
  *
  * @param filename The path to the file to parse.
  */
 public void parse(String filename) throws ConfigException {
   try {
     String xml = Utils.fileToString(filename);
     JSONObject jobj = XML.toJSONObject(xml);
     configObject = (Map) new JSONReader(jobj.toString()).readObject();
   } catch (Exception e) {
     throw new ConfigException("Error parsing config", e);
   }
 }
예제 #7
0
  public static byte[] convertToJSON(
      IExtensionHelpers helpers, IHttpRequestResponse requestResponse) {

    byte[] request = requestResponse.getRequest();

    if (Objects.equals(helpers.analyzeRequest(request).getMethod(), "GET")) {
      request = helpers.toggleRequestMethod(request);
    }

    IRequestInfo requestInfo = helpers.analyzeRequest(request);

    int bodyOffset = requestInfo.getBodyOffset();

    byte content_type = requestInfo.getContentType();

    String body = new String(request, bodyOffset, request.length - bodyOffset);

    String json = "";

    Boolean success = true;

    try {
      if (content_type == 3) {
        JSONObject xmlJSONObject = XML.toJSONObject(body);
        json = xmlJSONObject.toString(2);
      } else if (content_type == 0 || content_type == 1) {
        Map<String, String> params = splitQuery(body);
        Gson gson = new Gson();
        json = gson.toJson(params);
      } else {
        json = body;
      }
    } catch (Exception e) {
      success = false;
    }

    if (!success) {
      return request;
    } else {

      List<String> headers;

      headers = helpers.analyzeRequest(request).getHeaders();

      Iterator<String> iter = headers.iterator();
      while (iter.hasNext()) {
        if (iter.next().contains("Content-Type")) iter.remove();
      }

      headers.add("Content-Type: application/json;charset=UTF-8");

      return helpers.buildHttpMessage(headers, json.getBytes());
    }
  }
 private void sendResponse(HttpServletResponse resp, String payload, boolean json) {
   if (json) {
     JSONObject jsonObject = XML.toJSONObject(payload);
     payload = jsonObject.toString(3);
   }
   try {
     OutputStream outputStream = resp.getOutputStream();
     outputStream.write(payload.getBytes());
     outputStream.flush();
   } catch (IOException e) {
     throw new HTTPException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
   }
 }
 // Send the response payload to the client.
 private void sendResponse(HttpServletResponse response, String payload, boolean json) {
   try {
     // Convert to JSON?
     if (json) {
       JSONObject jobt = XML.toJSONObject(payload);
       payload = jobt.toString(3); // 3 is indentation level for nice
       // look
     }
     OutputStream out = response.getOutputStream();
     out.write(payload.getBytes());
     out.flush();
   } catch (Exception exception) {
     throw new HTTPException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
   }
 }
예제 #10
0
  public XMLImport(File xmlFile, String worksheetName, Workspace workspace) {
    super(worksheetName, workspace);

    try {
      String fileContents = FileUtil.readFileContentsToString(xmlFile);

      // Converting the XML to JSON
      JSONObject json = XML.toJSONObject(fileContents);
      jsonImport = new JsonImport(json, this.getFactory(), this.getWorksheet());
    } catch (JSONException ex) {
      logger.error("Error in populating the worksheet with XML");
    } catch (IOException ex) {
      logger.error("Error in reading the XML file");
    }
  }
  public void LoadSTNSpeakers(String mapfile) throws Exception {

    String mongoTableName = "rwParty";
    String xmlCollection = "SeedLOVMaps";
    try {
      InputStream is = this.getClass().getResourceAsStream(mapfile);
      String xml;
      xml = IOUtils.toString(is);
      JSONObject rwSeed = XML.toJSONObject(xml);

      if (!rwSeed.isNull(xmlCollection)) {
        JSONObject json = rwSeed.getJSONObject(xmlCollection);
        DBCollection dbTable = store.getColl(mongoTableName);

        Object xmlRecords = (Object) json.get(mongoTableName);
        if (xmlRecords instanceof JSONArray == false) {
          JSONObject xmlRecord = (JSONObject) xmlRecords;
          JSONArray jAry = new JSONArray();
          jAry.put(xmlRecord);
          xmlRecords = jAry;
        }

        if (xmlRecords instanceof JSONArray) {
          JSONArray xmlRecordAry = (JSONArray) xmlRecords;
          for (int i = 0; i < xmlRecordAry.length(); i++) {
            JSONObject xmlRecord = (JSONObject) xmlRecordAry.get(i);

            String parent_GlobalVal = xmlRecord.getString("parent_GlobalVal");
            String child_GlobalVal = xmlRecord.getString("child_GlobalVal");
            String parent_LovType = xmlRecord.getString("parent_LovType");
            String child_LovType = xmlRecord.getString("child_LovType");
            String childId = getLOVId(child_LovType, child_GlobalVal);
            String parentId = getLOVId(parent_LovType, parent_GlobalVal);
            xmlRecord.put("parentId", parentId);
            xmlRecord.put("childId", childId);
            dbTable.insert((DBObject) com.mongodb.util.JSON.parse(xmlRecord.toString()));
          }
        } else {
          dbTable.insert((DBObject) com.mongodb.util.JSON.parse(xmlRecords.toString()));
        }
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      log.debug("API Error: ", e);
    }
  }
예제 #12
0
  /**
   * Marshals a SearchResult or ModsType object to an XML string. This string is converted to json
   * using the org.json package. Order of the json array is not guaranteed (as per spec); TO DO
   * (201405007) - investigate means for preserving XML order (json schema?)
   *
   * @param obj a a SearchResult or ModsType object for conversion to json string
   * @return the json String
   */
  protected String writeJson(Object obj) throws JAXBException {
    StringWriter sw = new StringWriter();
    String jsonString = null;
    Marshaller jaxbMarshaller = JAXBHelper.context.createMarshaller();
    jaxbMarshaller.marshal(obj, sw);

    try {
      String xml = sw.toString();
      JSONObject xmlJSONObj = XML.toJSONObject(xml);
      jsonString = xmlJSONObj.toString(5);
      // System.out.println(jsonString);
    } catch (JSONException je) {
      log.error(je.getMessage());
      je.printStackTrace();
    }
    return jsonString;
  }
예제 #13
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    PrintWriter out = response.getWriter();
    String location = URLDecoder.decode(request.getParameter("location"));
    String type = URLDecoder.decode(request.getParameter("type"));
    String unit = URLDecoder.decode(request.getParameter("unit"));
    String awsURL =
        "http://default-environment-ii9naedwp8.elasticbeanstalk.com/?location="
            + URLEncoder.encode(location)
            + "&type="
            + type
            + "&unit="
            + unit;
    // out.write(awsURL);
    String myurl = URLEncoder.encode(awsURL);
    // out.write("\n"+myurl);
    URL url = new URL(awsURL);
    URLConnection urlConnection = url.openConnection();

    InputStream awsResponse = urlConnection.getInputStream();
    InputStreamReader iSReader = new InputStreamReader(awsResponse);
    StringBuffer sb = new StringBuffer();
    String xmlLine;
    BufferedReader buf = new BufferedReader(iSReader);
    try {
      while ((xmlLine = buf.readLine()) != null) {
        sb.append(xmlLine);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    xmlLine = sb.toString();

    response.setContentType("application/json; charset=UTF-8");
    int indent = 6;
    try {
      JSONObject jsonObj = XML.toJSONObject(xmlLine);
      String json1 = jsonObj.toString(indent);
      out.write(json1);
    } catch (JSONException ex) {
      ex.printStackTrace();
    }
  }
  public void LoadSavedSearch(String datafile, String mongoTableName, String xmlCollection)
      throws Exception {
    // String mongoTableName = "rwSavedSearch";
    // String xmlCollection = "SavedSearches";
    try {
      InputStream is = this.getClass().getResourceAsStream(datafile);
      String xml;
      xml = IOUtils.toString(is);
      JSONObject rwSeed = XML.toJSONObject(xml);

      if (!rwSeed.isNull(xmlCollection)) {
        JSONObject json = rwSeed.getJSONObject(xmlCollection);
        DBCollection dbTable = store.getColl(mongoTableName);

        Object xmlRecords = (Object) json.get(mongoTableName);
        if (xmlRecords instanceof JSONArray == false) {
          JSONObject xmlRecord = (JSONObject) xmlRecords;
          JSONArray jAry = new JSONArray();
          jAry.put(xmlRecord);
          xmlRecords = jAry;
        }

        if (xmlRecords instanceof JSONArray) {
          JSONArray xmlRecordAry = (JSONArray) xmlRecords;
          for (int i = 0; i < xmlRecordAry.length(); i++) {
            JSONObject xmlRecord = (JSONObject) xmlRecordAry.get(i);
            dbTable.insert((DBObject) com.mongodb.util.JSON.parse(xmlRecord.toString()));
          }
        } else {
          dbTable.insert((DBObject) com.mongodb.util.JSON.parse(xmlRecords.toString()));
        }
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      log.debug("API Error: ", e);
    }
  }
예제 #15
0
  private DocumentPojo buildDocument(
      SyndEntry entry, SourcePojo source, LinkedList<String> duplicateSources) {

    String tmpURL = this.cleanUrlStart(entry.getLink().toString());
    // (can't return null because called from code which checks this)

    // create the feed pojo
    DocumentPojo doc = new DocumentPojo();

    doc.setUrl(tmpURL);
    doc.setCreated(new Date());
    doc.setModified(new Date());

    // Strip out html if it is present
    if (entry.getTitle() != null) doc.setTitle(entry.getTitle().replaceAll("\\<.*?\\>", "").trim());
    if (entry.getDescription() != null)
      doc.setDescription(entry.getDescription().getValue().replaceAll("\\<.*?\\>", "").trim());
    if (entry.getPublishedDate() != null) {
      doc.setPublishedDate(entry.getPublishedDate());
    } else {
      doc.setPublishedDate(new Date());
    }

    // Clone from an existing source if we can:
    if (!duplicateSources.isEmpty()
        && (null == doc.getUpdateId())) { // (can't duplicate updating document)
      doc.setDuplicateFrom(duplicateSources.getFirst());
    }

    // GeoRSS
    GeoRSSModule geoRSSModule =
        GeoRSSUtils.getGeoRSS(entry); // currently does not handle <georss:circle>
    if (null != geoRSSModule) {
      if (null != geoRSSModule.getPosition()) {
        double lat = geoRSSModule.getPosition().getLatitude();
        double lon = geoRSSModule.getPosition().getLongitude();
        GeoPojo gp = new GeoPojo();
        gp.lat = lat;
        gp.lon = lon;
        doc.setDocGeo(gp);
      }
      if (null != geoRSSModule.getGeometry()) {
        AbstractGeometry ag = geoRSSModule.getGeometry();
        if (ag.getClass().equals(new LineString().getClass())) { // <georss:line>
          LineString ls = ((LineString) geoRSSModule.getGeometry());

          double latAvg = 0.0;
          double lonAvg = 0.0;
          int length = ls.getPositionList().size();
          for (int i = 0; i < length; i++) {
            latAvg += ls.getPositionList().getLatitude(i);
            lonAvg += ls.getPositionList().getLongitude(i);
          }
          latAvg = latAvg / length;
          lonAvg = lonAvg / length;
          GeoPojo gp = new GeoPojo();
          gp.lat = latAvg;
          gp.lon = lonAvg;
          doc.setDocGeo(gp);
        } else if (ag.getClass().equals(new Polygon().getClass())) // <georss:polygon>
        {
          Polygon poly = ((Polygon) geoRSSModule.getGeometry());
          AbstractRing ar = poly.getExterior();
          LinearRing lr = (LinearRing) ar;

          double latAvg = 0.0;
          double lonAvg = 0.0;
          int length = lr.getPositionList().size();
          for (int i = 0; i < length; i++) {
            latAvg += lr.getPositionList().getLatitude(i);
            lonAvg += lr.getPositionList().getLongitude(i);
          }
          latAvg = latAvg / length;
          lonAvg = lonAvg / length;
          GeoPojo gp = new GeoPojo();
          gp.lat = latAvg;
          gp.lon = lonAvg;
          doc.setDocGeo(gp);
        } else if (ag.getClass().equals(new Envelope().getClass())) { // <georss:box>
          Envelope env = ((Envelope) geoRSSModule.getGeometry());

          double latAvg = (env.getMaxLatitude() + env.getMinLatitude()) / 2;
          double lonAvg = (env.getMaxLongitude() + env.getMinLongitude()) / 2;

          GeoPojo gp = new GeoPojo();
          gp.lat = latAvg;
          gp.lon = lonAvg;
          doc.setDocGeo(gp);
        }
      }
    } // end if GeoRSS

    // Arbitrary other metadata:

    if (null != entry.getForeignMarkup()) {
      JSONObject rssMetadata = new JSONObject();

      @SuppressWarnings("unchecked")
      List<Element> fms = (List<Element>) entry.getForeignMarkup();
      for (Element fm : fms) {
        try {
          JSONObject subObj = XML.toJSONObject(new XMLOutputter().outputString(fm));
          if (1 == subObj.length()) {
            for (String name : JSONObject.getNames(subObj)) {
              rssMetadata.put(name, subObj.get(name));
            }
          } else { // (this will never happen in practice?)
            rssMetadata.put(fm.getName(), subObj);
          }
        } catch (JSONException e) {
        } // (do nothing just carry on)
      }
      if (!fms.isEmpty()) {
        doc.addToMetadata(
            "_FEED_METADATA_", XmlToMetadataParser.convertJsonObjectToLinkedHashMap(rssMetadata));
      }
    } // TESTED (longs converted to string, eg edgar:assistantDirector from
      // "http.www.sec.gov.archives.edgar.usgaap.rss.xml")

    return doc;
  }
예제 #16
0
  private JSONObject convertXMLToJSON(String xmlData) throws JSONException, JAXBException {
    // Unmarshall the xml into a GraphML
    ByteArrayInputStream baiStream = new ByteArrayInputStream(xmlData.getBytes());
    JAXBContext jc = JAXBContext.newInstance(GraphMLUtil.GRAPHML_CLASSES);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    GraphML graphML = (GraphML) unmarshaller.unmarshal(baiStream);

    // eventually check version for compatibility
    s_logger.info("Importing chart version: {}", graphML.getversion());

    Graph graph = graphML.getGraph();

    JSONObject toReturn = new JSONObject(),
        miscData = null,
        columnJSON,
        nodeJSON = null,
        clusterJSON;
    String cachedClusterJSON = null;
    int columnIdx = -1, rowIdx = -1;
    List<List<JSONObject>> allColumns = new ArrayList<List<JSONObject>>();
    List<JSONObject> currColumn, outColumns = new ArrayList<JSONObject>();

    // first, set up the column and misc JSON data contained in the graph
    for (GraphDataXML data : graph.getdata()) {
      if (data.getkey().startsWith("column")) {
        columnJSON = XML.toJSONObject(data.getvalue());
        columnIdx = Integer.parseInt(data.getkey().substring(6));
        while (columnIdx >= outColumns.size()) {
          outColumns.add(new JSONObject());
        }

        outColumns.set(columnIdx, columnJSON);
        allColumns.add(new ArrayList<JSONObject>());
      } else if (data.getkey().equals("miscData")) {
        miscData = XML.toJSONObject(data.getvalue());
      }
    }

    // next, iterate through the graph nodes and place the JSONObject for each into it's proper
    // row/column
    for (GraphNode node : graph.getnode()) {
      for (GraphData data : node.getdata()) { // parse the goodies from each file node
        if (data.getkey().equals("column")) {
          columnIdx = Integer.parseInt(data.getvalue());
        } else if (data.getkey().equals("row")) {
          rowIdx = Integer.parseInt(data.getvalue());
        }
      }

      for (GraphDataXML data : node.getnodedata()) { // parse the goodies from each data node
        if (data.getkey().equals("fileJSON")) {
          nodeJSON = XML.toJSONObject(data.getvalue());
        } else if (data.getkey().equals("clusterJSON")) {
          cachedClusterJSON = data.getvalue();
        }
      }

      if (nodeJSON != null
          && nodeJSON.has("clusterUIObject")
          && !nodeJSON.get("clusterUIObject").toString().equals("null")) {
        clusterJSON = nodeJSON.getJSONObject("clusterUIObject"); // do annoying cleanup
        insertJSONArray(clusterJSON, "children");
        insertJSONArray(clusterJSON.getJSONObject("spec"), "members");
      }

      if (cachedClusterJSON != null) {
        PermitSet permits = new PermitSet();

        try {
          List<String> entityIds = new LinkedList<String>();
          List<FL_Cluster> allClusters = ClusterHelper.listFromJson(cachedClusterJSON);
          ;
          for (FL_Cluster cluster : allClusters) {
            entityIds.addAll(cluster.getMembers());
            for (FL_Property property : cluster.getProperties()) {
              if (!(property.getRange() instanceof FL_SingletonRange)) continue;
              FL_SingletonRange range = (FL_SingletonRange) property.getRange();
              if (!range.getType().equals(FL_PropertyType.STRING)) continue;
              property.setRange(
                  new SingletonRangeHelper(
                      StringEscapeUtils.unescapeXml((String) range.getValue())));
            }
          }

          final ContextReadWrite contextRW =
              contextCache.getReadWrite(nodeJSON.getString("xfId"), permits);
          contextRW.getContext().addClusters(allClusters);
          contextRW
              .getContext()
              .addEntities(entityAccess.getEntities(entityIds, FL_LevelOfDetail.SUMMARY));
          contextRW.setSimplifiedContext(allClusters);
        } catch (IOException e) {
          throw new ResourceException(
              Status.CLIENT_ERROR_BAD_REQUEST, "Exception during cluster cache processing.", e);
        } finally {
          permits.revoke();
        }
      }

      currColumn = allColumns.get(columnIdx);
      while (rowIdx >= currColumn.size()) {
        currColumn.add(new JSONObject());
      }
      currColumn.set(rowIdx, nodeJSON);
    }

    // place the files as children in the outgoing columns array
    for (int i = 0; i < allColumns.size(); i++) {
      columnJSON = outColumns.get(i);
      columnJSON.put("children", new JSONArray(allColumns.get(i)));
    }

    // finally, place the child columns and misc data in the resulting JSON object
    toReturn.put("children", new JSONArray(outColumns));
    for (String dataKey : JSONObject.getNames(miscData)) {
      toReturn.put(dataKey, miscData.get(dataKey));
    }

    return toReturn;
  }