public ImportContext context() throws IOException {
    ImportContext context = null;
    if (json.has("import")) {
      context = new ImportContext();

      json = json.getJSONObject("import");
      if (json.has("id")) {
        context.setId(json.getLong("id"));
      }
      if (json.has("state")) {
        context.setState(State.valueOf(json.getString("state")));
      }
      if (json.has("user")) {
        context.setUser(json.getString("user"));
      }
      if (json.has("archive")) {
        context.setArchive(json.getBoolean("archive"));
      }
      if (json.has("targetWorkspace")) {
        context.setTargetWorkspace(
            fromJSON(json.getJSONObject("targetWorkspace"), WorkspaceInfo.class));
      }
      if (json.has("targetStore")) {
        context.setTargetStore(fromJSON(json.getJSONObject("targetStore"), StoreInfo.class));
      }
      if (json.has("data")) {
        context.setData(data(json.getJSONObject("data")));
      }
    }
    return context;
  }
 @Test
 public void testCreateAsJSON() throws Exception {
   GeoServer geoServer = getGeoServer();
   geoServer.remove(geoServer.getSettings(geoServer.getCatalog().getWorkspaceByName("sf")));
   String json =
       "{'settings':{'workspace':{'name':'sf'},"
           + "'contact':{'addressCity':'Alexandria','addressCountry':'Egypt','addressType':'Work',"
           + "'contactEmail':'*****@*****.**','contactOrganization':'The ancient geographes INC',"
           + "'contactPerson':'Claudius Ptolomaeus','contactPosition':'Chief geographer'},"
           + "'charset':'UTF-8','numDecimals':10,'onlineResource':'http://geoserver.org',"
           + "'proxyBaseUrl':'http://proxy.url','verbose':false,'verboseExceptions':'true'}}";
   MockHttpServletResponse response =
       putAsServletResponse("/rest/workspaces/sf/settings", json, "text/json");
   assertEquals(200, response.getStatusCode());
   JSON jsonMod = getAsJSON("/rest/workspaces/sf/settings.json");
   JSONObject jsonObject = (JSONObject) jsonMod;
   assertNotNull(jsonObject);
   JSONObject settings = jsonObject.getJSONObject("settings");
   assertNotNull(settings);
   JSONObject workspace = settings.getJSONObject("workspace");
   assertNotNull(workspace);
   assertEquals("sf", workspace.get("name"));
   assertEquals("10", settings.get("numDecimals").toString().trim());
   assertEquals("http://geoserver.org", settings.get("onlineResource"));
   assertEquals("http://proxy.url", settings.get("proxyBaseUrl"));
   JSONObject contact = settings.getJSONObject("contact");
   assertEquals("Claudius Ptolomaeus", contact.get("contactPerson"));
   assertEquals("The ancient geographes INC", contact.get("contactOrganization"));
   assertEquals("Work", contact.get("addressType"));
   assertEquals("*****@*****.**", contact.get("contactEmail"));
 }
  @Test
  public void testPutAsJSON() throws Exception {
    String inputJson =
        "{'settings':{'workspace':{'name':'sf'},"
            + "'contact':{'addressCity':'Cairo','addressCountry':'Egypt','addressType':'Work',"
            + "'contactEmail':'*****@*****.**','contactOrganization':'The ancient geographes INC',"
            + "'contactPerson':'Claudius Ptolomaeus','contactPosition':'Chief geographer'},"
            + "'charset':'UTF-8','numDecimals':8,'onlineResource':'http://geoserver2.org',"
            + "'proxyBaseUrl':'http://proxy2.url','verbose':true,'verboseExceptions':'true'}}";

    MockHttpServletResponse response =
        putAsServletResponse("/rest/workspaces/sf/settings", inputJson, "text/json");
    assertEquals(200, response.getStatusCode());
    JSON jsonMod = getAsJSON("/rest/workspaces/sf/settings.json");
    JSONObject jsonObject = (JSONObject) jsonMod;
    assertNotNull(jsonObject);
    JSONObject settings = jsonObject.getJSONObject("settings");
    assertNotNull(settings);
    JSONObject workspace = settings.getJSONObject("workspace");
    assertNotNull(workspace);
    assertEquals("sf", workspace.get("name"));
    assertEquals("8", settings.get("numDecimals").toString().trim());
    assertEquals("http://geoserver2.org", settings.get("onlineResource"));
    assertEquals("http://proxy2.url", settings.get("proxyBaseUrl"));
    assertEquals("true", settings.get("verbose").toString().trim());
    assertEquals("true", settings.get("verboseExceptions").toString().trim());
    JSONObject contact = settings.getJSONObject("contact");
    assertNotNull(contact);
    assertEquals("Claudius Ptolomaeus", contact.get("contactPerson"));
    assertEquals("Cairo", contact.get("addressCity"));
  }
  /**
   * Accept a POST request.
   *
   * @param entity the representation of a new entry.
   * @throws ResourceException thrown when unable to accept representation.
   */
  @Override
  public void acceptRepresentation(final Representation entity) throws ResourceException {
    String json;
    try {
      json = entity.getText();
      log.debug("RecommendationsCollectionResource POST" + json);

      JSONObject jsonReco = JSONObject.fromObject(json);
      JSONObject jsonAuthor = jsonReco.getJSONObject(AUTHOR_KEY);
      JSONObject jsonSubject = jsonReco.getJSONObject(SUBJECT_KEY);
      Recommendation recommendation =
          new Recommendation(
              jsonSubject.getString(ID_KEY),
              jsonAuthor.getString(ID_KEY),
              jsonReco.getString(TEXT_KEY));

      getRecommendationMapper().insert(recommendation);

      Map<String, Person> people = getPeopleInfoForRecommendations(recommendation);

      JSONObject recoJSON =
          convertRecoToJSON(
              recommendation,
              people.get(recommendation.getAuthorOpenSocialId()),
              people.get(recommendation.getSubjectOpenSocialId()));

      getAdaptedResponse().setEntity(recoJSON.toString(), MediaType.APPLICATION_JSON);
    } catch (IOException e) {
      log.error("POST to RecommendationsCollection failed", e);
      throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
    }

    log.debug("RecommendationsCollectionResource POST " + entity.toString());
  }
  /** Tests {@link ExternalResource#toJson()}. */
  @PrepareForTest(Hudson.class)
  @Test
  public void testToJson() {
    Hudson hudson = MockUtils.mockHudson();
    MockUtils.mockMetadataValueDescriptors(hudson);

    String name = "name";
    String description = "description";
    String id = "id";
    ExternalResource resource =
        new ExternalResource(name, description, id, true, new LinkedList<MetadataValue>());
    String me = "me";
    resource.setReserved(
        new StashInfo(
            StashInfo.StashType.INTERNAL, me, new Lease(Calendar.getInstance(), "iso"), "key"));
    TreeStructureUtil.addValue(resource, "value", "descript", "some", "path");

    JSONObject json = resource.toJson();
    assertEquals(name, json.getString(JsonUtils.NAME));
    assertEquals(id, json.getString(JSON_ATTR_ID));
    assertTrue(json.getBoolean(JSON_ATTR_ENABLED));
    assertTrue(json.getJSONObject(JSON_ATTR_LOCKED).isNullObject());
    JSONObject reserved = json.getJSONObject(JSON_ATTR_RESERVED);
    assertNotNull(reserved);
    assertEquals(StashInfo.StashType.INTERNAL.name(), reserved.getString(Constants.JSON_ATTR_TYPE));
    assertEquals(me, reserved.getString(Constants.JSON_ATTR_STASHED_BY));
    assertEquals(1, json.getJSONArray(JsonUtils.CHILDREN).size());
  }
Example #6
0
  /**
   * Parses a JSONObject into its appropriate ViewVariable implementation
   *
   * @param obj
   * @return
   */
  private static AbstractViewVariable parseJSONRecursive(JSONObject obj) {

    if (obj == null || obj.isNullObject()) throw new NullArgumentException("obj");

    String type = obj.getString("type");
    if (type == null) throw new IllegalArgumentException("Object missing type " + obj);

    // Parse a SimpleAxis
    if (type.equals(SimpleAxis.TYPE_STRING)) {
      SimpleAxis axis =
          new SimpleAxis(
              attemptGetString(obj, "name"),
              attemptGetString(obj, "dataType"),
              attemptGetString(obj, "units"),
              null,
              null);

      JSONObject dimensionBounds = obj.getJSONObject("dimensionBounds");
      JSONObject valueBounds = obj.getJSONObject("valueBounds");

      if (dimensionBounds != null && !dimensionBounds.isNullObject()) {
        axis.setDimensionBounds(
            new SimpleBounds(dimensionBounds.getDouble("from"), dimensionBounds.getDouble("to")));
      }

      if (valueBounds != null && !valueBounds.isNullObject()) {
        axis.setValueBounds(
            new SimpleBounds(valueBounds.getDouble("from"), valueBounds.getDouble("to")));
      }

      return axis;

      // Parse a SimpleGrid
    } else if (type.equals(SimpleGrid.TYPE_STRING)) {
      JSONArray axes = obj.getJSONArray("axes");
      SimpleGrid grid =
          new SimpleGrid(
              attemptGetString(obj, "name"),
              attemptGetString(obj, "dataType"),
              attemptGetString(obj, "units"),
              null);
      List<AbstractViewVariable> childAxes = new ArrayList<>();

      for (int i = 0; i < axes.size(); i++) {
        AbstractViewVariable var = parseJSONRecursive(axes.getJSONObject(i));
        if (var != null) childAxes.add(var);
      }

      if (childAxes.size() > 0) {
        grid.setAxes(childAxes.toArray(new AbstractViewVariable[childAxes.size()]));
        return grid;
      } else {
        return null;
      }

    } else {
      throw new IllegalArgumentException("Unable to parse type " + type);
    }
  }
Example #7
0
  public void testFileUploadWithConfigChange() throws Exception {
    int i = postNewImport();
    int t = postNewTaskAsMultiPartForm(i, "shape/archsites_no_crs.zip");

    JSONObject task = getTask(i, t);
    assertEquals("INCOMPLETE", task.getString("state"));

    JSONObject item = getItem(i, t, 0);
    assertEquals("NO_CRS", item.getString("state"));

    String json =
        "{"
            + "\"item\": {"
            + "\"resource\": {"
            + "\"featureType\": {"
            + "\"srs\": \"EPSG:4326\""
            + "}"
            + "}"
            + "}"
            + "}";
    putItem(i, t, 0, json);

    item = getItem(i, t, 0);
    assertEquals("READY", item.getString("state"));
    assertEquals(
        "gs_archsites",
        item.getJSONObject("layer")
            .getJSONObject("layer")
            .getJSONObject("defaultStyle")
            .getString("name"));
    json =
        "{"
            + "\"item\": {"
            + "\"layer\": {"
            + "\"layer\": {"
            + "\"defaultStyle\": {"
            + "\"name\": \"point\""
            + "}"
            + "}"
            + "}"
            + "}"
            + "}";
    putItem(i, t, 0, json);

    item = getItem(i, t, 0);

    assertEquals("READY", item.getString("state"));
    assertEquals(
        "point",
        item.getJSONObject("layer")
            .getJSONObject("layer")
            .getJSONObject("defaultStyle")
            .getString("name"));

    postImport(i);
    runChecks("archsites");
  }
    @Override
    public JobProperty<?> newInstance(StaplerRequest req, JSONObject formData)
        throws FormException {
      if (formData.getJSONObject("track-git") == null
          || formData.getJSONObject("track-git").isNullObject()) {
        return null;
      }

      return super.newInstance(req, formData.getJSONObject("track-git"));
    }
 /**
  * Takes a JSON object and fills its internal data-structure.
  *
  * @param json the JSON Object.
  */
 public void fromJson(JSONObject json) {
   super.fromJson(json);
   if (json.containsKey(CHANGE)) {
     change = new Change(json.getJSONObject(CHANGE));
   }
   if (json.containsKey(PATCH_SET)) {
     patchSet = new PatchSet(json.getJSONObject(PATCH_SET));
   } else if (json.containsKey(PATCHSET)) {
     patchSet = new PatchSet(json.getJSONObject(PATCHSET));
   }
 }
 @Override
 public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
   JSONObject hookMode = json.getJSONObject("hookMode");
   manageHook = "auto".equals(hookMode.getString("value"));
   JSONObject o = hookMode.getJSONObject("hookUrl");
   if (o != null && !o.isNullObject()) {
     hookUrl = o.getString("url");
   } else {
     hookUrl = null;
   }
   credentials = req.bindJSONToList(Credential.class, hookMode.get("credentials"));
   save();
   return true;
 }
  LayerInfo layer(JSONObject json) throws IOException {
    CatalogFactory f = importer.getCatalog().getFactory();

    if (json.has("layer")) {
      json = json.getJSONObject("layer");
    }

    ResourceInfo r = f.createFeatureType();
    if (json.has("name")) {
      r.setName(json.getString("name"));
    }
    if (json.has("nativeName")) {
      r.setNativeName(json.getString("nativeName"));
    }
    if (json.has("srs")) {
      r.setSRS(json.getString("srs"));
      try {
        r.setNativeCRS(CRS.decode(json.getString("srs")));
      } catch (Exception e) {
        // should fail later
      }
    }
    if (json.has("bbox")) {
      r.setNativeBoundingBox(bbox(json.getJSONObject("bbox")));
    }

    LayerInfo l = f.createLayer();
    l.setResource(r);
    // l.setName(); don't need to this, layer.name just forwards to name of underlying resource

    if (json.has("style")) {
      JSONObject sobj = new JSONObject();
      sobj.put("defaultStyle", json.get("style"));

      JSONObject lobj = new JSONObject();
      lobj.put("layer", sobj);

      LayerInfo tmp = fromJSON(lobj, LayerInfo.class);
      if (tmp.getDefaultStyle() != null) {
        l.setDefaultStyle(tmp.getDefaultStyle());
      } else {
        sobj = new JSONObject();
        sobj.put("style", json.get("style"));

        l.setDefaultStyle(fromJSON(sobj, StyleInfo.class));
      }
    }
    return l;
  }
Example #12
0
  @Override
  protected void updateConnectorDataHistory(UpdateInfo updateInfo)
      throws RateLimitReachedException, Exception {
    // taking care of resetting the data if things went wrong before
    if (!connectorUpdateService.isHistoryUpdateCompleted(updateInfo.apiKey, -1))
      apiDataService.eraseApiData(updateInfo.apiKey, -1);
    int retrievedItems = ITEMS_PER_PAGE;
    for (int page = 0; retrievedItems == ITEMS_PER_PAGE; page++) {
      JSONObject feed = retrievePhotoHistory(updateInfo, 0, System.currentTimeMillis(), page);
      if (feed.has("stat")) {
        String stat = feed.getString("stat");
        if (stat.equalsIgnoreCase("fail")) {
          String message = feed.getString("message");
          throw new RuntimeException("Could not retrieve Flickr history: " + message);
        }
      }
      JSONObject photosWrapper = feed.getJSONObject("photos");

      if (photosWrapper != null) {
        JSONArray photos = photosWrapper.getJSONArray("photo");
        retrievedItems = photos.size();
        apiDataService.cacheApiDataJSON(updateInfo, feed, -1, -1);
      } else break;
    }
  }
Example #13
0
  @Override
  public void updateConnectorData(UpdateInfo updateInfo) throws Exception {
    int retrievedItems = ITEMS_PER_PAGE;
    long lastUploadTime = getLastUploadTime(updateInfo);
    for (int page = 0; retrievedItems == ITEMS_PER_PAGE; page++) {
      JSONObject feed =
          retrievePhotoHistory(updateInfo, lastUploadTime, System.currentTimeMillis(), page);

      if (!(feed.getString("stat").equalsIgnoreCase("ok"))) {
        String message = "n/a";
        if (feed.containsKey("message")) message = feed.getString("message");
        throw new Exception("There was an error calling the Flickr API: " + message);
      }

      JSONObject photosWrapper = feed.getJSONObject("photos");

      if (photosWrapper != null) {
        if (photosWrapper.containsKey("photo")) {
          JSONArray photos = photosWrapper.getJSONArray("photo");
          retrievedItems = photos.size();
          apiDataService.cacheApiDataJSON(updateInfo, feed, -1, -1);
        } else break;
      } else break;
    }
  }
  public void execute(Tuple tuple) {
    JSONObject eventObj = (JSONObject) tuple.getValueByField("eventoutput");
    String session = eventObj.getString("sessionid");
    String eventType = eventObj.getString("event");

    if (eventType.equals("change")) {
      JSONObject payload = eventObj.getJSONObject("payload");

      if (payload.getString("field").equals("firstname")) {
        Long count = this.counts.get(session);
        if (count == null) {
          count = 0L;
        }
        count++;
        this.counts.put(session, count);

        if (count > 2) {
          String desc =
              "In the " + session + " : " + "firstname was changed more than " + count + "times";
          System.out.println(desc);
          eventType = "TooManyNameChange";
          eventObj.put("event", eventType);
          // this.collector.emit(new Values(eventObj, desc,"APPUI_ACCEPT_PASSPORT"));
          this.collector.emit(new Values(eventObj, desc, "TOOMANYNAMECHANGES"));
        }
      }
    }
  }
Example #15
0
 /**
  * 获取应用代理
  *
  * @return
  */
 public static Result<QiYeAgent> getAgent(String token, String agentid) {
   Result<QiYeAgent> result = new Result<QiYeAgent>();
   JSONObject jo = UserAPI.getAgent(token, agentid);
   if (jo != null) {
     System.out.println(jo);
     result.setErrmsg(ErrorCodeText.errorMsg(jo.getString("errcode")));
     result.setErrcode(jo.getString("errcode"));
     if (result.getErrcode().equals("0")) {
       QiYeAgent agent = new QiYeAgent();
       agent.setName(jo.getString("name"));
       agent.setAgentid(jo.getString("agentid"));
       JSONObject jsonObject = jo.getJSONObject("allowpartys");
       agent.setAllowpartys(new PartyContainer(jsonObject.getString("partyid")));
       agent.setAllowusers(new UserContainer(jo.getString("allowusers")));
       agent.setMode(jo.getString("mode"));
       if (agent.getMode() == "1") {
         agent.setCallbackurl(jo.getString("callbackurl"));
         agent.setUrltoken(jo.getString("urltoken"));
         agent.setReport_location_flag(jo.getString("report_location_flag"));
       }
       agent.setDescription(jo.getString("description"));
       agent.setRedirectdomain(jo.getString("redirectdomain"));
       agent.setRoundUrl(jo.getString("RoundUrl"));
       agent.setSquareUrl(jo.getString("SquareUrl"));
       agent.setUseridlist(jo.getString("useridlist"));
       agent.setClose(jo.getInt("close"));
       result.setObject(agent);
     }
   }
   return result;
 }
Example #16
0
  /**
   * @param jsontxt
   * @return Autor[] - Extract autorun entries from Json representation.
   */
  public static Autorun[] extractAutorun(String jsontxt) {

    JSONObject jsonAutorunlist = (JSONObject) JSONSerializer.toJSON(jsontxt);
    // JSONObject Offline = json.getJSONObject("hooked-browsers").getJSONObject("offline");
    Autorun Autorunlist[] = new Autorun[jsonAutorunlist.size()];
    if (jsonAutorunlist.isEmpty()) {
      System.out.println("No Autorun, may be list is empty !");
    } else {
      for (int i = 0; i < jsonAutorunlist.size(); i++) {

        try {
          Autorun Autor = new Autorun();
          JSONObject Autorid = jsonAutorunlist.getJSONObject("" + i);
          Autor.setId(Autorid.getString("id"));
          Autor.setName(Autorid.getString("name"));
          Autor.setCc(Autorid.getString("cc"));
          Autor.setBrowser(Autorid.getString("browser"));
          Autor.setParam(Autorid.getString("Param"));
          Autor.setCategory(Autorid.getString("category"));
          Autorunlist[i] = Autor;
        } catch (JSONException e) {
          System.out.println("ERROR: " + e);
        }
      }
    }
    return Autorunlist;
  }
  public JSONObject setConditionXPath(String target, String value) {
    JSONObject targetElement = this.elementCache.get(target);
    MappingElement sourceElement = this.inputSchema.getMappingElement(value);
    String xpath = sourceElement.getXPath();
    String type = sourceElement.getType();

    if (targetElement.has("condition")) {
      log.debug("Set condition xpath for " + target + " to " + xpath);
      targetElement.getJSONObject("condition").put("xpath", xpath);
      targetElement.getJSONObject("condition").put("type", type);
      targetElement.getJSONObject("condition").remove("value");
      saveMappings();
    }

    return targetElement;
  }
Example #18
0
    private JSONObject reformLastestTrafficData(String sensorURL, JSONArray filterArr) {
      JSONObject result = new JSONObject();
      try {
        SensorManager sensorManager = new SensorManager();
        Sensor sensor = sensorManager.getSpecifiedSensorWithSensorId(sensorURL);
        if (sensor == null) return result;
        Observation obs = sensorManager.getNewestObservationForOneSensor(sensorURL);

        JSONObject metaJson = new JSONObject();
        metaJson.put("name", sensor.getName());
        metaJson.put("source", sensor.getSource());
        metaJson.put("sourceType", sensor.getSourceType());
        metaJson.put("city", sensor.getPlace().getCity());
        metaJson.put("country", sensor.getPlace().getCountry());

        OutputStream out = null;
        out = DatabaseUtilities.getNewestSensorData(sensorURL);
        JSONObject json = (JSONObject) JSONSerializer.toJSON(out.toString());
        json.put("updated", DateUtil.date2StandardString(new Date()));
        json.put("ntriples", JSONUtil.JSONToNTriple(json.getJSONObject("results")));
        json.put("error", "false");
        json.put("meta", metaJson);

        System.out.println(json);
        result = json;
      } catch (Exception e) {
        e.printStackTrace();
        JSONObject jsonResult = new JSONObject();
        jsonResult.put("error", "true");
        jsonResult.put("ntriples", "");
        result = jsonResult;
      }
      return result;
    }
Example #19
0
  void processSetProperties(JSONObject data) {
    final String tokenId = data.getString("tokenId");
    final Token token = findTokenFromId(tokenId);
    final Zone zone = findZoneTokenIsOn(token);

    if (token == null) {
      System.out.println("DEBUG: sendTokenInfo(): Unable to find token " + tokenId);
      return;
      // FIXME: log this error
    }

    final JSONObject props = data.getJSONObject("properties");
    EventQueue.invokeLater(
        new Runnable() {
          @Override
          public void run() {
            Set<String> pnames = props.keySet();
            for (String pname : pnames) {
              String val = props.getString(pname);
              token.setProperty(pname, val);
            }

            zone.putToken(token);
          }
        });
  }
 @Override
 public boolean configure(final StaplerRequest req, final JSONObject json) throws FormException {
   JSONObject selectedJson = json.getJSONObject("searchBackend");
   if (selectedJson.containsKey(SOLR_URL)) {
     String solrUrl = selectedJson.getString(SOLR_URL);
     ensureNotError(doCheckSolrUrl(solrUrl), SOLR_URL);
     try {
       setSolrUrl(makeSolrUrl(solrUrl));
     } catch (IOException e) {
       // Really shouldn't be possible, but this is the correct action, should it ever happen
       throw new FormException("Incorrect freetext config", SOLR_URL);
     }
   }
   if (selectedJson.containsKey(SOLR_COLLECTION)) {
     String solrCollection = selectedJson.getString(SOLR_COLLECTION);
     ensureNotError(doCheckSolrCollection(solrCollection, getSolrUrl()), SOLR_COLLECTION);
     setSolrCollection(solrCollection);
   }
   if (selectedJson.containsKey(LUCENE_PATH)) {
     String lucenePath = selectedJson.getString(LUCENE_PATH);
     ensureNotError(doCheckLucenePath(lucenePath), LUCENE_PATH);
     setLucenePath(new File(lucenePath));
   }
   if (json.containsKey(USE_SECURITY)) {
     setUseSecurity(json.getBoolean(USE_SECURITY));
   }
   setSearchBackend(SearchBackendEngine.valueOf(json.get("").toString()));
   reconfigure();
   return super.configure(req, json);
 }
  private void parseZeoTime(JSONObject stats, String key, ZeoSleepStatsFacet facet) {
    JSONObject o = stats.getJSONObject(key);

    int day = o.getInt("day");
    int month = o.getInt("month");
    int year = o.getInt("year");
    int hours = o.getInt("hour");
    int minutes = o.getInt("minute");
    int seconds = o.getInt("second");

    Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    c.set(Calendar.MILLISECOND, 0);
    c.set(year, month - 1, day, hours, minutes, seconds);
    if (key.equals("bedTime")) {
      facet.startTimeStorage = toTimeStorage(year, month, day, hours, minutes, seconds);
      facet.start = c.getTimeInMillis();
    } else {
      facet.date =
          (new StringBuilder())
              .append(year)
              .append("-")
              .append(pad(month))
              .append("-")
              .append(pad(day))
              .toString();
      facet.endTimeStorage = toTimeStorage(year, month, day, hours, minutes, seconds);
      facet.end = c.getTimeInMillis();
    }
  }
  /** {@inheritDoc} */
  @Override
  protected void submit(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException, Descriptor.FormException {
    super.submit(req, rsp);
    synchronized (this) {
      JSONObject json = req.getSubmittedForm();

      /*
      Set<String> oldSourceIds = new HashSet<String>();
      for (SCMSource source : getSCMSources()) {
          oldSourceIds.add(source.getId());
      }
      */

      sources.replaceBy(req.bindJSONToList(BranchSource.class, json.opt("sources")));
      for (SCMSource scmSource : getSCMSources()) {
        scmSource.setOwner(this);
      }

      setProjectFactory(
          req.bindJSON(BranchProjectFactory.class, json.getJSONObject("projectFactory")));

      save();

      /* TODO currently ComputedFolder.save always reschedules indexing; could define API to be more discerning
      Set<String> newSourceIds = new HashSet<String>();
      for (SCMSource source : getSCMSources()) {
          newSourceIds.add(source.getId());
      }
      reindex = !newSourceIds.equals(oldSourceIds);
      */
    }
  }
Example #23
0
  int putNewTask(int imp, String data) throws Exception {
    File zip = getTestDataFile(data);
    byte[] payload = new byte[(int) zip.length()];
    FileInputStream fis = new FileInputStream(zip);
    fis.read(payload);
    fis.close();

    MockHttpServletRequest req =
        createRequest("/rest/imports/" + imp + "/tasks/" + new File(data).getName());
    req.setHeader("Content-Type", MediaType.APPLICATION_ZIP.toString());
    req.setMethod("PUT");
    req.setBodyContent(payload);

    MockHttpServletResponse resp = dispatch(req);
    assertEquals(201, resp.getStatusCode());
    assertNotNull(resp.getHeader("Location"));

    assertTrue(resp.getHeader("Location").matches(".*/imports/" + imp + "/tasks/\\d"));
    assertEquals("application/json", resp.getContentType());

    JSONObject json = (JSONObject) json(resp);

    JSONObject task = json.getJSONObject("task");
    return task.getInt("id");
  }
Example #24
0
  int postNewTaskAsMultiPartForm(int imp, String data) throws Exception {
    File dir = unpack(data);

    List<Part> parts = new ArrayList<Part>();
    for (File f : dir.listFiles()) {
      parts.add(new FilePart(f.getName(), f));
    }
    MultipartRequestEntity multipart =
        new MultipartRequestEntity(
            parts.toArray(new Part[parts.size()]), new PostMethod().getParams());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    multipart.writeRequest(bout);

    MockHttpServletRequest req = createRequest("/rest/imports/" + imp + "/tasks");
    req.setContentType(multipart.getContentType());
    req.addHeader("Content-Type", multipart.getContentType());
    req.setMethod("POST");
    req.setBodyContent(bout.toByteArray());

    MockHttpServletResponse resp = dispatch(req);
    assertEquals(201, resp.getStatusCode());
    assertNotNull(resp.getHeader("Location"));

    assertTrue(resp.getHeader("Location").matches(".*/imports/" + imp + "/tasks/\\d"));
    assertEquals("application/json", resp.getContentType());

    JSONObject json = (JSONObject) json(resp);

    JSONObject task = json.getJSONObject("task");
    return task.getInt("id");
  }
Example #25
0
  public void pick() throws IOException {
    while (true) {
      pickUrl =
          String.format(
              "http://web.im.baidu.com/pick?v=30&session=&source=22&type=23&flag=1&seq=%d&ack=%s&guid=%s",
              sequence, ack, guid);

      HttpGet getRequest = new HttpGet(pickUrl);
      HttpResponse pickRes = httpClient.execute(getRequest);
      String entityStr = EntityUtils.toString(pickRes.getEntity());
      System.out.println("Pick result:" + entityStr);
      EntityUtils.consume(pickRes.getEntity());

      JSONObject jsonObject = JSONObject.fromObject(entityStr);
      JSONObject content = jsonObject.getJSONObject("content");
      if (content != null && content.get("ack") != null) {
        ack = (String) content.get("ack");
        JSONArray fields = content.getJSONArray("fields");
        JSONObject o = fields.getJSONObject(0);
        String fromUser = (String) o.get("from");
        System.out.println("++++Message from: " + fromUser);
      }
      updateSequence();

      if (sequence > 4) {
        break;
      }
    }
  }
Example #26
0
 public static Namelist fromJSONtoNamelist(JSONObject jsonObj) {
   logger.info("Convert json object to namelist...");
   if (jsonObj != null) {
     String name = jsonObj.getString("_name");
     String species = jsonObj.getString("_species");
     if (species == null) {
       JSONObject metadataJSONObj = jsonObj.getJSONObject("metadata");
       if (metadataJSONObj != null) {
         species = metadataJSONObj.getString("species");
       }
     }
     int size = jsonObj.getInt("_size");
     JSONArray data =
         jsonObj.containsKey("_data")
             ? jsonObj.getJSONArray("_data")
             : jsonObj.getJSONArray("gaggle-data");
     String[] names = new String[data.size()];
     for (int i = 0; i < data.size(); i++) {
       logger.info("Data item: " + data.getString(i));
       names[i] = data.getString(i);
     }
     logger.info("Species: " + species + " Names: " + names);
     Namelist nl = new Namelist(name, species, names);
     return nl;
   }
   return null;
 }
    @Override
    public synchronized boolean configure(StaplerRequest req, JSONObject formData)
        throws FormException {

      // The following codes are bad...
      // How to bind formData to List<Discriptor> ?

      if (nexusMap == null) {
        nexusMap = new HashMap<String, NexusDescriptor>();
      }

      try {
        JSONObject json = formData.getJSONObject("nexusList");
        nexusMap.clear();
        NexusDescriptor desc = parse(json);
        nexusMap.put(desc.getName(), desc);
      } catch (JSONException e) {
        try {
          JSONArray jsons = formData.getJSONArray("nexusList");
          nexusMap.clear();
          for (Object json : jsons) {
            NexusDescriptor desc = parse((JSONObject) json);
            nexusMap.put(desc.getName(), desc);
          }
        } catch (JSONException ee) {
          // exec in this path only if nexusList is empty.
        }
      }

      save();
      return super.configure(req, formData);
    }
 private String getOpenStatus(
     CrawlerPage crawlerPage, String partnerId, String encryptProviderUserId) {
   String url =
       "https://zht.alipay.com/asset/assetItemQuery.json?_input_charset=utf-8&action=bank";
   String encodedId;
   try {
     encodedId = URLEncoder.encode(encryptProviderUserId, "UTF-8");
     String sourceCode =
         getNewSourceCode(
                 crawlerPage,
                 url + "&partnerId=" + partnerId + "&encryptProviderUserId=" + encodedId)
             .getSourceCode();
     JSONObject result = JSONObject.fromObject(sourceCode);
     if ("ok".equals(result.getString("stat"))) {
       if (result
           .getJSONObject("results")
           .getJSONObject("FASTPAYSERVICE")
           .getBoolean("validKatong")) {
         return "已开通";
       } else {
         return "未开通";
       }
     }
   } catch (UnsupportedEncodingException e) {
     logger.warn(e.getMessage());
   }
   return "";
 }
Example #29
0
  public static void main(String[] args) {
    List<Map<String, Integer>> list = new ArrayList<Map<String, Integer>>();
    for (int i = 24; i <= 28; i++) {
      Map<String, Integer> map = new HashMap<String, Integer>();
      map.put("day", i);
      map.put("havedata", 0);
      list.add(map);
    }
    Random r = new Random();
    for (int i = 1; i <= 31; i++) {
      Map<String, Integer> map = new HashMap<String, Integer>();
      map.put("day", i);
      map.put("havedata", 1);
      map.put("nowfee", 3216 + r.nextInt(1000000));
      map.put("oldfee", 3216 + r.nextInt(1000000));
      map.put("dau", 3216 + r.nextInt(1000000));
      map.put("dnu", 3216 + r.nextInt(1000000));
      list.add(map);
    }
    for (int i = 1; i <= 6; i++) {
      Map<String, Integer> map = new HashMap<String, Integer>();
      map.put("day", i);
      map.put("havedata", 0);
      list.add(map);
    }
    System.out.println(array2JsonString(list));

    String json =
        "{\"code\":0,\"info\":\"success\",\"data\":{\"systemMail\":{\"mailVer\":19,\"target\":0,\"condition\":0,\"value\":2,\"title\":\"???è?????é??\",\"content\":\"???è?????é?????è?????é??\",\"sendTime\":1402555848,\"award\":{\"awardId\":0,\"gold\":2,\"heart\":2,\"diamond\":333,\"items\":[12,123],\"itemsCount\":[1,2]}}},\"sys_time\":1402555848}";
    JSONObject obj = getObj(json);
    System.out.println(obj.getJSONObject("data").getJSONObject("systemMail").getInt("mailVer"));
    System.out.println(obj.getInt("code"));
  }
 public void run() {
   System.out.println("Getting Repost Feature of " + uid);
   File f = new File(Config.SAVE_PATH + "\\Weibos\\" + uid + ".txt");
   List<String> weibo_list = new ArrayList<String>();
   try {
     GetInfo.getList(f, weibo_list, false);
   } catch (IOException e1) {
     e1.printStackTrace();
   }
   for (String weibo : weibo_list) {
     JSONObject weibo_json = JSONObject.fromObject(weibo);
     JSONObject retweet = weibo_json.getJSONObject("weibo").getJSONObject("retweetedStatus");
     if (retweet == null || retweet.equals("")) continue;
     String id = retweet.getString("userId");
     if (id.equals("null")) continue; // 被转发的微博已经被删除
     if (user.containsKey(id)) {
       user.put(id, user.get(id) + 1);
     } else {
       user.put(id, 1);
     }
   }
   List<Entry<String, Integer>> list = Utils.orderMapByValue(user); // 按转发次数从大到小排序
   try {
     SaveInfo.saveEntryList("\\Feature_RePost\\" + uid + ".txt", list, ":", false);
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }