private void addTagsToProperties(MethodInfo mi, JSONObject propJ) throws JSONException {
    // create description object. description tag enables the visual tools to display description of
    // keys/values
    // of a map property, items of a list, properties within a complex type.
    JSONObject descriptionObj = new JSONObject();
    if (mi.comment != null) {
      descriptionObj.put("$", mi.comment);
    }
    for (Map.Entry<String, String> descEntry : mi.descriptions.entrySet()) {
      descriptionObj.put(descEntry.getKey(), descEntry.getValue());
    }
    if (descriptionObj.length() > 0) {
      propJ.put("descriptions", descriptionObj);
    }

    // create useSchema object. useSchema tag is added to enable visual tools to be able to render a
    // text field
    // as a dropdown with choices populated from the schema attached to the port.
    JSONObject useSchemaObj = new JSONObject();
    for (Map.Entry<String, String> useSchemaEntry : mi.useSchemas.entrySet()) {
      useSchemaObj.put(useSchemaEntry.getKey(), useSchemaEntry.getValue());
    }
    if (useSchemaObj.length() > 0) {
      propJ.put("useSchema", useSchemaObj);
    }
  }
  /**
   * @param gd
   * @param peer
   * @throws IOException
   * @throws EncodeException
   * @throws JSONException
   */
  @OnMessage
  public void broadCastMessage(GameData gd, Session peer)
      throws IOException, EncodeException, JSONException, Exception {
    System.out.println("JSON RECEIVED");
    String gameID = gd.getJson().get("gameId").toString();
    String playername = gd.getJson().getString("playerName");

    // we may not need these lines
    GameBoard board = cache.getBoard();
    board.addPlayerToBoard(new Player(playername));
    JSONObject jSONObject = new JSONObject();
    jSONObject.put("players", board.getPlayersOnBoard());
    jSONObject.put("gameId", gameID);
    jSONObject.put("type", "notify");
    jSONObject.put("playerName", playername);
    if (board.getPlayersOnBoard().size() == 3) {
      jSONObject.put("startGame", true);
    }
    gd.setJson(jSONObject);
    System.out.println("JSON : " + gd.getJson());
    for (Session currPeer : peers) {
      currPeer.getBasicRemote().sendObject(gd);
    }
    System.out.println("JSON SENT");
  }
  /**
   * Returns the entity audit events for a given entity id. The events are returned in the
   * decreasing order of timestamp.
   *
   * @param guid entity id
   * @param startKey used for pagination. Startkey is inclusive, the returned results contain the
   *     event with the given startkey. First time getAuditEvents() is called for an entity,
   *     startKey should be null, with count = (number of events required + 1). Next time
   *     getAuditEvents() is called for the same entity, startKey should be equal to the entityKey
   *     of the last event returned in the previous call.
   * @param count number of events required
   * @return
   */
  @GET
  @Path("{guid}/audit")
  @Produces(Servlets.JSON_MEDIA_TYPE)
  public Response getAuditEvents(
      @PathParam("guid") String guid,
      @QueryParam("startKey") String startKey,
      @QueryParam("count") @DefaultValue("100") short count) {
    LOG.debug(
        "Audit events request for entity {}, start key {}, number of results required {}",
        guid,
        startKey,
        count);
    try {
      List<EntityAuditEvent> events = metadataService.getAuditEvents(guid, startKey, count);

      JSONObject response = new JSONObject();
      response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId());
      response.put(AtlasClient.EVENTS, getJSONArray(events));
      return Response.ok(response).build();
    } catch (AtlasException | IllegalArgumentException e) {
      LOG.error("Unable to get audit events for entity guid={} startKey={}", guid, startKey, e);
      throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST));
    } catch (Throwable e) {
      LOG.error("Unable to get audit events for entity guid={} startKey={}", guid, startKey, e);
      throw new WebApplicationException(
          Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
    }
  }
  /**
   * Deletes a given trait from an existing entity represented by a guid.
   *
   * @param guid globally unique identifier for the entity
   * @param traitName name of the trait
   */
  @DELETE
  @Path("{guid}/traits/{traitName}")
  @Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON})
  @Produces(Servlets.JSON_MEDIA_TYPE)
  public Response deleteTrait(
      @Context HttpServletRequest request,
      @PathParam("guid") String guid,
      @PathParam(TRAIT_NAME) String traitName) {
    LOG.info("Deleting trait={} from entity={} ", traitName, guid);
    try {
      metadataService.deleteTrait(guid, traitName);

      JSONObject response = new JSONObject();
      response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId());
      response.put(TRAIT_NAME, traitName);

      return Response.ok(response).build();
    } catch (EntityNotFoundException | TypeNotFoundException e) {
      LOG.error("An entity with GUID={} does not exist traitName={} ", guid, traitName, e);
      throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.NOT_FOUND));
    } catch (TraitNotFoundException e) {
      LOG.error("The trait name={} for entity={} does not exist.", traitName, guid, e);
      throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.NOT_FOUND));
    } catch (AtlasException | IllegalArgumentException e) {
      LOG.error("Unable to delete trait name={} for entity={}", traitName, guid, e);
      throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST));
    } catch (Throwable e) {
      LOG.error("Unable to delete trait name={} for entity={}", traitName, guid, e);
      throw new WebApplicationException(
          Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
    }
  }
  /**
   * Gets the list of trait names for a given entity represented by a guid.
   *
   * @param guid globally unique identifier for the entity
   * @return a list of trait names for the given entity guid
   */
  @GET
  @Path("{guid}/traits")
  @Produces(Servlets.JSON_MEDIA_TYPE)
  public Response getTraitNames(@PathParam("guid") String guid) {
    try {
      LOG.debug("Fetching trait names for entity={}", guid);
      final List<String> traitNames = metadataService.getTraitNames(guid);

      JSONObject response = new JSONObject();
      response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId());
      response.put(AtlasClient.RESULTS, new JSONArray(traitNames));
      response.put(AtlasClient.COUNT, traitNames.size());

      return Response.ok(response).build();
    } catch (EntityNotFoundException e) {
      LOG.error("An entity with GUID={} does not exist", guid, e);
      throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.NOT_FOUND));
    } catch (AtlasException | IllegalArgumentException e) {
      LOG.error("Unable to get trait names for entity {}", guid, e);
      throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST));
    } catch (Throwable e) {
      LOG.error("Unable to get trait names for entity {}", guid, e);
      throw new WebApplicationException(
          Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
    }
  }
  /**
   * Gets the list of entities for a given entity type.
   *
   * @param entityType name of a type which is unique
   */
  public Response getEntityListByType(String entityType) {
    try {
      Preconditions.checkNotNull(entityType, "Entity type cannot be null");

      LOG.debug("Fetching entity list for type={} ", entityType);
      final List<String> entityList = metadataService.getEntityList(entityType);

      JSONObject response = new JSONObject();
      response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId());
      response.put(AtlasClient.TYPENAME, entityType);
      response.put(AtlasClient.RESULTS, new JSONArray(entityList));
      response.put(AtlasClient.COUNT, entityList.size());

      return Response.ok(response).build();
    } catch (NullPointerException e) {
      LOG.error("Entity type cannot be null", e);
      throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST));
    } catch (AtlasException | IllegalArgumentException e) {
      LOG.error("Unable to get entity list for type {}", entityType, e);
      throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST));
    } catch (Throwable e) {
      LOG.error("Unable to get entity list for type {}", entityType, e);
      throw new WebApplicationException(
          Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
    }
  }
 private void appendProperty(
     JSONObject item, ISchemaType type, ISchemaProperty prop, ISerializationNode childNode) {
   Node n = (Node) childNode;
   ISchemaType propType = prop.getType();
   String propName = type.getQualifiedPropertyName(prop);
   try {
     if (prop.isAttribute()) {
       propName = "@" + propName;
       if (prop.getStructureType() == StructureType.MAP) {
         IMapSchemaProperty mapProp = (IMapSchemaProperty) prop;
         Object defaultValue = DefaultValueFactory.getDefaultValue(mapProp.getValueType());
         item.put(propName + "_1", defaultValue + "_1");
         item.put(propName + "_2", defaultValue + "_2");
       } else {
         Object defaultValue = DefaultValueFactory.getDefaultValue(propType);
         item.put(propName, defaultValue);
       }
     } else if (prop.getStructureType() == StructureType.COLLECTION) {
       item.put(propName, n.array);
     } else if (propType == null || propType.isComplex()) {
       item.put(propName, n.object);
     } else {
       Object defaultValue = DefaultValueFactory.getDefaultValue(prop);
       if (item != null) item.put(propName, defaultValue);
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
  public static void main(String[] args)
      throws SQLException, ClassNotFoundException, JSONException {
    PostgresDb db = new PostgresDb();
    // db.setUrl("jdbc:postgresql://localhost:5432/powaaim");

    try {
      Class.forName("org.postgresql.Driver");
      c = DriverManager.getConnection(db.getUrl(), db.getUser(), db.getPass());
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    st = c.createStatement();
    rs = st.executeQuery("SELECT id, name, externalshopid from shop where name='David_3'");
    System.out.println("id" + " " + "name" + " " + "externalshopid");
    c.close();
    obj = new JSONObject();

    while (rs.next()) {
      int id = rs.getInt("id");
      String externaId = rs.getString("externalshopid");
      String name = rs.getString("name");
      // System.out.println(id+ " " + " "+ name + " " +" "+ externaId);
      System.out.println();
      obj.put("id", id);
      obj.put("name", name);
      obj.put("externalshopid", externaId);
      System.out.print(obj);
    }
  }
 public void sendJson(Object jsonData) throws Log4AllException {
   HttpPut addLogPut;
   if (jsonData instanceof JSONArray) {
     addLogPut = new HttpPut(url + "/api/logs");
   } else {
     addLogPut = new HttpPut(url + "/api/log");
   }
   String rawResponse = "";
   JSONObject jsonResp;
   try {
     JSONObject jsonReq;
     if (jsonData instanceof JSONArray) {
       jsonReq = new JSONObject();
       jsonReq.put("logs", jsonData);
     } else {
       jsonReq = (JSONObject) jsonData;
     }
     jsonReq.put("application", this.application);
     if (token != null) {
       jsonReq.put("application_token", this.token);
     }
     HttpEntity postData = new StringEntity(jsonReq.toString());
     addLogPut.setEntity(postData);
     HttpResponse resp = getHttpClient().execute(addLogPut);
     rawResponse = IOUtils.toString(resp.getEntity().getContent());
     jsonResp = new JSONObject(rawResponse);
     if (!jsonResp.getBoolean("success")) {
       throw new Log4AllException(jsonResp.getString("message"));
     }
   } catch (IOException e) {
     throw new Log4AllException(e.getMessage() + "httpResp:" + rawResponse, e);
   } catch (JSONException e) {
     throw new Log4AllException(e.getMessage() + "httpResp:" + rawResponse, e);
   }
 }
Beispiel #10
0
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.TEXT_PLAIN)
  @Path("/userList")
  public String getHotTalkList() throws Exception {
    JSONObject jsonData = new JSONObject();
    JSONArray jsonArray = new JSONArray();

    try {
      List<Map<String, Object>> lst = new ArrayList<Map<String, Object>>();
      lst = m_userDao.getUserList();
      if (lst.isEmpty()) {
        jsonData.put("err", "데이터가 없습니다.");
        return jsonData.toString();
      }
      Iterator<Map<String, Object>> itr = lst.iterator();
      int i = 0;
      while (itr.hasNext()) {
        itr.next();
        jsonArray.put(lst.get(i++));
      }
      jsonData.put("userList", jsonArray);
      jsonData.put("err", "");
    } catch (Exception ex) {
      ex.printStackTrace();
      System.out.println(ex.getMessage());
      jsonData.put("err", "시스템오류.");
    }
    // System.out.println("result : " + jsonData.toString());
    return jsonData.toString();
  }
 public static JSONObject toJSON(String msg, String level, Date date) throws JSONException {
   JSONObject jsonData = new JSONObject();
   jsonData.put("message", msg);
   jsonData.put("level", level);
   jsonData.put("date", date.getTime());
   return jsonData;
 }
Beispiel #12
0
    private static JSONObject exec(String method, String uri, Object data, String contentType)
        throws JSONException {
      ClientResponse apiResult;
      JSONObject response = new JSONObject();

      try {
        apiResult =
            buildRequest(API_BASE_URL + uri, contentType)
                .method(method, ClientResponse.class, data);
        int apiHttpCode = apiResult.getStatus();

        response.put("status", apiHttpCode);

        String responseBody = apiResult.getEntity(String.class);

        response.put(
            "response",
            responseBody.indexOf("[") == 0
                ? new JSONArray(responseBody)
                : new JSONObject(responseBody));
      } catch (Exception e) {
        response.put("status", 500);
        response.put("error", e.getMessage());
      }

      return response;
    }
Beispiel #13
0
  @Override
  public JSONObject convertToATSJSON() throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(ATSConstants.ENTITY, "tez_" + applicationAttemptId.toString());
    jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_APPLICATION_ATTEMPT.name());

    // Related Entities
    JSONArray relatedEntities = new JSONArray();
    JSONObject appEntity = new JSONObject();
    appEntity.put(ATSConstants.ENTITY, applicationAttemptId.getApplicationId().toString());
    appEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.APPLICATION_ID);
    JSONObject appAttemptEntity = new JSONObject();
    appAttemptEntity.put(ATSConstants.ENTITY, applicationAttemptId.toString());
    appAttemptEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.APPLICATION_ATTEMPT_ID);
    relatedEntities.put(appEntity);
    relatedEntities.put(appAttemptEntity);
    jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities);

    // TODO decide whether this goes into different events,
    // event info or other info.
    JSONArray events = new JSONArray();
    JSONObject startEvent = new JSONObject();
    startEvent.put(ATSConstants.TIMESTAMP, startTime);
    startEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.AM_STARTED.name());
    events.put(startEvent);
    jsonObject.put(ATSConstants.EVENTS, events);

    return jsonObject;
  }
  @Override
  public boolean doWork(Message message) {

    try {
      // either create and insert a new payload:
      // JSONObject json_out = new JSONObject();
      // json_out.put("processed", true);
      // message.setPayload(json_out);

      // or work on the existing one:
      JSONObject tweet = message.getPayload();

      if (processTweet(tweet)) {
        JSONObject result = new JSONObject();
        result.put("tweet_id", tweet.getLong("id"));
        result.put("date_posted", tweet.getLong("date_posted"));
        if (tweet.has("images")) result.put("images", tweet.getJSONArray("images"));
        if (tweet.has("coordinates") && !tweet.isNull("coordinates"))
          result.put("coordinates", tweet.getJSONObject("coordinates"));
        message.setPayload(result);

        return true;
      } else {
        return false;
      }
    } catch (JSONException e) {
      log.error("JSONException: " + e);
      logConn.error("JSONException: " + e);
      return false;
    }
  }
  /** Upon initialization, send across emberized forms of the (relevant) model definitions */
  public void sendModels(ErrorHandler eh) {
    for (Observer o : observers) {
      Model m = o.getModel();
      for (String docName : m.documents()) {
        for (ObjectDefinition od : m.objects(docName)) {
          try {
            JSONObject model = new JSONObject();
            model.put("modelName", StringUtil.capitalize(od.name));
            JSONObject hash = new JSONObject();
            model.put("model", hash);
            for (FieldDefinition x : od.fields()) {
              hash.put(x.name, attrOf(x.type, x));
            }
            send(model);
          } catch (JSONException ex) {
            logger.error("Error creating models", ex);
          }
        }
        /*
        for (LeaderboardDefinition ld : m.leaderboards(docName)) {
        	for (Grouping g : ld.groupings()) {
        		try {
        			String vn = ld.getViewName(g);
        			ObjectDefinition od = m.getModel(eh, vn);
        			// First define the entry
        			String lbname = StringUtil.capitalize(ld.name) + g.asGroupName();
        			String lbentry = lbname + "Entry";
        			{
        				JSONObject model = new JSONObject();
        				model.put("modelName", lbentry);
        				JSONObject hash = new JSONObject();
        				model.put("model", hash);
        				for (FieldDefinition x : od.fields()) {
        					hash.put(x.name, attrOf(x.type));
        				}
        				send(model);
        			}

        			// Then define the board
        			{
        				JSONObject model = new JSONObject();
        				model.put("modelName", lbname);
        				JSONObject hash = new JSONObject();
        				model.put("model", hash);
        				hash.put("entries", new JSONObject(CollectionUtils.map("rel", "hasMany", "name", lbentry)));
        				send(model);
        			}

        		} catch (JSONException ex) {
        			logger.error("Error creating models", ex);
        		}
        	}
        }
        */
      }
    }
  }
Beispiel #16
0
  @Override
  public JSONObject toJSONObject() throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("modulus", JSONObject.NULL);
    jsonObject.put("privateExponent", JSONObject.NULL);
    jsonObject.put("d", JwtUtil.base64urlencodeUnsignedBigInt(d));

    return jsonObject;
  }
Beispiel #17
0
 public static void addResultInfo(JSONObject response, AbstractProcessor processor)
     throws JSONException {
   String realKey = processor.getMessage().getKey();
   response.put("rc", processor.getRC());
   response.put("message", realKey);
   response.put("cause", realKey);
   response.put(
       "parameter",
       processor.getParameter()); // if getParameters returns null, nothing bad happens :-)
 }
 @Override
 public synchronized void deliver(Interest i, JSONObject payload) {
   try {
     JSONObject obj = new JSONObject();
     obj.put("deliveryFor", i.handle);
     obj.put("payload", payload);
     send(obj);
   } catch (JSONException ex) {
     sendError(ex.getMessage());
   }
 }
Beispiel #19
0
 @Override
 public JSONObject toJSON() {
   try {
     JSONObject storedFile = new JSONObject();
     storedFile.put("file_name", fileName);
     storedFile.put("topic_id", fileTopicId);
     return storedFile;
   } catch (Exception e) {
     throw new RuntimeException("Serialization failed (" + this + ")", e);
   }
 }
Beispiel #20
0
 /**
  * You must do the compaction before running this to remove the duplicate tokens out of the
  * server. TODO code it.
  */
 @SuppressWarnings("unchecked")
 public JSONObject estimateKeys() throws JSONException {
   Iterator<Entry<String, ColumnFamilyStoreMBean>> it = super.getColumnFamilyStoreMBeanProxies();
   JSONObject object = new JSONObject();
   while (it.hasNext()) {
     Entry<String, ColumnFamilyStoreMBean> entry = it.next();
     object.put("keyspace", entry.getKey());
     object.put("column_family", entry.getValue().getColumnFamilyName());
     object.put("estimated_size", entry.getValue().estimateKeys());
   }
   return object;
 }
 private JSONObject getResponse(AtlasClient.EntityResult entityResult)
     throws AtlasException, JSONException {
   JSONObject response = new JSONObject();
   response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId());
   response.put(
       AtlasClient.ENTITIES, new JSONObject(entityResult.toString()).get(AtlasClient.ENTITIES));
   String sampleEntityId = getSample(entityResult);
   if (sampleEntityId != null) {
     String entityDefinition = metadataService.getEntityDefinition(sampleEntityId);
     response.put(AtlasClient.DEFINITION, new JSONObject(entityDefinition));
   }
   return response;
 }
Beispiel #22
0
 private String createDagInfo(String script) throws IOException {
   String dagInfo;
   try {
     JSONObject jsonObject = new JSONObject();
     jsonObject.put("context", "Pig");
     jsonObject.put("description", script);
     dagInfo = jsonObject.toString();
   } catch (JSONException e) {
     throw new IOException("Error when trying to convert Pig script to JSON", e);
   }
   log.debug("DagInfo: " + dagInfo);
   return dagInfo;
 }
 @Override
 public String toString() {
   try {
     JSONObject jsonObj = new JSONObject();
     jsonObj.put("i", i);
     jsonObj.put("s", s);
     JSONObject barbarObj = new JSONObject(barbar.toString());
     jsonObj.put("barbar", barbarObj);
     return jsonObj.toString();
   } catch (JSONException e) {
     throw new RuntimeException("failed to construct JSONObject for toString", e);
   }
 }
 private void setAttributeRec(int i, String[] parts, JSONObject attrs, Object value)
     throws JSONException {
   if (i == parts.length - 1) {
     attrs.put(parts[i], value);
     return;
   }
   if (attrs.has(parts[i])) {
     setAttributeRec(i + 1, parts, attrs.getJSONObject(parts[i]), value);
   } else {
     attrs.put(parts[i], new JSONObject());
     setAttributeRec(i + 1, parts, attrs.getJSONObject(parts[i]), value);
   }
 }
Beispiel #25
0
  @POST
  @Produces(MediaType.APPLICATION_JSON)
  @Path("select")
  public String getUserData(String json) {
    JSONObject jObj = null;
    try {
      jObj = new JSONObject(json);
      Integer userID = Integer.parseInt(jObj.getString("userID"));
      User user = dbManager.getUserbyAccountId(userID);

      jObj.put("middle_name", user.getMiddleName());
      jObj.put("last_name", user.getLastName());
      jObj.put("street", user.getStreet());
      jObj.put("house_number", user.getHouseNumber());
      jObj.put("city", user.getCity());
      jObj.put("postal_code", user.getPostalCode());
      jObj.put("country", user.getCountry());
      Account account = user.getAccountId();
      jObj.put("email", account.getUserName());

    } catch (JSONException ex) {
      Logger.getLogger(ChangeAccount.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      return jObj.toString();
    }
  }
 @Override
 protected JSONObject execute(Map<String, Object> parameters, String data) {
   JSONObject result = new JSONObject();
   JSONObject errorMessage = new JSONObject();
   try {
     OBContext.setAdminMode(true);
     final JSONObject jsonData = new JSONObject(data);
     final String strBankStatementLineId = jsonData.getString("bankStatementLineId");
     String dateStr = jsonData.getString("updated");
     SimpleDateFormat xmlDateTimeFormat = JsonUtils.createJSTimeFormat();
     Date date = null;
     try {
       date = xmlDateTimeFormat.parse(dateStr);
     } catch (ParseException e) {
     }
     final FIN_BankStatementLine bsline =
         OBDal.getInstance().get(FIN_BankStatementLine.class, strBankStatementLineId);
     Date bbddBSLUpdated = bsline.getUpdated();
     // Remove milis
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(OBDateUtils.convertDateToUTC(bbddBSLUpdated));
     calendar.setLenient(true);
     calendar.set(Calendar.MILLISECOND, 0);
     if (date.getTime() != calendar.getTimeInMillis()) {
       throw new OBStaleObjectException("@APRM_StaleDate@");
     }
     final FIN_FinaccTransaction transaction = bsline.getFinancialAccountTransaction();
     if (transaction != null) {
       APRM_MatchingUtility.unmatch(bsline);
     }
   } catch (Exception e) {
     OBDal.getInstance().rollbackAndClose();
     log.error("Error Unmatching Transaction", e);
     try {
       Throwable ex = DbUtility.getUnderlyingSQLException(e);
       String message = OBMessageUtils.translateError(ex.getMessage()).getMessage();
       errorMessage = new JSONObject();
       errorMessage.put("severity", "error");
       errorMessage.put("title", "Error");
       errorMessage.put("text", message);
       result.put("message", errorMessage);
     } catch (Exception e2) {
       log.error("Message could not be built", e2);
     }
   } finally {
     OBContext.restorePreviousMode();
   }
   return result;
 }
Beispiel #27
0
  private static JSONObject map2json(Map<?, ?> preference) throws JSONException, Exception {
    JSONObject result = new JSONObject();

    for (Entry<?, ?> entry : preference.entrySet()) {
      if (entry.getValue() instanceof Collection) {
        result.put((String) entry.getKey(), map2json((Collection<?>) entry.getValue()));
      } else if (entry.getValue() instanceof Map) {
        result.put((String) entry.getKey(), map2json((Map<?, ?>) entry.getValue()));
      } else {
        result.put((String) entry.getKey(), entry.getValue());
      }
    }

    return result;
  }
Beispiel #28
0
  @GET
  @Path("/")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getStatisticsIndex(@Context final UriInfo uriInfo)
      throws IllegalArgumentException, UriBuilderException, JSONException {

    final JSONObject result = new JSONObject();
    result.put(
        MAX_RESULTS_PATH,
        uriInfo.getBaseUriBuilder().path(Settings.class).path(MAX_RESULTS_PATH).build());
    result.put(
        PAGE_REFRESH_PATH,
        uriInfo.getBaseUriBuilder().path(Settings.class).path(PAGE_REFRESH_PATH).build());

    return Response.ok(result.toString()).build();
  }
Beispiel #29
0
  /**
   * Deletes a file.
   *
   * @param id File ID
   * @return Response
   * @throws JSONException
   */
  @DELETE
  @Path("{id: [a-z0-9\\-]+}")
  @Produces(MediaType.APPLICATION_JSON)
  public Response delete(@PathParam("id") String id) throws JSONException {
    if (!authenticate()) {
      throw new ForbiddenClientException();
    }

    // Get the file
    FileDao fileDao = new FileDao();
    DocumentDao documentDao = new DocumentDao();
    File file;
    try {
      file = fileDao.getFile(id);
      documentDao.getDocument(file.getDocumentId(), principal.getId());
    } catch (NoResultException e) {
      throw new ClientException("FileNotFound", MessageFormat.format("File not found: {0}", id));
    }

    // Delete the file
    fileDao.delete(file.getId());

    // Raise a new file deleted event
    FileDeletedAsyncEvent fileDeletedAsyncEvent = new FileDeletedAsyncEvent();
    fileDeletedAsyncEvent.setFile(file);
    AppContext.getInstance().getAsyncEventBus().post(fileDeletedAsyncEvent);

    // Always return ok
    JSONObject response = new JSONObject();
    response.put("status", "ok");
    return Response.ok().entity(response).build();
  }
Beispiel #30
0
  public JSONObject toJSON() {
    JSONObject ret = new JSONObject();

    try {
      ret.put("name", name);
      ret.put("address", address);
      ret.put("port", port);
      ret.put("user", user);
      ret.put("passwd", passwd);
      ret.put("status", status);
    } catch (JSONException e) {
      System.err.println("JSONException in toJSON: " + e);
    }

    return ret;
  }