Пример #1
0
 @Override
 public JSONObject serialize(Query bean) throws JSONException {
   if (bean == null) {
     return null;
   }
   if (!typeNames.containsKey(bean.getClass())) {
     throw new UnsupportedOperationException(
         "Class "
             + bean.getClass()
             + " is not supported for serialization by the QueryJsonHandler");
   }
   JSONObject defaultSerialization = (JSONObject) JsonSerializer.serialize(bean, false);
   if (bean instanceof FieldAwareQuery) {
     defaultSerialization.remove("field");
     if (bean instanceof SpanTerm && ((SpanTerm) bean).getBoost() == null) {
       SpanTerm spanTerm = (SpanTerm) bean;
       defaultSerialization = new JSONObject().put(spanTerm.getField(), spanTerm.getValue());
     } else {
       defaultSerialization =
           new JSONObject().put(((FieldAwareQuery) bean).getField(), defaultSerialization);
     }
   }
   if (bean instanceof Selection) {
     defaultSerialization.remove("field");
     defaultSerialization =
         new JSONObject().put(((Selection) bean).getField(), defaultSerialization);
   }
   if (bean.getRelevance() != null) {
     defaultSerialization.remove("relevance");
     defaultSerialization.put("relevance", JsonSerializer.serialize(bean.getRelevance()));
   }
   return new JSONObject().put(typeNames.get(bean.getClass()), defaultSerialization);
 }
  private static URI getThumbnailUrl(final JSONObject json)
      throws URISyntaxException, ElementProcessingException {
    // System.out.println("\n\n\nGot JSON: \n"+json.toString(2));
    /*
     * "media$group":{"media$thumbnail":
     * [{"width":"130","height":"97","time":"00:07:43.500",
     * "url":"http://img.youtube.com/vi/jDDkNFiEm1A/2.jpg"}
     */
    try {
      final JSONObject mediaGroup = json.getJSONObject("media$group");
      // System.out.println("Got Media GROUP: "+mediaGroup);
      final JSONArray mediaThumbnails = mediaGroup.getJSONArray("media$thumbnail");
      final JSONObject mediaThumbnail = mediaThumbnails.getJSONObject(0);
      final String url = mediaThumbnail.getString("url");

      // System.out.println("Returning thumb URL: "+url);

      // While we're here, purge some stuff to save memory!!
      mediaGroup.remove("media$description");
      mediaGroup.remove("media$keywords");

      json.remove("category");
      json.remove("content");

      // System.out.println("Cleaned JSON: \n"+json.toString(2));
      return new URI(url);
    } catch (final JSONException e) {
      throw new ElementProcessingException("Bad JSON?...." + json, e);
    }
  }
Пример #3
0
 public void updatePlaceToWelocally(JSONObject place) throws JSONException {
   place.put("_id", place.getString("id").replaceAll("SG_", "WL_"));
   place.put("type", "Place");
   place.remove("id");
   JSONObject properties = place.getJSONObject("properties");
   properties.remove("href");
   properties.put("owner", "welocally");
 }
 /**
  * Prepares a new copy of an analysis for editing.
  *
  * @param daoFactory used to obtain data access objects.
  * @param analysis the analysis to copy.
  * @param userDetails information about the current user.
  * @return the new analysis identifier.
  */
 private String copyAnalysis(
     DaoFactory daoFactory, TransformationActivity analysis, UserDetails userDetails) {
   JSONObject json = marshalAnalysis(daoFactory, analysis, new NoIdRetentionStrategy());
   json.remove("published_date");
   json.remove("edited_date");
   String newId = UUID.randomUUID().toString().toUpperCase();
   json = convertAnalysisToCopy(json, newId, userDetails);
   importAnalysis(json.toString());
   return new AnalysisId(newId).toString();
 }
Пример #5
0
 public static void trackFromSparksEvent(@NonNull SparksEvent sparksEvent) {
   if (!isEventIgnored(sparksEvent.getName()) && sMixpanelAPI != null && sGson != null) {
     try {
       JSONObject jSONObject = new JSONObject(sGson.toJson(sparksEvent.getParams()));
       jSONObject.remove("appVersion");
       jSONObject.remove("ts");
       jSONObject.remove("deviceId");
       sMixpanelAPI.m4786a(sparksEvent.getName(), jSONObject);
     } catch (JSONException e) {
       C3095y.m9479c(e.toString());
     }
   }
 }
  public static JSONObject translateFromEvent(AnalyticsEvent source) {
    if (null == source) {
      log.warn("The Event provided was null");
      return new JSONObject();
    }

    JSONObject json = source.toJSONObject();
    if (json.has("class")) {
      json.remove("class");
    }
    if (json.has("hashCode")) {
      json.remove("hashCode");
    }
    return json;
  }
Пример #7
0
 @Override
 public void removeMapKeys(
     String collection, String name, ColumnField mapField, ArrayList<ColumnField> mapKeys)
     throws FailedDBOperationException {
   JSONObject record = null;
   try {
     record = lookupEntireRecord(collection, name);
   } catch (RecordNotFoundException e) {
   }
   DatabaseConfig.getLogger().log(Level.FINE, "Record before:{0}", record);
   if (record == null) {
     throw new FailedDBOperationException(collection, name, "Record not found.");
   }
   if (mapField != null && mapKeys != null) {
     try {
       JSONObject json = record.getJSONObject(mapField.getName());
       for (int i = 0; i < mapKeys.size(); i++) {
         String fieldName = mapKeys.get(i).getName();
         json.remove(fieldName);
       }
       DatabaseConfig.getLogger().log(Level.FINE, "Json after:{0}", json);
       record.put(mapField.getName(), json);
       DatabaseConfig.getLogger().log(Level.FINE, "Record after:{0}", record);
     } catch (JSONException e) {
       DatabaseConfig.getLogger().log(Level.SEVERE, "Problem updating json: {0}", e.getMessage());
     }
   }
   getMap(collection).put(name, record);
 }
 public void addNewArticleToUser(String data, int articleId) {
   Log.d("SVF", "Modifying topic " + articleId);
   try {
     JSONObject article = new JSONObject(data);
     boolean found = article.getBoolean("found");
     if (found) {
       // update topic with new article; don't do anything if not found
       if (!ValuesAndUtil.getInstance().articleAlreadyExists(article, topics, articleId)) {
         article.remove("found");
         article.put("thumbsUp", false);
         article.put("thumbsDown", false);
         JSONObject topic = topics.getJSONObject(articleId);
         JSONArray timeline = topic.getJSONArray("timeline");
         timeline = ValuesAndUtil.getInstance().addToExistingJSON(timeline, 0, article);
         topic.put("timeline", timeline);
         topic.put("lastTimeStamp", article.getLong("date"));
         topic.put("lastSignature", article.getString("signature"));
         topic.put("lastUpdated", System.currentTimeMillis());
         Log.d("SVF", topic.toString(2));
         topics.put(articleId, topic);
         user.put("topics", topics);
         ValuesAndUtil.getInstance().saveUserData(user, getActivity().getApplicationContext());
         mAdapter.notifyItemChanged(articleId);
         numUpdated++;
       }
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
  // Handle actionbar menu actions
  public void onSaveButton(MenuItem item) {
    try {
      // Look up the address field and add the lat/lon
      if (!mUser.isNull("loc_address") && !mUser.optString("loc_address").isEmpty()) {
        Geocoder g = new Geocoder(this, Locale.US);
        List<Address> result = g.getFromLocationName(mUser.optString("loc_address"), 1);

        if (!result.isEmpty()) {
          mUser.put("loc_lat", result.get(0).getLatitude());
          mUser.put("loc_lon", result.get(0).getLongitude());

          Log.d(TAG, "Put lat: " + result.get(0).getLatitude());
          Log.d(TAG, "Put lon: " + result.get(0).getLongitude());
        }
      }

      // Don't send picture if we didn't update it
      if (!mUser.optBoolean("picture_updated")) {
        mUser.remove("picture");
      }

      // Save all items to our user object and send it to the database
      saveAllItems();
      mUser.put("action", "update_user");
      new DatabaseRequest(mUser, this, this, true);
    } catch (JSONException e) {
      Log.e(TAG, e.toString(), e);
    } catch (IOException e) {
      Log.e(TAG, e.toString(), e);
    }
  }
Пример #10
0
 public int count(JSONObject query) throws ParseException {
   final String endPoint = retrieveEndpoint();
   ParseGetCommand command = new ParseGetCommand(endPoint);
   query.put("count", 1);
   query.put("limit", 0);
   query.remove("className");
   command.setData(query);
   ParseResponse response = command.perform();
   if (!response.isFailed()) {
     if (response.getJsonObject() == null) {
       LOGGER.debug("Empty response.");
       throw response.getException();
     }
     try {
       JSONObject json = response.getJsonObject();
       int count = json.getInt("count");
       return count;
     } catch (JSONException e) {
       LOGGER.error(
           "Although Parse reports object successfully saved, the response was invalid.", e);
       throw new ParseException(
           ParseException.INVALID_JSON,
           "Although Parse reports object successfully saved, the response was invalid.",
           e);
     }
   } else {
     LOGGER.debug("Request failed.");
     throw response.getException();
   }
 }
 @Override
 public JSONEntity read(Class<? extends JSONEntity> clazz, HttpInputMessage inputMessage)
     throws IOException, HttpMessageNotReadableException {
   // First read the string
   String jsonString =
       JSONEntityHttpMessageConverter.readToString(
           inputMessage.getBody(), inputMessage.getHeaders().getContentType().getCharSet());
   try {
     return EntityFactory.createEntityFromJSONString(jsonString, clazz);
   } catch (JSONObjectAdapterException e) {
     // Try to convert entity type to a concrete type and try again. See PLFM-2079.
     try {
       JSONObject jsonObject = new JSONObject(jsonString);
       if (jsonObject.has(ENTITY_TYPE)) {
         // get the entity type so we can replace it with concrete type
         String type = jsonObject.getString(ENTITY_TYPE);
         jsonObject.remove(ENTITY_TYPE);
         jsonObject.put(CONCRETE_TYPE, type);
         jsonString = jsonObject.toString();
         // try again
         return EntityFactory.createEntityFromJSONString(jsonString, clazz);
       } else {
         // Something else went wrong
         throw new HttpMessageNotReadableException(e.getMessage(), e);
       }
     } catch (JSONException e1) {
       throw new HttpMessageNotReadableException(e1.getMessage(), e);
     } catch (JSONObjectAdapterException e2) {
       throw new HttpMessageNotReadableException(e2.getMessage(), e);
     }
   }
 }
  private void deleteItem(String hash) {
    String filename = getString(R.string.my_devices_file);
    JSONObject jsonObject = new JSONObject();
    File dir = getFilesDir();
    File file = new File(dir, filename);
    if (file.exists()) {
      try {
        jsonObject = new JSONObject(readFromFile());
      } catch (JSONException e) {
        e.printStackTrace();
      }

      if (jsonObject.has(hash)) {
        //	this device is already saved
        jsonObject.remove(hash);
        String saveBeaconInfo = jsonObject.toString();
        // Log.v(TAG,"This is saved "+ saveBeaconInfo);
        FileOutputStream outputStream;
        try {
          outputStream = openFileOutput(filename, Context.MODE_PRIVATE); // was append
          outputStream.write(saveBeaconInfo.getBytes());
          outputStream.close();
        } catch (Exception e) {
          e.printStackTrace();
          Toast.makeText(getBaseContext(), "Failed to save", Toast.LENGTH_SHORT).show();
        }
      }
    }
  }
 public synchronized void delete(String appname) {
   if (mJsonArray != null) {
     int length = mJsonArray.length();
     JSONObject json = null;
     for (int i = 0; i < length; i++) {
       json = mJsonArray.optJSONObject(i);
       String name = (String) json.optString(Constant.APPNAME_KEY);
       if (null != name && name.equals(appname)) {
         json.remove(Constant.APPNAME_KEY);
         json.remove(Constant.DOWNLOAD_SIZE_KEY);
         persistent();
         return;
       }
     }
   }
 }
Пример #14
0
  /* (non-Javadoc)
   * @see com.futureplatforms.android.jscore.fragmentation.CursorCoercer#coerceToJSONObject(java.lang.String[], android.database.AbstractWindowedCursor)
   */
  @Override
  public JSONObject coerceToJSONObject(String[] cols, AbstractWindowedCursor c) {
    JSONObject obj = new JSONObject();
    for (int i = 0; i < cols.length; i++) {
      String name = cols[i];
      // do we have to worry about types?
      // if we do, then we need the CursorWindow.

      // TODO we can make this faster for SDK > 5.
      // TODO have a separate class depending on SDK.
      try {
        if (c.isString(i)) {
          obj.putOpt(name, c.getString(i));
        } else if (c.isLong(i)) {
          obj.put(name, c.getLong(i));
        } else if (c.isFloat(i)) {
          obj.put(name, c.getDouble(i));
        } else if (c.isNull(i)) {
          obj.remove(name);
        }
      } catch (JSONException e) {
        Log.e(C.TAG, e.getLocalizedMessage(), e);
      }
    }
    return obj;
  }
Пример #15
0
  /** Encode options to JSON. */
  public String toString() {
    JSONObject dict = options.getDict();
    JSONObject json = new JSONObject();

    try {
      json = new JSONObject(dict.toString());
    } catch (JSONException e) {
      e.printStackTrace();
    }

    json.remove("updatedAt");
    json.remove("soundUri");
    json.remove("iconUri");

    return json.toString();
  }
Пример #16
0
  public void callService(@NonNull final JSONObject params, int method_type)
      throws UnsupportedEncodingException {

    String jobID = null;
    try {
      jobID = params.getString(Constants.JOBID);
      String startIndex = "&startIndex=" + params.getString(Constants.STARTINDEX);
      String endIndex = "&endIndex=" + params.getString(Constants.ENDINDEX);
      String url = Constants.GetJobChatWebservice + jobID + startIndex + endIndex;
      params.remove(Constants.JOBID);
      params.remove(Constants.STARTINDEX);
      params.remove(Constants.ENDINDEX);
      super.callService(url, params, method_type);
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
Пример #17
0
 public boolean convertUploadDefinition(
     final JSONObject uploadConfig, final Class<?> originalClass, final Class<?> newClass) {
   if (uploadConfig.has(originalClass.getName())) {
     uploadConfig.put(newClass.getName(), uploadConfig.remove(originalClass.getName()));
     return true;
   }
   return false;
 }
Пример #18
0
  /**
   * Logins.
   *
   * <p>Renders the response with a json object, for example,
   *
   * <pre>
   * {
   *     "isLoggedIn": boolean,
   *     "msg": "" // optional, exists if isLoggedIn equals to false
   * }
   * </pre>
   *
   * @param context the specified context
   */
  @RequestProcessing(value = "/login", method = HTTPRequestMethod.POST)
  public void login(final HTTPRequestContext context) {
    final HttpServletRequest request = context.getRequest();

    final JSONRenderer renderer = new JSONRenderer();

    context.setRenderer(renderer);
    final JSONObject jsonObject = new JSONObject();

    renderer.setJSONObject(jsonObject);

    try {
      jsonObject.put(Common.IS_LOGGED_IN, false);
      final String loginFailLabel = langPropsService.get("loginFailLabel");

      jsonObject.put(Keys.MSG, loginFailLabel);

      final JSONObject requestJSONObject =
          Requests.parseRequestJSONObject(request, context.getResponse());
      final String userEmail = requestJSONObject.getString(User.USER_EMAIL);
      final String userPwd = requestJSONObject.getString(User.USER_PASSWORD);

      if (Strings.isEmptyOrNull(userEmail) || Strings.isEmptyOrNull(userPwd)) {
        return;
      }

      LOGGER.log(Level.INFO, "Login[email={0}]", userEmail);

      final JSONObject user = userQueryService.getUserByEmail(userEmail);

      if (null == user) {
        LOGGER.log(Level.WARN, "Not found user[email={0}]", userEmail);
        return;
      }

      if (MD5.hash(userPwd).equals(user.getString(User.USER_PASSWORD))) {
        Sessions.login(request, context.getResponse(), user);

        LOGGER.log(Level.INFO, "Logged in[email={0}]", userEmail);

        jsonObject.put(Common.IS_LOGGED_IN, true);

        if (Role.VISITOR_ROLE.equals(user.optString(User.USER_ROLE))) {
          jsonObject.put("to", Latkes.getServePath());
        } else {
          jsonObject.put("to", Latkes.getServePath() + Common.ADMIN_INDEX_URI);
        }

        jsonObject.remove(Keys.MSG);

        return;
      }

      LOGGER.log(Level.WARN, "Wrong password[{0}]", userPwd);
    } catch (final Exception e) {
      LOGGER.log(Level.ERROR, e.getMessage(), e);
    }
  }
Пример #19
0
  @SuppressWarnings("unchecked")
  public List<T> find(JSONObject query) throws ParseException {
    final String endPoint = retrieveEndpoint();
    ParseGetCommand command = new ParseGetCommand(endPoint);
    query.remove("className");
    command.setData(query);
    ParseResponse response = command.perform();
    List<T> results = null;
    if (!response.isFailed()) {
      if (response.getJsonObject() == null) {
        LOGGER.debug("Empty response.");
        throw response.getException();
      }
      try {
        JSONObject json = response.getJsonObject();
        JSONArray objs = json.getJSONArray("results");
        if (objs.length() == 0) {
          return null;
        }

        if (trace) {
          strTrace = json.getString("trace");
          if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(strTrace);
          }
        }

        results = new ArrayList<T>();
        for (int i = 0; i < objs.length(); i++) {
          results.add(createPojo((JSONObject) objs.get(i)));
        }

        return results;
      } catch (JSONException e) {
        LOGGER.error(
            "Although Parse reports object successfully saved, the response was invalid.", e);
        throw new ParseException(
            ParseException.INVALID_JSON,
            "Although Parse reports object successfully saved, the response was invalid.",
            e);
      } catch (InstantiationException e) {
        LOGGER.error("Error while instantiating class. Did you register your subclass?", e);
        throw new ParseException(
            ParseException.INVALID_JSON,
            "Although Parse reports object successfully saved, the response was invalid.",
            e);
      } catch (IllegalAccessException e) {
        LOGGER.error("Error while instantiating class. Did you register your subclass?", e);
        throw new ParseException(
            ParseException.INVALID_JSON,
            "Although Parse reports object successfully saved, the response was invalid.",
            e);
      }
    } else {
      LOGGER.debug("Request failed.");
      throw response.getException();
    }
  }
 @Override
 public boolean onJSONManipulate(JSONObject object) {
   if (object.has(key)) {
     object.remove(key);
     notifyOnChange(key);
     return true;
   } else {
     return false;
   }
 }
  public TunePushPayload(String json) throws JSONException {
    JSONObject object = new JSONObject(json);

    // In test pushes we are not guaranteed to have an open action field
    if (object.has(JSON_OPEN_ACTION)) {
      onOpenAction = new TunePushOpenAction(object.getJSONObject(JSON_OPEN_ACTION));
      // The extra payload params the user sets is everything but our 'ANA' field
      object.remove(JSON_OPEN_ACTION);
    }
    userExtraPayloadParams = object;
  }
Пример #22
0
 /**
  * Put a key/value pair in the JSONObject. If the value is null, then the key will be removed from
  * the JSONObject if it is present.
  *
  * @param key A key string.
  * @param value An object which is the value. It should be of one of these types: Boolean, Double,
  *     Integer, JSONArray, JSONObject, Long, String, or the JSONObject.NULL object.
  * @return this.
  * @throws JSONException If the value is non-finite number or if the key is null.
  */
 public JSONObject put(String key, Object value) throws JSONException {
   if (key == null) {
     throw new JSONException("Null key.");
   }
   if (value != null) {
     testValidity(value);
     this.map.put(key, value);
   } else {
     remove(key);
   }
   return this;
 }
  private SheetContent deserializeChart(JSONObject content)
      throws JSONException, SerializationException {
    SheetContent toReturn;
    ChartDefinition chart = new ChartDefinition();

    JSONObject categoryJSON = content.optJSONObject(WorkSheetSerializationUtils.CATEGORY);
    if (categoryJSON != null) {
      Attribute category =
          (Attribute)
              SerializationManager.deserialize(categoryJSON, "application/json", Attribute.class);
      chart.setCategory(category);
    }

    JSONObject groupingVariableJSON =
        content.optJSONObject(WorkSheetSerializationUtils.GROUPING_VARIABLE);
    if (groupingVariableJSON != null) {
      Attribute groupingVariable =
          (Attribute)
              SerializationManager.deserialize(
                  groupingVariableJSON, "application/json", Attribute.class);
      chart.setGroupingVariable(groupingVariable);
    }

    List<Serie> series = new ArrayList<Serie>();
    JSONArray seriesJSON = content.getJSONArray(WorkSheetSerializationUtils.SERIES);
    SerieJSONDeserializer deserialier = new SerieJSONDeserializer();
    for (int i = 0; i < seriesJSON.length(); i++) {
      JSONObject aSerie = seriesJSON.getJSONObject(i);
      Serie serie = deserialier.deserialize(aSerie);
      series.add(serie);
    }
    chart.setSeries(series);

    content.remove(WorkSheetSerializationUtils.CATEGORY);
    content.remove(WorkSheetSerializationUtils.SERIES);
    chart.setConfig(content);

    toReturn = chart;
    return toReturn;
  }
Пример #24
0
  private JSONObject sanitizeConfigLocation(final JSONObject config) {
    if (config == null) {
      return null;
    }

    // sanitize plugin.config.location.classes
    JSONObject location = config.optJSONObject("location");
    if (location != null) {
      String classes = location.optString("classes");
      if (classes != null && classes.length() > 0) {
        String[] filteredClasses = filterClasses(classes.split(" "));
        JSONHelper.putValue(location, "classes", StringUtils.join(filteredClasses, " "));
      }
      // Make sure we don't have inline css set
      location.remove("top");
      location.remove("right");
      location.remove("bottom");
      location.remove("left");
    }

    return config;
  }
  /** The inverse of toRest. Creates a new OperationSet from the given JSON. */
  public static ParseOperationSet fromRest(JSONObject json, ParseDecoder decoder)
      throws JSONException {
    // Copy the json object to avoid making changes to the old object
    Iterator<String> keysIter = json.keys();
    String[] keys = new String[json.length()];
    int index = 0;
    while (keysIter.hasNext()) {
      String key = keysIter.next();
      keys[index++] = key;
    }

    JSONObject jsonCopy = new JSONObject(json, keys);
    String uuid = (String) jsonCopy.remove(REST_KEY_UUID);
    ParseOperationSet operationSet =
        (uuid == null ? new ParseOperationSet() : new ParseOperationSet(uuid));

    boolean isSaveEventually = jsonCopy.optBoolean(REST_KEY_IS_SAVE_EVENTUALLY);
    jsonCopy.remove(REST_KEY_IS_SAVE_EVENTUALLY);
    operationSet.setIsSaveEventually(isSaveEventually);

    Iterator<?> opKeys = jsonCopy.keys();
    while (opKeys.hasNext()) {
      String opKey = (String) opKeys.next();
      Object value = decoder.decode(jsonCopy.get(opKey));
      ParseFieldOperation fieldOp;
      if (opKey.equals("ACL")) {
        value = ParseACL.createACLFromJSONObject(jsonCopy.getJSONObject(opKey), decoder);
      }
      if (value instanceof ParseFieldOperation) {
        fieldOp = (ParseFieldOperation) value;
      } else {
        fieldOp = new ParseSetOperation(value);
      }
      operationSet.put(opKey, fieldOp);
    }

    return operationSet;
  }
 @PUT
 @Path("/edit/{id}")
 @Consumes(MediaType.APPLICATION_JSON)
 public void editNote(String inputData, @PathParam("id") int id) {
   JSONObject inputJSON = new JSONObject(inputData);
   if ((inputJSON.has("sessionID"))
       && UsersController.checkLogin(inputJSON.getString("sessionID"))) {
     Note newNote = resolveNoteData(inputJSON);
     if (inputJSON.has("noteID")) inputJSON.remove("noteID"); // na wszelki wypadek - ID podano
     hibernate.controllers.NotesController notesController =
         new hibernate.controllers.NotesController();
     if (newNote != null) notesController.updateNote(newNote, id);
   }
 }
Пример #27
0
 @Override
 public void map(LongWritable key, Text value, Context context)
     throws IOException, InterruptedException {
   try {
     JSONObject obj = new JSONObject(value.toString());
     long gameID = obj.getLong("game");
     obj.remove("game");
     outputKey.set(gameID);
     outputValue.set(obj.toString());
     context.write(outputKey, outputValue);
   } catch (Exception e) {
     System.out.println(e);
   }
 }
 @POST
 @Path("/create")
 @Consumes(MediaType.APPLICATION_JSON)
 public void createNote(String inputData) {
   JSONObject inputJSON = new JSONObject(inputData);
   if ((inputJSON.has("sessionID"))
       && UsersController.checkLogin(inputJSON.getString("sessionID"))) {
     if (inputJSON.has("noteID"))
       inputJSON.remove("noteID"); // na wszelki wypadek - chcemy generowaæ ID automatycznie
     Note newNote = resolveNoteData(inputJSON);
     hibernate.controllers.NotesController notesController =
         new hibernate.controllers.NotesController();
     if (newNote != null) notesController.addNote(newNote);
   }
 }
Пример #29
0
  public static int checkDirectory(String basedir, JSONArray files) {
    if (files == null) return 0;

    Simple.removePost(freeMemory);
    getStorage();

    int newcount = 0;
    int skiplen = basedir.length() + 1;

    boolean initial = !filestats.has(basedir);

    JSONObject oldfiles = initial ? null : Json.getObject(filestats, basedir);
    JSONObject newfiles = new JSONObject();

    for (int inx = 0; inx < files.length(); inx++) {
      JSONObject file = Json.getObject(files, inx);
      String name = Json.getString(file, "file");
      String time = Json.getString(file, "time");
      if ((name == null) || (time == null)) continue;

      name = name.substring(skiplen);

      if (oldfiles != null) {
        if (oldfiles.has(name)) {
          oldfiles.remove(name);
          Json.put(newfiles, name, time);
        } else {
          newcount++;
        }
      } else {
        Json.put(newfiles, name, time);
      }
    }

    Json.put(filestats, basedir, newfiles);

    int delcount = (oldfiles != null) ? oldfiles.length() : 0;

    if ((delcount > 0) || (newcount > 0) || initial) {
      dirty = true;
    }

    Simple.makePost(freeMemory, 10 * 1000);

    return newcount;
  }
Пример #30
0
  @DELETE
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  @Produces("application/json")
  public ReturnMessage deleteSearch(
      @FormParam("user") String user, @FormParam("searchName") String searchName) {

    CouchConnection couch = new CouchConnection("http://localhost:5984/", "savedsearches/");
    ReturnMessage rm = new ReturnMessage();
    try {
      JSONObject userViews = new JSONObject(couch.queryDB(user));

      userViews.remove(searchName);
      couch.updateDocument(user, userViews);

      rm.setResult("success");
    } catch (Exception e) {
      rm.setResult("failure");
    }
    return rm;
  }