Пример #1
0
  private String jsonArtistes(Map<String, Artiste> artistes) {
    Map<String, Artiste> artistesTrie = new TreeMap<String, Artiste>(artistes);
    JSONObject jsonResultat = new JSONObject();
    JSONArray jsonArtistes = new JSONArray();
    for (String nome : artistesTrie.keySet()) {
      Artiste artiste = artistesTrie.get(nome);
      JSONObject jsonArtiste = new JSONObject();
      jsonArtiste.put("nom", nome);
      JSONArray jsonAlbums = new JSONArray();
      for (Integer annee : artiste.getAlbums().keySet()) {
        Album album = artiste.getAlbums().get(annee);
        JSONObject newAlbum = new JSONObject();
        newAlbum.put("id", album.getId());
        newAlbum.put("titre", album.getTitre());
        newAlbum.put("annee", album.getAnnee());
        newAlbum.put("qte", album.getQuantite());
        jsonAlbums.add(newAlbum);
      }
      jsonArtiste.accumulate("albums", jsonAlbums);
      jsonArtistes.add(jsonArtiste);
    }
    jsonResultat.accumulate("artistes", jsonArtistes);

    return jsonResultat.toString(2);
  }
Пример #2
0
  private static JSONObject recursive(Element parentElement) {
    List<Element> childElements = parentElement.elements();

    JSONObject jsonObject = new JSONObject();
    for (Element childElement : childElements) {

      String attributeValue = childElement.attributeValue(CLASS);
      if (LIST_CLASS_ATTRIBUTE.contains(attributeValue)) {
        List<Element> elements = childElement.elements();

        JSONArray jsonArray = new JSONArray();
        for (Element element : elements) {
          jsonArray.add(recursive(element));
        }
        jsonObject.element(childElement.getName(), jsonArray);
      } else {
        if (!childElement.elements().isEmpty()) {
          JSONObject recursive = recursive(childElement);
          jsonObject.accumulate(childElement.getName(), recursive);
        } else {
          jsonObject.accumulate(childElement.getName(), childElement.getTextTrim());
        }
      }
    }
    return jsonObject;
  }
Пример #3
0
 /**
  * 验证响应 thinkpad dushaofei
  *
  * @param clientData
  * @param signatureData
  * @param keyHandle
  * @return
  */
 @SuppressWarnings({"unchecked", "static-access"})
 @RequestMapping(value = "/v1/test/AuthenticateResponse")
 public ProcessResult<Integer> AuthResponse(@RequestBody AuthenticateResponseData responseData) {
   ProcessResult<Integer> pr = new ProcessResult<Integer>();
   String url = "http://192.168.1.8:8080/FIDOServer/rp/AuthenticateResponse";
   HttpUriRequest post = new HttpPost(url);
   JSONObject jsonP = new JSONObject();
   jsonP.accumulate("clientData", responseData.getClientData());
   jsonP.accumulate("signatureData", responseData.getSignatureData());
   jsonP.accumulate("keyHandle", responseData.getKeyHandle());
   StringEntity entity;
   try {
     entity = new StringEntity(jsonP.toString(), HTTP.UTF_8);
     ((HttpPost) post).setEntity(entity);
     JSONObject jsonObj = getJsonObject(post);
     pr = (ProcessResult<Integer>) jsonObj.toBean(jsonObj, pr.getClass());
     return pr;
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   } catch (IOException io) {
     io.printStackTrace();
   }
   System.out.println(pr.getErrorNum());
   return pr;
 }
  @Override
  public void syncSharedConnectorSettings(
      final long apiKeyId, final SharedConnector sharedConnector) {
    JSONObject jsonSettings = new JSONObject();
    if (sharedConnector.filterJson != null)
      jsonSettings = JSONObject.fromObject(sharedConnector.filterJson);
    // get calendars, add new configs for new calendars...
    // we use the data in the connector settings, which have either just been synched (see
    // UpdateWorker's syncSettings)
    // or were synched  when the connector was last updated; in either cases, we know that the data
    // is up-to-date
    final GoogleCalendarConnectorSettings connectorSettings =
        (GoogleCalendarConnectorSettings) settingsService.getConnectorSettings(apiKeyId);
    final List<CalendarConfig> calendars = connectorSettings.calendars;

    JSONArray sharingSettingsCalendars = new JSONArray();
    if (jsonSettings.has("calendars"))
      sharingSettingsCalendars = jsonSettings.getJSONArray("calendars");
    there:
    for (CalendarConfig calendarConfig : calendars) {
      for (int i = 0; i < sharingSettingsCalendars.size(); i++) {
        JSONObject sharingSettingsCalendar = sharingSettingsCalendars.getJSONObject(i);
        if (sharingSettingsCalendar.getString("id").equals(calendarConfig.id)) continue there;
      }
      JSONObject sharingConfig = new JSONObject();
      sharingConfig.accumulate("id", calendarConfig.id);
      sharingConfig.accumulate("summary", calendarConfig.summary);
      sharingConfig.accumulate("description", calendarConfig.description);
      sharingConfig.accumulate("shared", false);
      sharingSettingsCalendars.add(sharingConfig);
    }

    // and remove configs for deleted notebooks - leave others untouched
    JSONArray settingsToDelete = new JSONArray();
    there:
    for (int i = 0; i < sharingSettingsCalendars.size(); i++) {
      JSONObject sharingSettingsCalendar = sharingSettingsCalendars.getJSONObject(i);
      for (CalendarConfig calendarConfig : calendars) {
        if (sharingSettingsCalendar.getString("id").equals(calendarConfig.id)) continue there;
      }
      settingsToDelete.add(sharingSettingsCalendar);
    }
    for (int i = 0; i < settingsToDelete.size(); i++) {
      JSONObject toDelete = settingsToDelete.getJSONObject(i);
      for (int j = 0; j < sharingSettingsCalendars.size(); j++) {
        if (sharingSettingsCalendars
            .getJSONObject(j)
            .getString("id")
            .equals(toDelete.getString("id"))) {
          sharingSettingsCalendars.remove(j);
        }
      }
    }
    jsonSettings.put("calendars", sharingSettingsCalendars);
    String toPersist = jsonSettings.toString();
    coachingService.setSharedConnectorFilter(sharedConnector.getId(), toPersist);
  }
Пример #5
0
  private JSONObject extractTika(String contents) {

    JSONObject jObj = (JSONObject) JSONSerializer.toJSON(contents);

    if (jObj.containsKey("_source")) {
      JSONObject jObjSource = jObj.getJSONObject("_source");

      if (jObjSource.containsKey("raw_content")) {
        String rawHtml = jObjSource.getString("raw_content");

        ByteArrayInputStream bIs = new ByteArrayInputStream(rawHtml.getBytes());

        Metadata metadata = new Metadata();

        AutoDetectParser adp = new AutoDetectParser();

        ContentHandler handler = new BodyContentHandler(10 * 1024 * 1024);

        try {
          adp.parse(bIs, handler, metadata);

          String[] metadataNames = metadata.names();

          JSONObject jObjMetadata = new JSONObject();

          for (String metadataName : metadataNames) {
            String[] values = metadata.getValues(metadataName);

            JSONArray jArray = new JSONArray();
            for (String mValue : values) {
              jArray.add(mValue);
            }

            jObjMetadata.accumulate(metadataName, jArray);
          }

          // remove empty lines from the text
          String rawTextAdjusted = handler.toString().replaceAll("(?m)^[ \t]*\r?\n", "");

          // detect language
          LanguageIdentifier li = new LanguageIdentifier(rawTextAdjusted);

          jObjSource.accumulate("tikametadata", jObjMetadata);
          jObjSource.accumulate("raw_text", rawTextAdjusted);
          jObjSource.accumulate("rawtextdetectedlanguage", li.getLanguage());

        } catch (Exception e) {
          LOG.error("Error:", e);
          ;
        }
      }
    }
    return jObj;
  }
 private static String checkUser(String sessionId, String site) {
   synchronized ("") {
     MemcachedCli cli = MemcachedCli.getInstance();
     Object memCachedJsonData = cli.get(CACHED_KEY_SESSION_ID + sessionId);
     JSONObject jsonData =
         JSONObject.fromObject(memCachedJsonData == null ? "{}" : memCachedJsonData);
     int size = jsonData.size();
     if (size == 0) {
       jsonData.accumulate("exist", "false");
     } else {
       jsonData.accumulate("exist", "true");
     }
     return jsonData.toString();
   }
 }
Пример #7
0
 @Override
 protected synchronized JSON data() {
   JSONArray r = new JSONArray();
   for (User u : modified) {
     UserInfo i = users.get(u);
     JSONObject entry =
         new JSONObject()
             .accumulate("id", u.getId())
             .accumulate("fullName", u.getFullName())
             .accumulate("url", u.getUrl())
             .accumulate(
                 "avatar",
                 i.avatar != null
                     ? i.avatar
                     : Stapler.getCurrentRequest().getContextPath()
                         + Functions.getResourcePath()
                         + "/images/"
                         + iconSize
                         + "/user.png")
             .accumulate("timeSortKey", i.getTimeSortKey())
             .accumulate("lastChangeTimeString", i.getLastChangeTimeString());
     AbstractProject<?, ?> p = i.getProject();
     if (p != null) {
       entry
           .accumulate("projectUrl", p.getUrl())
           .accumulate("projectFullDisplayName", p.getFullDisplayName());
     }
     r.add(entry);
   }
   modified.clear();
   return r;
 }
Пример #8
0
  @RequestMapping(value = "/teacher/manageTeacher", headers = "Accept=application/json")
  @ResponseBody
  public String manageTeachers() {
    List<Teacher> result = homeService.findallTeachers();
    JSONObject json = new JSONObject();
    json.put("Result", "OK");

    for (int i = 0; i < result.size(); i++) {
      System.out.println("Value: " + i + " - Person ID: " + result.get(i).getUserId());
      JSONObject teacherObj = new JSONObject();
      teacherObj.put("userId", result.get(i).getUserId());
      teacherObj.put("fname", result.get(i).getFname());
      teacherObj.put("lname", result.get(i).getLname());
      teacherObj.put("mname", result.get(i).getMname());
      teacherObj.put("address", result.get(i).getAddress());
      teacherObj.put("bday", result.get(i).getBday().toString());
      teacherObj.put("gender", result.get(i).getGender());
      teacherObj.put("email", result.get(i).getEmail());
      json.accumulate("Records", teacherObj);
    }

    System.out.println("JSON: " + json.toString(2));
    String jsonString = json.toString();
    return jsonString;
  }
 private void addJsonAnnotations(ModelAndView mav, String style, boolean prefix) {
   if (prefix) {
     mav.addObject("mapPrefix", "map");
     mav.addObject("mimetype", "application/x-javascript");
   } else {
     mav.addObject("mimetype", "application/json");
   }
   List<ConceptAnnotation> annotations =
       (List<ConceptAnnotation>) mav.getModel().get("annotations");
   if (annotations != null) {
     JSONArray mappings = new JSONArray();
     for (ConceptAnnotation annotation : annotations) {
       JSONObject mapping = new JSONObject();
       mapping.accumulate("id", String.valueOf(annotation.getOid()));
       mapping.accumulate("start", String.valueOf(annotation.getBegin()));
       mapping.accumulate("end", String.valueOf(annotation.getEnd()));
       mapping.accumulate("pname", annotation.getPname());
       mapping.accumulate("group", annotation.getStygroup());
       mapping.accumulate("codes", StringUtils.replace(annotation.getStycodes(), "\"", ""));
       mapping.accumulate("text", annotation.getCoveredText());
       mappings.put(mapping);
     }
     mav.addObject(
         "stringAnnotations", "pretty".equals(style) ? mappings.toString(2) : mappings.toString());
   }
 }
Пример #10
0
  private JSONObject creerJsonMap(Map<String, Integer> var) {
    JSONObject jsonActivites = new JSONObject();

    for (Map.Entry<String, Integer> entry : var.entrySet()) {
      jsonActivites.accumulate(entry.getKey(), entry.getValue());
    }

    return jsonActivites;
  }
Пример #11
0
 public String queryById() throws Exception {
   System.out.println(">>>>>>>>>id=" + this.getId());
   Student student = ss.queryById(this.getId());
   JSONObject json = new JSONObject();
   json.accumulate("student", student);
   System.out.println(">>>>>>>json=" + json);
   HttpServletResponse response = ServletActionContext.getResponse();
   response.setContentType("text/x-json;charset=UTF-8");
   response.setHeader("Cache-Control", "no-cache");
   response.getWriter().print(json.toString());
   return null;
 }
Пример #12
0
 public String queryAll() throws Exception {
   System.out.println("********queryAll********");
   List<Student> list = ss.queryAll();
   JSONObject json = new JSONObject();
   json.accumulate("Rows", list);
   System.out.println(">>>>>>>>>>json" + json);
   HttpServletResponse response = ServletActionContext.getResponse();
   response.setContentType("text/x-json;charset=UTF-8");
   response.setHeader("Cache-Control", "no-cache");
   response.getWriter().print(json.toString());
   return null;
 }
Пример #13
0
 @POST
 @Path("/renew/{apiKeyId}")
 @Produces({MediaType.APPLICATION_JSON})
 public String renewConnectorTokens(@PathParam("apiKeyId") long apiKeyId) throws Exception {
   final ApiKey apiKey = guestService.getApiKey(apiKeyId);
   ConnectorInfo connectorInfo = sysService.getConnectorInfo(apiKey.getConnector().getName());
   JSONObject renewInfo = new JSONObject();
   final String renewTokensUrlTemplate = connectorInfo.renewTokensUrlTemplate;
   final String renewTokensUrl = String.format(renewTokensUrlTemplate, apiKey.getId());
   renewInfo.accumulate("redirectTo", env.get("homeBaseUrl") + renewTokensUrl);
   return renewInfo.toString();
 }
Пример #14
0
  /**
   * Like {@link #doInstallNecessaryPlugins(StaplerRequest)} but only checks if everything is
   * installed or if some plugins need updates or installation.
   *
   * <p>This method runs without side-effect. I'm still requiring the ADMINISTER permission since
   * XML file can contain various external references and we don't configure parsers properly
   * against that.
   *
   * @since 1.483
   */
  @RequirePOST
  public JSONArray doPrevalidateConfig(StaplerRequest req) throws IOException {
    Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);

    JSONArray response = new JSONArray();

    for (Map.Entry<String, VersionNumber> p :
        parseRequestedPlugins(req.getInputStream()).entrySet()) {
      PluginWrapper pw = getPlugin(p.getKey());
      JSONObject j =
          new JSONObject()
              .accumulate("name", p.getKey())
              .accumulate("version", p.getValue().toString());
      if (pw == null) { // install new
        response.add(j.accumulate("mode", "missing"));
      } else if (pw.isOlderThan(p.getValue())) { // upgrade
        response.add(j.accumulate("mode", "old"));
      } // else already good
    }

    return response;
  }
 /** 缓存session 和登录用户信息绑定一起 */
 public static void addUserToSession(JSONObject json) {
   synchronized ("") {
     MemcachedCli cli = MemcachedCli.getInstance();
     Object memCachedJsonData = cli.get(CACHED_KEY_SESSION_ID + json.getString("sessionId"));
     JSONObject jsonData =
         JSONObject.fromObject(memCachedJsonData == null ? "{}" : memCachedJsonData);
     int size = jsonData.size();
     if (size == 0) {
       jsonData.accumulate("site", json.getString("site"));
     } else {
       // 判断当前登录站点
       if (jsonData.getString("site").indexOf(json.getString("site")) == -1) {
         String site = jsonData.getString("site") + "," + json.getString("site");
         jsonData.remove("site");
         jsonData.accumulate("site", site);
       }
     }
     jsonData.put("name", json.getString("name"));
     jsonData.put("passwd", json.getString("passwd"));
     jsonData.put("sessionId", json.getString("sessionId"));
     jsonData.put("lastTime", json.getString("lastTime"));
     cli.set(
         CACHED_KEY_SESSION_ID + json.getString("sessionId"),
         jsonData.toString(),
         new java.util.Date(System.currentTimeMillis() + 60 * 1000 * 120));
     // ------------------------------------------------------------
     Map<String, String> map = new HashMap<String, String>();
     map.put("sessionId", json.getString("sessionId"));
     map.put("siteSessionId", json.getString("siteSessionId"));
     map.put("site", json.getString("site"));
     cli.set(
         CACHED_KEY_SESSION_SITE + json.getString("siteSessionId"),
         JSONObject.fromObject(map).toString(),
         new java.util.Date(System.currentTimeMillis() + 60 * 1000 * 120));
     // ------------------------------------------------------------
   }
 }
Пример #16
0
 /**
  * 注册响应 thinkpad dushaofei
  *
  * @param clientData
  * @param registData
  * @param address
  * @return
  * @throws UnsupportedEncodingException
  */
 @SuppressWarnings({"unchecked", "static-access"})
 @RequestMapping(value = "/v1/RegisterReponse")
 @ResponseBody
 public ProcessResult<Integer> RegistResponse(
     @RequestBody RegisterResponseData responseData, HttpServletRequest address)
     throws UnsupportedEncodingException {
   ProcessResult<Integer> pr = new ProcessResult<Integer>();
   String url = "http://192.168.1.8:8080/FIDOServer/rp/RegisterResponse";
   HttpUriRequest request = new HttpPost(url);
   JSONObject obj = new JSONObject();
   obj.accumulate("clientData", responseData.getClientData());
   obj.accumulate("registrationData", responseData.getRegistrationData());
   StringEntity entity = new StringEntity(obj.toString(), HTTP.UTF_8);
   ((HttpPost) request).setEntity(entity);
   try {
     JSONObject jsonObj = getJsonObject(request);
     pr = (ProcessResult<Integer>) jsonObj.toBean(jsonObj, pr.getClass());
   } catch (ClientProtocolException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return pr;
 }
Пример #17
0
  @SuppressWarnings("empty-statement")
  public static void main(String[] args) throws Exception {
    String json = utilities.FileReader.loadFileIntoString("json/catalogue.json");
    JSONArray lvrs = JSONArray.fromObject(json);

    // Build the livre list to add in the order
    JSONArray livres = new JSONArray();
    double total = 0.0;
    for (int i = 0; i < lvrs.size(); i++) {
      JSONObject livre = lvrs.getJSONObject(i);
      if (livre.getDouble("prix") < 100.0) {
        total += livre.getDouble("prix");
        livres.add(livre);
      }
    }

    // Format the price
    DecimalFormat format = new DecimalFormat();
    format.setMinimumFractionDigits(2);
    String totalStr = format.format(total);

    // get current date time with Date()
    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Date date = new Date();
    String dateOrder = dateFormat.format(date);
    ;
    // Build the order
    JSONObject order = new JSONObject();
    order.accumulate("id", "1321033823");
    order.accumulate("total", totalStr);
    order.accumulate("date", dateOrder);
    order.accumulate("validation", true);
    order.accumulate("livres", livres);

    System.out.println(order);
  }
Пример #18
0
  protected JSONObject creerJsonStatistique() {
    JSONObject jsonStatistique = new JSONObject();
    jsonStatistique.accumulate("declaration_completes", nbDeclarationsCompletes);
    jsonStatistique.accumulate(
        "declaration_incompletes_ou_invalide", nbDeclarationsIncompletesOuInvalide);
    jsonStatistique.accumulate("declaration_hommes", nbDeclarationsHommes);
    jsonStatistique.accumulate("declaration_femmes", nbDeclarationsFemmes);
    jsonStatistique.accumulate("declaration_sexe_inconnu", nbDeclarationsSexeInconnu);

    jsonStatistique.accumulate("activites", creerJsonMap(nbActivites));
    jsonStatistique.accumulate(
        "declaratiion_ordre_valide_complete", creerJsonMap(nbDeclarationsOrdreComplet));
    jsonStatistique.accumulate(
        "declaratiion_ordre_valide_incomplete", creerJsonMap(nbDeclarationsOrdreIncomplet));
    jsonStatistique.accumulate("declaration_numero_invalide", nbDeclarationsNumeroInvalide);
    return jsonStatistique;
  }
  /** Tests the transformation. */
  @Test
  public void transformTestMatchingId() {
    final Long entityId = 10L;
    final String entityAcctName = "acctName";

    final JSONObject jsonReq = new JSONObject();
    jsonReq.accumulate("joinedGroups", entityAcctName);

    final List<Long> followedGroups = Arrays.asList(1L, 2L, 3L);

    DomainGroupModelView group1 = new DomainGroupModelView();
    group1.setEntityId(1L);
    group1.setStreamId(4L);

    DomainGroupModelView group2 = new DomainGroupModelView();
    group2.setEntityId(2L);
    group2.setStreamId(5L);

    DomainGroupModelView group3 = new DomainGroupModelView();
    group3.setEntityId(3L);
    group3.setStreamId(6L);

    final List<DomainGroupModelView> groups = Arrays.asList(group1, group2, group3);

    context.checking(
        new Expectations() {
          {
            oneOf(getPersonIdByAccountId).execute(entityAcctName);
            will(returnValue(entityId));

            oneOf(followeGroupsMapper).execute(entityId);
            will(returnValue(followedGroups));

            oneOf(groupMapper).execute(followedGroups);
            will(returnValue(groups));
          }
        });

    Assert.assertEquals(
        Arrays.asList(group1.getStreamId(), group2.getStreamId(), group3.getStreamId()),
        sut.transform(jsonReq, entityId));

    context.assertIsSatisfied();
  }
  /** Tests the transformation. */
  @Test
  public void transformTestNotMatchingId() {
    final Long entityId = 10L;
    final String entityAcctName = "acctName";

    final JSONObject jsonReq = new JSONObject();
    jsonReq.accumulate("joinedGroups", entityAcctName);

    context.checking(
        new Expectations() {
          {
            oneOf(getPersonIdByAccountId).execute(entityAcctName);
            will(returnValue(entityId - 1L));
          }
        });

    List<Long> groups = (List<Long>) sut.transform(jsonReq, entityId);
    Assert.assertEquals(0, groups.size());

    context.assertIsSatisfied();
  }
Пример #21
0
  /**
   * load quota and current using space
   *
   * @return JSON
   */
  private JSON loadQuota() {
    MailAcctConfigInfo config = this.configBo.findByUser();
    if (config == null) return FAILURE_JSON;

    String smtpDef = config.getDefaultSMTP();
    if (!StringService.hasLength(smtpDef)) {
      return FAILURE_JSON;
    }

    // get email account from ticket
    String email = MailService.getUsername(smtpDef);

    // find detail LDAP mail account
    LdapMailAccount ldapMailAccount = mailAccountManager.findByName(email);

    if (ldapMailAccount == null) return FAILURE_JSON;

    // get quota
    int quota = 0;
    try {
      quota = Integer.parseInt(ldapMailAccount.getQuota());
    } catch (NumberFormatException ex) {
      logger.warning("Error to parse quota to integer", ex);
      return FAILURE_JSON;
    }

    // check quota equal zero
    if (quota == 0) return FAILURE_JSON;

    long spaceUsed = this.headerBo.getCurrentUsing(getCode(), smtpDef);

    // create JSON to return result
    JSONObject object = new JSONObject();
    object.accumulate(FIELD_QUOTA, quota).accumulate(FIELD_USED, spaceUsed);

    return object;
  }
Пример #22
0
 // 获得参数类型下拉框值
 public void gainComboboxData() {
   JSONObject json = new JSONObject();
   json.accumulate("rows", paramService.findByList(null));
   sendDataToView(json.toString());
 }
Пример #23
0
  @SuppressWarnings({"unchecked", "static-access"})
  public static void main(String[] args) throws ClientProtocolException, IOException {
    //		ProcessResult<RegisterRequestData> pr = new ProcessResult<RegisterRequestData>();
    //		String url ="http://192.168.1.8:8080/FIDOServer/rp/RegisterRequest/"+"shaofei";
    //		HttpGet get = new HttpGet(url);
    //		try {
    //			JSONObject json = getJsonObject(get);
    //			pr =   (ProcessResult<RegisterRequestData>) JSONObject.toBean(json,  pr.getClass());
    //
    //	System.out.println(pr.getErrorNum()+"+"+pr.getErrorMessage()+"+"+pr.getSuccess()+pr.getDetail());
    //		}  catch (IOException e) {
    //			e.printStackTrace();
    //		}
    // 注册响应
    //		ProcessResult<Integer> pr = new ProcessResult<Integer>();
    //		String clientData="";
    //		String registData = "";
    //		String url = "http://192.168.1.8:8080/FIDOServer/rp/RegisterResponse";
    //		HttpUriRequest request = new HttpPost(url);
    //		clientData =
    // "eyJjaGFsbGVuZ2UiOiIwXzI1VjJXMFRyWkdfNy1ZS0tBZXNiOUZodTBRWWJHdUc3WUItZ1ZQa29FIiwib3JpZ2luIjoiaHR0cDovL21lLmlkc21hbmFnZXIuY29tL0ZJRE9TZXJ2ZXIiLCJ0eXAiOiJuYXZpZ2F0b3IuaWQuZmluaXNoRW5yb2xsbWVudCJ9";
    //		registData =
    // "BQTVcBof2jtG-Ajk-uQA9n4QYP59--mK09QGUkWJDyeDPfNTwbLaOtk2VVDB_bOWTNWQh-QEowyplZUYw-FH9vqbAAAAAAAAAAAAAAAAAAA\u003d";
    //		JSONObject obj = new JSONObject();
    //		obj.accumulate("clientData", clientData);
    //		obj.accumulate("registrationData", registData);
    //		StringEntity entity = new StringEntity(obj.toString(),HTTP.UTF_8);
    //		((HttpPost)request).setEntity(entity);
    //		try {
    //			JSONObject jsonObj = getJsonObject(request);
    //			pr = (ProcessResult<Integer>) jsonObj.toBean(jsonObj,pr.getClass());
    //		} catch (ClientProtocolException e) {
    //			e.printStackTrace();
    //		} catch (IOException e) {
    //			e.printStackTrace();
    //		}
    // 验证请求

    //		ProcessResult<AuthenticateRequestData> pr = new ProcessResult<AuthenticateRequestData>();
    //		String url = "http://192.168.1.8:8080/FIDOServer/rp/AuthenticateRequest/"+"yalin";
    //		String backMessager = "";
    //		HttpGet get = new HttpGet(url);
    //		try {
    //			JSONObject jsonObj = getJsonObject(get);
    //			pr = (ProcessResult<AuthenticateRequestData>) jsonObj.toBean(jsonObj, pr.getClass());
    //
    //			System.out.println(pr.getDetail());
    //		} catch (ClientProtocolException e) {
    //
    //			e.printStackTrace();
    //		} catch (IOException e) {
    //
    //			e.printStackTrace();
    //		}
    // 验证注册
    String clientData =
        "eyJjaGFsbGVuZ2UiOiJ4YjMxeG1DQ1ZNbDVpcTN1SDNFR1JkQzlrWEZ2YmJZaHY1ZTN4LW1VQ3FzIiwib3JpZ2luIjoiaHR0cDovLzE5Mi4xNjguMS4xMTYvRklET1NlcnZlciIsInR5cCI6Im5hdmlnYXRvci5pZC5nZXRBc3NlcnRpb24ifQ";
    String signatureData =
        "AQAAAAEwRgIhAODp8v3pEdKMQ4tpzalxlB8L5_vBOPtB-H8CjIfitCbaAiEA5FKoaVf4VaWeZWNftYDuKPBFOqCxOSAFE1QoTMZsshw=";
    String keyHandle =
        "iqSj1IaVHRx3zIms7w55SipzqIkhLlmoiOQh2xILekWhY2ko6uJp1KSaZ5TYkEyPBXtT6RElSD9TP-mi9IADyy6mJhc7vpxEHrSyn24KXGdfnBCNrk2g3Mt1Ph8-FzlyNaDYASVVDZwQqrRCPwOQhnAS_rRGacAfOvmiciAWZmhKmX2AamRrFHfkXh4ETktBKyqtbk0U7jkYgOp57fJAIdwiQYRd_x8DZGtfPAsBhx7sbyM15ZpONg";
    ProcessResult<Integer> pr = new ProcessResult<Integer>();
    String url = "http://192.168.1.8:8080/FIDOServer/rp/AuthenticateResponse";
    HttpUriRequest post = new HttpPost(url);
    JSONObject jsonP = new JSONObject();
    jsonP.accumulate("clientData", clientData);
    jsonP.accumulate("signatureData", signatureData);
    jsonP.accumulate("keyHandle", keyHandle);
    StringEntity entity = new StringEntity(jsonP.toString(), HTTP.UTF_8);
    ((HttpPost) post).setEntity(entity);
    JSONObject jsonObj = getJsonObject(post);
    pr = (ProcessResult<Integer>) jsonObj.toBean(jsonObj, pr.getClass());
    System.out.println(pr.getErrorNum());
  }
Пример #24
0
  @GET
  @Path("/installed")
  @Produces({MediaType.APPLICATION_JSON})
  public String getInstalledConnectors() {
    Guest guest = AuthHelper.getGuest();
    // If no guest is logged in, return empty array
    if (guest == null) return "[]";
    ResourceBundle res = ResourceBundle.getBundle("messages/connectors");
    try {
      List<ConnectorInfo> connectors = sysService.getConnectors();
      JSONArray connectorsArray = new JSONArray();
      for (int i = 0; i < connectors.size(); i++) {
        final ConnectorInfo connectorInfo = connectors.get(i);
        final Connector api = connectorInfo.getApi();
        if (api == null) {
          StringBuilder sb =
              new StringBuilder(
                  "module=API component=connectorStore action=getInstalledConnectors ");
          logger.warn("message=\"null connector for " + connectorInfo.getName() + "\"");
          continue;
        }
        if (!guestService.hasApiKey(guest.getId(), api)
            || api.getName().equals("facebook") /*HACK*/) {
          connectors.remove(i--);
        } else {
          ConnectorInfo connector = connectorInfo;
          JSONObject connectorJson = new JSONObject();
          Connector conn = Connector.fromValue(connector.api);
          ApiKey apiKey = guestService.getApiKey(guest.getId(), conn);

          connectorJson.accumulate("prettyName", conn.prettyName());
          List<String> facetTypes = new ArrayList<String>();
          ObjectType[] objTypes = conn.objectTypes();
          if (objTypes != null) {
            for (ObjectType obj : objTypes) {
              facetTypes.add(connector.connectorName + "-" + obj.getName());
            }
          }
          connectorJson.accumulate("facetTypes", facetTypes);
          connectorJson.accumulate(
              "status", apiKey.status != null ? apiKey.status.toString() : "NA");
          connectorJson.accumulate("name", connector.name);
          connectorJson.accumulate("connectUrl", connector.connectUrl);
          connectorJson.accumulate("image", connector.image);
          connectorJson.accumulate("connectorName", connector.connectorName);
          connectorJson.accumulate("enabled", connector.enabled);
          connectorJson.accumulate("manageable", connector.manageable);
          connectorJson.accumulate("text", connector.text);
          connectorJson.accumulate("api", connector.api);
          connectorJson.accumulate("apiKeyId", apiKey.getId());
          connectorJson.accumulate(
              "lastSync", connector.supportsSync ? getLastSync(apiKey) : Long.MAX_VALUE);
          connectorJson.accumulate("latestData", getLatestData(apiKey));
          final String auditTrail = checkForErrors(apiKey);
          connectorJson.accumulate("errors", auditTrail != null);
          connectorJson.accumulate("auditTrail", auditTrail != null ? auditTrail : "");
          connectorJson.accumulate("syncing", checkIfSyncInProgress(guest.getId(), conn));
          connectorJson.accumulate(
              "channels", settingsService.getChannelsForConnector(guest.getId(), conn));
          connectorJson.accumulate("sticky", connector.connectorName.equals("fluxtream_capture"));
          connectorJson.accumulate("supportsRenewToken", connector.supportsRenewTokens);
          connectorJson.accumulate("supportsSync", connector.supportsSync);
          connectorJson.accumulate("supportsFileUpload", connector.supportsFileUpload);
          connectorJson.accumulate("prettyName", conn.prettyName());
          final String uploadMessageKey = conn.getName() + ".upload";
          if (res.containsKey(uploadMessageKey)) {
            final String uploadMessage = res.getString(uploadMessageKey);
            connectorJson.accumulate("uploadMessage", uploadMessage);
          }
          connectorsArray.add(connectorJson);
        }
      }
      StringBuilder sb =
          new StringBuilder("module=API component=connectorStore action=getInstalledConnectors")
              .append(" guestId=")
              .append(guest.getId());
      logger.info(sb.toString());
      return connectorsArray.toString();
    } catch (Exception e) {
      StringBuilder sb =
          new StringBuilder("module=API component=connectorStore action=getInstalledConnectors")
              .append(" guestId=")
              .append(guest.getId())
              .append(" stackTrace=<![CDATA[")
              .append(Utils.stackTrace(e))
              .append("]]>");
      System.out.println(sb.toString());
      logger.warn(sb.toString());
      return gson.toJson(
          new StatusModel(false, "Failed to get installed connectors: " + e.getMessage()));
    }
  }