@RequestMapping(method = RequestMethod.POST, value = "/planrecurrent/{clientId}")
  public @ResponseBody RecurrentJourney planRecurrentJourney(
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession session,
      @RequestBody RecurrentJourneyParameters parameters,
      @PathVariable String clientId)
      throws InvocationException, AcServiceException {
    try {
      User user = getUser(request);
      String userId = getUserId(user);
      if (userId == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
      }

      List<String> reqs = buildRecurrentJourneyPlannerRequest(parameters);
      List<SimpleLeg> legs = new ArrayList<SimpleLeg>();
      ObjectMapper mapper = new ObjectMapper();
      for (String req : reqs) {
        String plan =
            HTTPConnector.doGet(
                otpURL + SMARTPLANNER + RECURRENT, req, MediaType.APPLICATION_JSON, null, "UTF-8");
        List sl = mapper.readValue(plan, List.class);
        for (Object o : sl) {
          legs.add((SimpleLeg) mapper.convertValue(o, SimpleLeg.class));
        }
      }

      DomainObject res =
          getObjectByClientId(
              clientId, "smartcampus.services.journeyplanner.RecurrentJourneyObject");
      if (res != null) {
        String objectId = checkUser(res, userId);
        if (objectId == null) {
          response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } else {
          RecurrentJourney oldJourney =
              mapper.convertValue(res.getContent().get("data"), RecurrentJourney.class);
          RecurrentJourney journey = new RecurrentJourney();
          journey.setParameters(parameters);
          journey.setLegs(legs);
          journey.setMonitorLegs(buildMonitorMap(legs, oldJourney.getMonitorLegs()));
          return journey;
        }
      } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      }

    } catch (ConnectorException e0) {
      response.setStatus(e0.getCode());
    } catch (Exception e) {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    return null;
  }
Exemplo n.º 2
0
 public static JsonNode toJsonNode(Object obj) {
   if (obj == null) {
     return null;
   }
   JsonNode node = mapper.convertValue(obj, JsonNode.class);
   return node;
 }
Exemplo n.º 3
0
 /**
  * Get List Object from key and Object type
  *
  * @param key
  * @param clz
  * @return
  */
 public <T> List<T> getList(String key, Class<T> clz) {
   ObjectMapper mapper = new ObjectMapper();
   mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
   List<T> lst =
       mapper.convertValue(
           this.data.get(key), mapper.getTypeFactory().constructCollectionType(List.class, clz));
   return lst;
 }
Exemplo n.º 4
0
 public static Map<String, Object> toJsonMap(Object obj) {
   if (obj == null) {
     return null;
   }
   @SuppressWarnings("unchecked")
   Map<String, Object> map = mapper.convertValue(obj, Map.class);
   return map;
 }
 private static MethodResult convertResult(SecureResponse resultMessage)
     throws ClassNotFoundException {
   MethodResult result = resultMessage.getMessage().getResult();
   Class<?> clazz = Class.forName(result.getClassName());
   Object resultValue = MAPPER.convertValue(result.getArg(), clazz);
   result.setArg(resultValue);
   return result;
 }
Exemplo n.º 6
0
 @SuppressWarnings("unchecked")
 public static Map<String, Object> createRequestJsonNamedParam(
     String action, String method, final int tid, Map<String, Object> data) {
   ExtDirectRequest dr = new ExtDirectRequest();
   dr.setAction(action);
   dr.setMethod(method);
   dr.setTid(tid);
   dr.setType("rpc");
   dr.setData(data);
   return mapper.convertValue(dr, LinkedHashMap.class);
 }
Exemplo n.º 7
0
  public static Object normalizeJsonTree(Object obj) {
    if (obj instanceof Map) {
      @SuppressWarnings("unchecked")
      Map<Object, Object> m = (Map<Object, Object>) obj;
      Object o;
      UUID uuid;
      for (Object k : m.keySet()) {
        if (k instanceof String && ((String) k).equalsIgnoreCase("name")) {
          continue;
        }

        o = m.get(k);
        uuid = tryConvertToUUID(o);
        if (uuid != null) {
          m.put(k, uuid);
        } else if (o instanceof Integer) {
          m.put(k, ((Integer) o).longValue());
        } else if (o instanceof BigInteger) {
          m.put(k, ((BigInteger) o).longValue());
        }
      }
    } else if (obj instanceof List) {
      @SuppressWarnings("unchecked")
      List<Object> l = (List<Object>) obj;
      Object o;
      UUID uuid;
      for (int i = 0; i < l.size(); i++) {
        o = l.get(i);
        uuid = tryConvertToUUID(o);
        if (uuid != null) {
          l.set(i, uuid);
        } else if ((o instanceof Map) || (o instanceof List)) {
          normalizeJsonTree(o);
        } else if (o instanceof Integer) {
          l.set(i, ((Integer) o).longValue());
        } else if (o instanceof BigInteger) {
          l.set(i, ((BigInteger) o).longValue());
        }
      }
    } else if (obj instanceof String) {
      UUID uuid = tryConvertToUUID(obj);
      if (uuid != null) {
        return uuid;
      }
    } else if (obj instanceof Integer) {
      return ((Integer) obj).longValue();
    } else if (obj instanceof BigInteger) {
      return ((BigInteger) obj).longValue();
    } else if (obj instanceof JsonNode) {
      return mapper.convertValue(obj, Object.class);
    }
    return obj;
  }
Exemplo n.º 8
0
  @SuppressWarnings("unchecked")
  @Override
  public List<TVBlobService> get(String url) throws Exception {
    List<TVBlobService> services = Lists.newArrayList();

    List<Object> objects = mapper.readValue(client.getContentsOf(url), ArrayList.class);
    for (Object object : objects) {
      TVBlobService service = mapper.convertValue(object, TVBlobService.class);
      services.add(service);
    }

    return services;
  }
  @RequestMapping(
      method = RequestMethod.GET,
      value = "/eu.trentorise.smartcampus.journeyplanner.sync.BasicRecurrentJourney/{clientId}")
  public @ResponseBody BasicRecurrentJourney getRecurrentJourney(
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession session,
      @PathVariable String clientId)
      throws InvocationException {
    try {
      User user = getUser(request);
      String userId = getUserId(user);
      if (userId == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
      }

      DomainObject obj =
          getObjectByClientId(
              clientId, "smartcampus.services.journeyplanner.RecurrentJourneyObject");
      if (obj == null) {
        return null;
      }
      if (checkUser(obj, userId) == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
      }

      ObjectMapper mapper = new ObjectMapper();
      mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      Map<String, Object> content = obj.getContent();
      RecurrentJourney recurrent = mapper.convertValue(content.get("data"), RecurrentJourney.class);
      BasicRecurrentJourney recurrentJourney = new BasicRecurrentJourney();
      String objectClientId = (String) content.get("clientId");
      if (!clientId.equals(objectClientId)) {
        response.setStatus(HttpServletResponse.SC_CONFLICT);
        return null;
      }
      recurrentJourney.setData(recurrent);
      recurrentJourney.setClientId(clientId);
      recurrentJourney.setName((String) obj.getContent().get("name"));
      recurrentJourney.setMonitor((Boolean) obj.getContent().get("monitor"));
      recurrentJourney.setUser((String) obj.getContent().get("userId"));

      return recurrentJourney;
    } catch (Exception e) {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
  }
Exemplo n.º 10
0
 /**
  * Get Object from key and Object type
  *
  * @param key
  * @param clz
  * @return
  */
 public <T> T get(String key, final Class<T> clz) {
   ObjectMapper mapper = new ObjectMapper();
   mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
   T t =
       mapper.convertValue(
           this.data.get(key),
           new TypeReference() {
             @Override
             public Type getType() {
               return clz;
             }
           });
   return t;
 }
Exemplo n.º 11
0
 @Override
 protected void onPostExecute(MobileResponse<List<R>> result) {
   if (callback != null) {
     if (result.isSuccess()) {
       ObjectMapper mapper = new ObjectMapper();
       JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, cltype);
       List<R> results = mapper.convertValue(result.getResult(), type);
       callback.onReceivedResult(results);
     } else {
       callback.onReceivedError(
           result.getErrorCode(), result.getErrorMessage(), result.getErrorTitle());
     }
   }
 }
  // no crud
  @RequestMapping(method = RequestMethod.POST, value = "/plansinglejourney")
  public @ResponseBody void planSingleJourney(
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession session,
      @RequestBody SingleJourney journeyRequest)
      throws InvocationException, AcServiceException {
    try {
      User user = getUser(request);
      String userId = getUserId(user);

      logger.info("-" + userId + "~AppConsume~plan");

      if (userId == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
      }

      List<String> reqs = buildItineraryPlannerRequest(journeyRequest);

      ObjectMapper mapper = new ObjectMapper();

      List<Itinerary> itineraries = new ArrayList<Itinerary>();

      for (String req : reqs) {
        String plan =
            HTTPConnector.doGet(
                otpURL + SMARTPLANNER + PLAN, req, MediaType.APPLICATION_JSON, null, "UTF-8");
        List its = mapper.readValue(plan, List.class);
        for (Object it : its) {
          Itinerary itinerary = mapper.convertValue(it, Itinerary.class);
          itineraries.add(itinerary);
        }
      }

      ItinerarySorter.sort(itineraries, journeyRequest.getRouteType());

      response.setContentType("application/json; charset=utf-8");

      String result = mapper.writeValueAsString(itineraries);

      ServletOutputStream sos = response.getOutputStream();
      sos.write(result.getBytes());
    } catch (ConnectorException e0) {
      response.setStatus(e0.getCode());
    } catch (Exception e) {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    //		return;
  }
Exemplo n.º 13
0
  /**
   * Upload the data vector as JSON to the specified Crowdflower job
   *
   * @param job
   * @param data - Generic vector of data, containing ordinary java classes. They should be
   *     annotated so that Jackson understands how to map them to JSON.
   */
  void uploadData(CrowdJob job, List<?> data) {
    Log LOG = LogFactory.getLog(getClass());

    // Crowdflower wants a Multi-line JSON, with each line having a new JSON object
    // Thus we have to map each (raw) object in data individually to a JSON string

    ObjectMapper mapper = new ObjectMapper();
    String jsonObjectCollection = "";

    StringBuilder jsonStringBuilder = new StringBuilder();
    int count = 0;
    for (Object obj : data) {
      count++;
      JsonNode jsonData = mapper.convertValue(obj, JsonNode.class);
      jsonStringBuilder.append(jsonData.toString());
      jsonStringBuilder.append("\n");
    }

    jsonObjectCollection = jsonStringBuilder.toString();

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> request = new HttpEntity<String>(jsonObjectCollection, headers);

    String result = "";

    if (job == null) {
      LOG.info("Upload new data and create new job: " + String.valueOf(count) + " data items");
      result = restTemplate.postForObject(uploadDataURL, request, String.class, apiKey);
    } else {
      LOG.info(
          "Uploading new data to job: "
              + job.getId()
              + ": "
              + String.valueOf(count)
              + " data items");
      result =
          restTemplate.postForObject(
              uploadDataWithJobURL, request, String.class, job.getId(), apiKey);
    }
    LOG.info("Upload response:" + result);

    // set gold? this is what i would like to do...
    // updateVariable(job, "https://api.crowdflower.com/v1/jobs/{jobid}/gold?key={apiKey}",
    // "set_standard_gold", "TRUE");
  }
Exemplo n.º 14
0
  @SuppressWarnings("unchecked")
  public static Map<String, Object> createRequestJson(
      String action, String method, final boolean namedParameter, int tid, Object data) {
    ExtDirectRequest dr = new ExtDirectRequest();
    dr.setAction(action);
    dr.setMethod(method);
    dr.setTid(tid);
    dr.setType("rpc");

    if (namedParameter || data instanceof Object[] || data == null) {
      dr.setData(data);
    } else {
      dr.setData(new Object[] {data});
    }
    return mapper.convertValue(dr, LinkedHashMap.class);
  }
  @RequestMapping(
      method = RequestMethod.GET,
      value = "/eu.trentorise.smartcampus.journeyplanner.sync.BasicRecurrentJourney")
  public @ResponseBody List<BasicRecurrentJourney> getRecurrentJourneys(
      HttpServletRequest request, HttpServletResponse response, HttpSession session)
      throws InvocationException {
    try {
      User user = getUser(request);
      String userId = getUserId(user);
      if (userId == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
      }

      Map<String, Object> pars = new TreeMap<String, Object>();
      pars.put("userId", userId);
      List<String> res =
          domainClient.searchDomainObjects(
              "smartcampus.services.journeyplanner.RecurrentJourneyObject",
              pars,
              "vas_journeyplanner_subscriber");

      List<BasicRecurrentJourney> journeys = new ArrayList<BasicRecurrentJourney>();
      ObjectMapper mapper = new ObjectMapper();
      mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      for (String r : res) {
        DomainObject obj = new DomainObject(r);
        RecurrentJourney recurrent =
            mapper.convertValue(obj.getContent().get("data"), RecurrentJourney.class);
        BasicRecurrentJourney recurrentJourney = new BasicRecurrentJourney();
        String clientId = (String) obj.getContent().get("clientId");
        recurrentJourney.setData(recurrent);
        recurrentJourney.setClientId(clientId);
        recurrentJourney.setName((String) obj.getContent().get("name"));
        recurrentJourney.setMonitor((Boolean) obj.getContent().get("monitor"));
        recurrentJourney.setUser((String) obj.getContent().get("userId"));

        journeys.add(recurrentJourney);
      }

      return journeys;

    } catch (Exception e) {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
  }
  @RequestMapping(method = RequestMethod.POST, value = "/planrecurrent")
  public @ResponseBody RecurrentJourney planRecurrentJourney(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestBody RecurrentJourneyParameters parameters,
      HttpSession session)
      throws InvocationException, AcServiceException {
    try {
      User user = getUser(request);
      String userId = getUserId(user);
      if (userId == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
      }

      List<String> reqs = buildRecurrentJourneyPlannerRequest(parameters);
      List<SimpleLeg> legs = new ArrayList<SimpleLeg>();
      ObjectMapper mapper = new ObjectMapper();
      for (String req : reqs) {
        String plan =
            HTTPConnector.doGet(
                otpURL + SMARTPLANNER + RECURRENT, req, MediaType.APPLICATION_JSON, null, "UTF-8");
        List sl = mapper.readValue(plan, List.class);
        for (Object o : sl) {
          legs.add((SimpleLeg) mapper.convertValue(o, SimpleLeg.class));
        }
      }

      RecurrentJourney journey = new RecurrentJourney();
      journey.setParameters(parameters);
      journey.setLegs(legs);
      journey.setMonitorLegs(buildMonitorMap(legs));

      response.setContentType("application/json; charset=utf-8");

      String result = mapper.writeValueAsString(journey);

      ServletOutputStream sos = response.getOutputStream();
      sos.write(result.getBytes());
    } catch (ConnectorException e0) {
      response.setStatus(e0.getCode());
    } catch (Exception e) {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    return null;
  }
 @Override
 @SuppressWarnings("unchecked")
 public String parseBundledQueryParams(String path, Object object)
     throws UnsupportedEncodingException {
   if (object != null) {
     path += path.contains("?") ? "&" : "?";
     Map<String, Object> props = mapper.convertValue(object, Map.class);
     List<String> vals = new ArrayList<String>();
     for (Map.Entry<String, Object> queryParamEntry : props.entrySet()) {
       if (queryParamEntry.getValue() != null) {
         String value = Uri.encode(queryParamEntry.getValue().toString());
         vals.add(queryParamEntry.getKey() + "=" + value);
       }
     }
     path = path + StringUtils.join(vals.toArray(), "&");
   }
   return path;
 }
Exemplo n.º 18
0
  private void retrieveFile(PrintWriter output, BufferedReader in)
      throws IOException, PortMgrException {
    FileRetriever fileRetriever = (FileRetriever) payload;

    output.println(LanguageProtocol.INIT_FILE_RETRIEVE);
    String response = in.readLine();

    if (null != response && response.equals(LanguageProtocol.ACK)) {
      String jsonOut = JDFSUtil.toJSON(fileRetriever.criteria);

      Printer.log("JSON of criteria:" + jsonOut);
      output.println(jsonOut);

      response = in.readLine();
      Printer.log("Got response " + response);

      if (null != response && response.equals(LanguageProtocol.ACCEPT_FILE_TRANS)) {
        output.println(LanguageProtocol.ACK);

        String json = in.readLine();
        ObjectMapper mapper = new ObjectMapper();
        FileRetrieverInfo incomingInfo = mapper.convertValue(json, FileRetrieverInfo.class);

        Printer.log("Got json:" + json);

        fileRetriever.setPort(PortMgr.getNextAvailablePort());

        Thread thread = new Thread(fileRetriever);
        thread.run();

        output.println(fileRetriever.port);

        /*
        response = in.readLine();
        if (null != response && response.equals(LanguageProtocol.ACK)) {
        	Thread thread = new Thread(fileRetriever);
        	thread.run();
        }*/

        FileHandler.getInstance().manageRecievedFile(fileRetriever.storeLocation, incomingInfo);
      }
    }
  }
  @RequestMapping(
      method = RequestMethod.GET,
      value = "/eu.trentorise.smartcampus.journeyplanner.sync.BasicItinerary/{clientId}")
  public @ResponseBody BasicItinerary getItinerary(
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession session,
      @PathVariable String clientId)
      throws InvocationException {
    try {
      User user = getUser(request);
      String userId = getUserId(user);
      if (userId == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
      }

      DomainObject res =
          getObjectByClientId(clientId, "smartcampus.services.journeyplanner.ItineraryObject");
      if (res == null) {
        return null;
      }

      if (checkUser(res, userId) == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
      }

      ObjectMapper mapper = new ObjectMapper();
      mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      Map<String, Object> content = res.getContent();
      BasicItinerary itinerary = mapper.convertValue(content, BasicItinerary.class);

      return itinerary;
    } catch (Exception e) {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
  }
  @RequestMapping(
      method = RequestMethod.GET,
      value = "/eu.trentorise.smartcampus.journeyplanner.sync.BasicItinerary")
  public @ResponseBody List<BasicItinerary> getItineraries(
      HttpServletRequest request, HttpServletResponse response, HttpSession session)
      throws InvocationException {
    try {
      User user = getUser(request);
      String userId = getUserId(user);
      if (userId == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
      }

      Map<String, Object> pars = new TreeMap<String, Object>();
      pars.put("userId", userId);
      List<String> res =
          domainClient.searchDomainObjects(
              "smartcampus.services.journeyplanner.ItineraryObject",
              pars,
              "vas_journeyplanner_subscriber");

      List<BasicItinerary> itineraries = new ArrayList<BasicItinerary>();
      ObjectMapper mapper = new ObjectMapper();
      mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

      for (String r : res) {
        DomainObject obj = new DomainObject(r);
        BasicItinerary itinerary = mapper.convertValue(obj.getContent(), BasicItinerary.class);
        itineraries.add(itinerary);
      }

      return itineraries;
    } catch (Exception e) {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
  }
Exemplo n.º 21
0
 public static JsonNode toJsonNode(Object obj) {
   return mapper.convertValue(obj, JsonNode.class);
 }
Exemplo n.º 22
0
 public static <T> T convertValue(Object object, TypeReference<T> typeReference) {
   return mapper.convertValue(object, typeReference);
 }
  /**
   * Gets the project milestone list view data with ajax.
   *
   * @return the result code.
   * @throws Exception if there is any error.
   * @since 1.1
   */
  public String getProjectMilestoneListData() throws Exception {
    try {

      List<Milestone> overdueMilestones =
          getMilestoneService()
              .getAll(
                  formData.getProjectId(),
                  Arrays.asList(new MilestoneStatus[] {MilestoneStatus.OVERDUE}),
                  SortOrder.ASCENDING);
      List<Milestone> upcomingMilestones =
          getMilestoneService()
              .getAll(
                  formData.getProjectId(),
                  Arrays.asList(new MilestoneStatus[] {MilestoneStatus.UPCOMING}),
                  SortOrder.ASCENDING);
      List<Milestone> completedMilestones =
          getMilestoneService()
              .getAll(
                  formData.getProjectId(),
                  Arrays.asList(new MilestoneStatus[] {MilestoneStatus.COMPLETED}),
                  SortOrder.DESCENDING);

      List<MilestoneContestDTO> milestoneContestAssociations =
          DataProvider.getMilestoneContestAssociations(
              formData.getProjectId(), 0, DirectUtils.getTCSubjectFromSession().getUserId());

      Map<Long, List<MilestoneContestDTO>> tempMapping =
          new HashMap<Long, List<MilestoneContestDTO>>();

      for (MilestoneContestDTO mcd : milestoneContestAssociations) {
        if (tempMapping.get(mcd.getMilestoneId()) == null) {
          tempMapping.put(mcd.getMilestoneId(), new ArrayList<MilestoneContestDTO>());
        }

        tempMapping.get(mcd.getMilestoneId()).add(mcd);
      }

      Map<String, List<ProjectMilestoneDTO>> result =
          new HashMap<String, List<ProjectMilestoneDTO>>();

      result.put("overdue", new ArrayList<ProjectMilestoneDTO>());
      result.put("upcoming", new ArrayList<ProjectMilestoneDTO>());
      result.put("completed", new ArrayList<ProjectMilestoneDTO>());

      for (Milestone m : overdueMilestones) {
        ProjectMilestoneDTO pmd = new ProjectMilestoneDTO();
        pmd.setMilestone(m);
        pmd.setContests(tempMapping.get(m.getId()));
        result.get("overdue").add(pmd);
      }

      for (Milestone m : upcomingMilestones) {
        ProjectMilestoneDTO pmd = new ProjectMilestoneDTO();
        pmd.setMilestone(m);
        pmd.setContests(tempMapping.get(m.getId()));
        result.get("upcoming").add(pmd);
      }

      for (Milestone m : completedMilestones) {
        ProjectMilestoneDTO pmd = new ProjectMilestoneDTO();
        pmd.setMilestone(m);
        pmd.setContests(tempMapping.get(m.getId()));
        result.get("completed").add(pmd);
      }

      ObjectMapper m = new ObjectMapper();

      setResult(m.convertValue(result, Map.class));

    } catch (Throwable e) {
      // set the error message into the ajax response
      if (getModel() != null) {
        setResult(e);
      }
      return ERROR;
    }
    return SUCCESS;
  }
  // no crud
  @RequestMapping(method = RequestMethod.POST, value = "/submitalert")
  public @ResponseBody void submitAlert(
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession session,
      @RequestBody Map<String, Object> map)
      throws InvocationException, AcServiceException {
    try {
      User user = getUser(request);
      String userId = getUserId(user);
      if (userId == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
      }

      AlertType type = AlertType.getAlertType((String) map.get("type"));

      ObjectMapper mapper = new ObjectMapper();

      Alert alert = null;
      String method = "";
      Map<String, Object> contentMap = (Map<String, Object>) map.get("content");
      switch (type) {
        case ACCIDENT:
          alert = mapper.convertValue(contentMap, AlertAccident.class);
          method = "submitAlertAccident";
          break;
        case DELAY:
          alert = mapper.convertValue(contentMap, AlertDelay.class);
          method = "submitAlertDelay";
          logger.info(
              "-"
                  + userId
                  + "~AppProsume~delay="
                  + ((AlertDelay) alert).getTransport().getAgencyId());
          break;
        case PARKING:
          alert = mapper.convertValue(contentMap, AlertParking.class);
          method = "submitAlertParking";
          break;
        case STRIKE:
          alert = mapper.convertValue(contentMap, AlertStrike.class);
          method = "submitAlertStrike";
          break;
      }

      alert.setType(type);
      alert.setCreatorId(userId);
      alert.setCreatorType(CreatorType.USER);

      Map<String, Object> pars = new HashMap<String, Object>();
      pars.put("newAlert", alert);
      // pars.put("userId", userId);
      domainClient.invokeDomainOperation(
          method,
          "smartcampus.services.journeyplanner.AlertFactory",
          "smartcampus.services.journeyplanner.AlertFactory.0",
          pars,
          userId,
          "vas_journeyplanner_subscriber");
    } catch (Exception e) {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
Exemplo n.º 25
0
 private void assertNoErrors(Map<String, String> fields) {
   if (fields.containsKey("error")) {
     JsonNode error = mapper.convertValue(fields, JsonNode.class);
     throw new DbAccessException(error.toString());
   }
 }
Exemplo n.º 26
0
 public static <T> T convertValue(Object object, Class<T> clazz) {
   return mapper.convertValue(object, clazz);
 }