@SuppressWarnings("deprecation")
  @GET
  @Path("/list/")
  @Produces("application/json")
  public JSONArray doGet(@QueryParam("ids") String paramIds) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    String[] ids = paramIds.split(",");

    JSONArray jsonMovies = new JSONArray();
    for (String id : ids) {
      Entity movieEntity;
      JSONObject movieToAdd = null;
      Query query = new Query("Movie").addFilter("redboxid", Query.FilterOperator.EQUAL, id);
      List<Entity> movieEntitiesArray =
          datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
      if (movieEntitiesArray.size() == 0) {
        // need to get the movie from the Redbox and then add to db
        movieEntity = getRedboxInfoAndAdd();
      } else {
        movieEntity = movieEntitiesArray.get(0);
      }

      try {
        // todo put the movie properties here
        movieToAdd.put("title", movieEntity.getProperty("title"));
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return jsonMovies;
  }
  @POST
  @Path("/addNewParentTestField")
  @Produces("text/plain")
  @Consumes(MediaType.APPLICATION_JSON)
  public String addNewParentField(JSONObject obj) {
    try {
      JSONArray data = obj.getJSONArray("parentfileds");
      Set<ParentTestFields> ParentFieldList = new HashSet<ParentTestFields>();
      for (int curr = 0; curr < data.length(); curr++) {
        ParentTestFields pf = new ParentTestFields();
        pf.setParentField_IDName("PF");
        pf.setParent_FieldName(data.getJSONObject(curr).getString("parent_FieldName"));
        // pf.setfTest_RangeID(testFieldsRangeDBDriver.getTestFieldRangeByID(Integer.parseInt(data.getJSONObject(curr).getString("fTest_RangeID"))));
        pf.setfTest_NameID(
            testNamesDBDriver.getTestNameByID(
                Integer.parseInt(data.getJSONObject(curr).getString("fTest_NameID"))));
        ParentFieldList.add(pf);
      }

      for (ParentTestFields pf : ParentFieldList) {
        parentfieldDBDriver.addNewParentTestField(pf);
      }

    } catch (JSONException e) {
      e.printStackTrace();
      return null;
    } catch (Exception e) {
      System.out.println(e.getMessage());
      return null;
    }
    return "TRUE";
  }
Esempio n. 3
0
  @Override
  public Contact checkIFPhoneNumberIsAContactOfUser(JSONObject data) {
    em = PersistenceManager.getEntityManagerFactory().createEntityManager();

    String phone = "";
    int userId = 0;
    try {
      phone = data.getString("phone");
      userId = data.getInt("userId");
    } catch (JSONException e) {
      e.printStackTrace();
    }

    try {
      return (Contact)
          em.createQuery(
                  "SELECT c FROM Contact c WHERE c.phone = '"
                      + phone
                      + "' AND c.user_owner.id = "
                      + userId)
              .getSingleResult();
    } catch (NoResultException e) {
      return null;
    }
  }
  /**
   * Get the URL of the file to download. This has not been modified from the original version.
   *
   * <p>For more information, please see: <a href=
   * "https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-portal-help#features">
   * https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-
   * portal-help#features</a>
   *
   * <p>Original code can be accessed at: <a href=
   * "https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip">
   * https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip </a>
   *
   * @see #login(String, String)
   * @see org.collegeboard.scoredwnld.client.FileInfo
   * @author CollegeBoard
   * @param accessToken Access token obtained from {@link #login(String, String)}
   * @param filePath File to download
   * @return FileInfo descriptor of file to download
   */
  private FileInfo getFileUrlByToken(String accessToken, String filePath) {

    Client client = getClient();
    WebResource webResource =
        client.resource(
            scoredwnldUrlRoot + "/pascoredwnld/file?tok=" + accessToken + "&filename=" + filePath);
    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
    if (response.getStatus() != 200) {
      throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    try {
      JSONObject json = new JSONObject(response.getEntity(String.class));
      FileInfo fileInfo = new FileInfo();
      fileInfo.setFileName(filePath);
      fileInfo.setFileUrl(String.valueOf(json.get("fileUrl")));
      return fileInfo;
    } catch (ClientHandlerException e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    } catch (UniformInterfaceException e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    } catch (JSONException e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    }

    return null;
  }
Esempio n. 5
0
  @PostConstruct
  public void listarGrupos() {

    JSONArray lista = null;
    try {
      JSONObject respuesta = new IGrupo().listarGrupos(sesion.getTokenId());

      lista = respuesta.getJSONArray("lista");
      listaGrupos.clear();
      if (lista != null) {
        int len = lista.length();
        for (int i = 0; i < len; i++) {
          try {
            JSONObject ob = lista.getJSONObject(i);
            JSONObject ob2 = ob.getJSONObject("grupo");
            listaGrupos.add(ob2.getString("nombre"));
          } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }

      } else {
        listaGrupos.clear();
      }

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  private ComboAvailableList() {
    this.playerCombos = new HashMap<>();
    try {
      JSONObject configs = new JSONObject(FilesTools.readFile(ConfigPath.comboAvailableList));

      Iterator iterator = configs.keys();
      while (iterator.hasNext()) {
        String name = (String) iterator.next();
        EGameObject player = EGameObject.getEnumByValue(name);
        if (player != EGameObject.NULL) {
          this.playerCombos.put(player, new ArrayList<>());
          JSONArray combos = configs.getJSONArray(name);
          for (int i = 0; i < combos.length(); ++i) {
            this.playerCombos
                .get(player)
                .add(
                    new Pair<>(
                        combos.getJSONObject(i).getString("name"),
                        combos.getJSONObject(i).getString("combo")));
          }
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
Esempio n. 7
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Long id = Long.valueOf(request.getParameter("id"));
    Contact contact = contactService.getById(id);

    HttpSession session = request.getSession();

    if (contact != null) {
      contactService.remove(id);

      try {
        conversationService.removeConversationByUserAndContact(
            new JSONObject()
                .put("userId", ((User) session.getAttribute("user")).getId())
                .put("phoneNumber", contact.getPhone()));
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      response.sendRedirect(request.getContextPath() + "/auth/contact");
    } else {
      session.setAttribute(Alert.PRMTR_ERROR, "The contact doesn't exist !");
      request.setAttribute("pageTitle", "Contacts");
      request.getRequestDispatcher("/auth/contact.jsp").forward(request, response);
    }
  }
  @GET
  @Path("/registerCoupons/{id}&{couponcode}&{allocated}&{used}/")
  @Produces(MediaType.APPLICATION_JSON)
  public JSONObject registerCoupons(
      @PathParam("id") String id,
      @PathParam("couponcode") String couponcode,
      @PathParam("allocated") String allocated,
      @PathParam("used") String used) {
    JSONObject res = new JSONObject();
    System.out.println("Inside registerCoupons ");

    Registration registration = new Registration();
    int response = registration.registerCoupons(id, couponcode, allocated, used);
    try {
      if (response == 0) {
        res.append("result", "200");
        res.append("response", "Successfully Registered");
      } else {
        res.append("result", "400");
        res.append("response", "Not Registered");
      }
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return res;
  }
Esempio n. 9
0
  public void registrarUsuario(ActionEvent ae) {

    try {
      JSONObject respuesta =
          new IUsuario()
              .registrarUsuario(
                  sesion.getTokenId(),
                  sesion.getMail(),
                  nombre,
                  apellido,
                  telefono,
                  interno,
                  contrasena);

      String status = respuesta.getString("status");
      if (status.equals("2")) {
        sesion.setNuevoUsuario(false);
      }

      System.out.println(sesion.isNuevoUsuario());

      String mensaje = respuesta.getString("mensaje");
      FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(mensaje, null));

    } catch (JSONException e) {
      e.printStackTrace();
      System.out.println("ERROR JSOOOOOOOOOOOON");
    }
  }
Esempio n. 10
0
 /** Simple méthode utilitaire. */
 private static String formatJsonString(String json) {
   try {
     return new JSONObject(json).toString(2);
   } catch (JSONException ex) {
     throw new RuntimeException(ex.getMessage(), ex);
   }
 }
Esempio n. 11
0
  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  public Response addUpdateListItem(InputStream incomingData) {
    StringBuilder listBuilder = new StringBuilder();
    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
      String line = null;
      while ((line = in.readLine()) != null) {
        listBuilder.append(line);
      }
    } catch (Exception e) {
      System.out.println("Error Parsing :- ");
    }

    try {
      JSONObject json = new JSONObject(listBuilder.toString());
      Iterator<String> iterator = json.keys();
      ListItem item =
          new ListItem(
              (String) json.get(iterator.next()),
              (String) json.get(iterator.next()),
              Boolean.parseBoolean((String) json.get(iterator.next())));
      int index = list.indexOf(item);
      item = list.get(index);
      list.remove(index);
      item.setTitle((String) json.get(iterator.next()));
      item.setBody((String) json.get(iterator.next()));
      list.add(index, item);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    // return HTTP response 200 in case of success
    return Response.status(200).entity(listBuilder.toString()).build();
  }
Esempio n. 12
0
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  public Response saveListItem(InputStream incomingData) {
    StringBuilder listBuilder = new StringBuilder();
    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
      String line = null;
      while ((line = in.readLine()) != null) {
        listBuilder.append(line);
      }
    } catch (Exception e) {
      System.out.println("Error Parsing: - ");
    }

    try {
      JSONObject json = new JSONObject(listBuilder.toString());
      Iterator<String> iterator = json.keys();
      if (list == null) {
        list = new ArrayList<ListItem>();
      }
      ListItem item =
          new ListItem(
              (String) json.get(iterator.next()),
              (String) json.get(iterator.next()),
              (Boolean) json.get(iterator.next()));
      list.add(item);
    } catch (JSONException e) {
      e.printStackTrace();
      return Response.status(500).entity(listBuilder.toString()).build();
    }
    // return HTTP response 200 in case of success
    return Response.status(200).entity(listBuilder.toString()).build();
  }
Esempio n. 13
0
  public List<NombreMail> listarAdministradores() {

    JSONObject respuesta = new IGrupo().listarAdministradores(sesion.getTokenId());

    JSONArray admins = null;
    listaAdministradores.clear();
    try {

      admins = respuesta.getJSONArray("lista");
      if (admins != null) {

        for (int i = 0; i < admins.length(); i++) {

          JSONObject ob = admins.getJSONObject(i);
          NombreMail b = new NombreMail();
          b.setMail(ob.getString("correo"));
          b.setNombre(ob.getString("nombre") + " " + ob.getString("apellido"));
          listaAdministradores.add(b);
        }
      }
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return listaAdministradores;
  }
    @Override
    public void processProperty(
        ISchemaType type,
        ISchemaProperty prop,
        ISerializationNode childNode,
        Set<String> processedTypes) {

      if (this.structureType == StructureType.COLLECTION) {
        int l = this.array.length();
        for (int i = 0; i < l; i++) {
          JSONObject item;
          try {
            item = (JSONObject) this.array.get(i);
            appendProperty(item, type, prop, childNode);
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }
      } else if (this.structureType == StructureType.MAP) {
        try {
          for (Iterator<?> iter = this.object.keys(); iter.hasNext(); ) {
            String key = iter.next().toString();
            JSONObject value = this.object.getJSONObject(key);
            appendProperty(value, type, prop, childNode);
          }
        } catch (JSONException e) {
          e.printStackTrace();
        }
      } else {
        appendProperty(this.object, type, prop, childNode);
      }
    }
Esempio n. 15
0
  public void guardarCambiosGrupo() {

    JSONArray lista = new JSONArray();

    for (int i = 0; i < listaTecnicosGrupo.size(); i++) {
      lista.put(listaTecnicosGrupo.get(i).getMail());
    }

    JSONObject respuesta =
        new IGrupo()
            .modificiarGrupo(
                sesion.getTokenId(),
                grupoSeleccionado,
                nuevoNombreGrupo,
                lista,
                parsearMail(nuevoAdministrador));
    try {
      FacesMessage msg;
      if (respuesta.getInt("status") == 2) {
        msg = new FacesMessage("Grupo modificado con exito", "");
        listarGrupos();
      } else msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error al modificar grupo.", "");

      FacesContext.getCurrentInstance().addMessage(null, msg);

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 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();
   }
 }
  /**
   * ****************************************************************
   *
   * <p>REGISTRATION URL FOR VARIOUS USERS 1. Kandy Details 2. Rewards
   *
   * <p>****************************************************************
   */
  @GET
  @Path("/registerKandy/{id}&{username}&{password}&{key}&{provider}&{uid}/")
  @Produces(MediaType.APPLICATION_JSON)
  public JSONObject registerEndUser(
      @PathParam("id") String id,
      @PathParam("username") String username,
      @PathParam("password") String password,
      @PathParam("key") String key,
      @PathParam("provider") String provider,
      @PathParam("uid") String uid) {
    JSONObject res = new JSONObject();
    System.out.println("Inside registerKandy Helper");

    Registration registration = new Registration();
    int response = registration.registerKandy(id, username, password, key, provider, uid);
    try {
      if (response == 0) {
        res.append("result", "200");
        res.append("response", "Successfully Registered");
      } else {
        res.append("result", "400");
        res.append("response", "Not Registered");
      }
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return res;
  }
Esempio n. 18
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String conversationId = request.getParameter("id");

    try {
      List<SMS> sms =
          smsService.getAllSMSByConversation(
              new JSONObject().put("conversationId", conversationId));
      request.setAttribute("sms", sms);

      Conversation conversation =
          conversationService.getConversationById(
              new JSONObject().put("conversationId", Integer.parseInt(conversationId)));
      request.setAttribute("conversationNumber", conversation.getContactName());

      Contact contact =
          contactService.getContactByPhoneAndUser(
              new JSONObject()
                  .put("phone", conversation.getContactName())
                  .put("userId", ((User) request.getSession().getAttribute("user")).getId()));
      if (contact != null)
        conversation.setContactName(contact.getFirstName() + " " + contact.getLastName());

      request.setAttribute("conversation", conversation);
    } catch (JSONException e) {
      e.printStackTrace();
    }

    request.setAttribute("pageTitle", "Conversation");
    request.getRequestDispatcher("/auth/conversation.jsp").forward(request, response);
  }
 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);
   }
 }
 public void log(String msg, String level, String stack) throws Log4AllException {
   JSONObject jsonData = null;
   try {
     jsonData = toJSON(msg, level, stack, new Date());
     log(jsonData);
   } catch (JSONException e) {
     throw new Log4AllException(e.getMessage(), e);
   }
 }
    public Node(ISchemaType type, ISchemaProperty prop) {

      this.structureType = prop != null ? prop.getStructureType() : type.getParentStructureType();
      if (structureType == StructureType.COLLECTION) {
        this.array = new JSONArray();
        if (type.isComplex()) {
          array.put(new JSONObject());
          array.put(new JSONObject());
        } else {
          Object defaultValue =
              prop != null
                  ? DefaultValueFactory.getDefaultValue(prop)
                  : DefaultValueFactory.getDefaultValue(type);
          array.put(defaultValue);
          array.put(defaultValue);
        }
      } else if (structureType == StructureType.MAP) {
        this.object = new JSONObject();

        ISchemaType keyType = SimpleType.STRING;
        ISchemaType valueType =
            new TypeModelImpl("Object", "java.lang.Object", null, StructureType.COMMON);
        if (prop != null && prop instanceof IMapSchemaProperty) {
          keyType = ((IMapSchemaProperty) prop).getKeyType();
          valueType = ((IMapSchemaProperty) prop).getValueType();
          if (!keyType.getClassName().equals(SimpleType.STRING.getClassName())) {
            StringBuilder bld =
                new StringBuilder("Invalid map key type. Only String is available as key type.");
            if (type != null) {
              bld.append(" Type: " + type.getClassQualifiedName());
            }
            if (prop != null) {
              bld.append(" Property: " + prop.getName());
            }
            throw new IllegalArgumentException(bld.toString());
          }
        }
        String key = DefaultValueFactory.getDefaultValue(keyType).toString();
        try {
          if (valueType.isComplex()) {
            this.object.put(key + "_1", new JSONObject());
            this.object.put(key + "_2", new JSONObject());
          } else {
            Object defaultValue = DefaultValueFactory.getDefaultValue(valueType);
            this.object.put(key + "_1", defaultValue);
            this.object.put(key + "_2", defaultValue);
          }
        } catch (JSONException e) {
          e.printStackTrace();
        }
      } else if (type.isComplex()) {
        this.object = new JSONObject();
      }
    }
Esempio n. 22
0
 public void refreshPhotonInfo() {
   if (isPhotonActive) {
     System.out.println(this.port + ": Updating photon");
     String photonJson = requestSender.findSpark();
     try {
       photon = new JSONObject(photonJson);
     } catch (JSONException e) {
       e.printStackTrace();
     }
   }
 }
Esempio n. 23
0
 @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());
   }
 }
Esempio n. 24
0
 private List<String> mapTagsField(String tags) {
   List<String> result = new ArrayList<String>();
   if (StringUtil.isNotEmpty(tags)) {
     try {
       JSONArray jsArr = new JSONArray(tags);
       for (int i = 0; i < jsArr.length(); i++) {
         result.add(jsArr.getString(i));
       }
     } catch (JSONException e) {
       e.printStackTrace();
     }
   }
   return result;
 }
 @Override
 public JSONObject deserialize(JsonParser jp, DeserializationContext ctxt)
     throws IOException, JsonProcessingException {
   JSONObject ob = new JSONObject();
   JsonToken t = jp.getCurrentToken();
   if (t == JsonToken.START_OBJECT) {
     t = jp.nextToken();
   }
   for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
     String fieldName = jp.getCurrentName();
     t = jp.nextToken();
     try {
       switch (t) {
         case START_ARRAY:
           ob.put(fieldName, JSONArrayDeserializer.instance.deserialize(jp, ctxt));
           continue;
         case START_OBJECT:
           ob.put(fieldName, deserialize(jp, ctxt));
           continue;
         case VALUE_STRING:
           ob.put(fieldName, jp.getText());
           continue;
         case VALUE_NULL:
           ob.put(fieldName, JSONObject.NULL);
           continue;
         case VALUE_TRUE:
           ob.put(fieldName, Boolean.TRUE);
           continue;
         case VALUE_FALSE:
           ob.put(fieldName, Boolean.FALSE);
           continue;
         case VALUE_NUMBER_INT:
           ob.put(fieldName, jp.getNumberValue());
           continue;
         case VALUE_NUMBER_FLOAT:
           ob.put(fieldName, jp.getNumberValue());
           continue;
         case VALUE_EMBEDDED_OBJECT:
           ob.put(fieldName, jp.getEmbeddedObject());
           continue;
       }
     } catch (JSONException e) {
       throw ctxt.mappingException("Failed to construct JSONObject: " + e.getMessage());
     }
     throw ctxt.mappingException("Urecognized or unsupported JsonToken type: " + t);
   }
   return ob;
 }
Esempio n. 26
0
  public void cargarDatosGrupo() {

    JSONObject respuesta =
        new IGrupo().listarMiembrosDeGrupo(sesion.getTokenId(), grupoSeleccionado);
    JSONObject respuesta2 =
        new IGrupo().tecnicosFueraDelGrupo(sesion.getTokenId(), grupoSeleccionado);
    try {

      if (respuesta.has("jefe")) {
        JSONObject objetoJefe = respuesta.getJSONObject("jefe");
        nuevoAdministrador =
            objetoJefe.getString("nombre") + " " + objetoJefe.getString("apellido");
        if (!objetoJefe.getString("nombre").equals(""))
          nuevoAdministrador = nuevoAdministrador + " - ";
        nuevoAdministrador = nuevoAdministrador + objetoJefe.getString("correo");
      } else nuevoAdministrador = "No tiene administrador.";

      listaTecnicosGrupo.clear();
      JSONArray objetoIntegantes = respuesta.getJSONArray("grupo");
      if (objetoIntegantes != null) {
        for (int i = 0; i < objetoIntegantes.length(); i++) {
          JSONObject ob = objetoIntegantes.getJSONObject(i);
          NombreMail b = new NombreMail();
          b.setMail(ob.getString("correo"));
          b.setNombre(ob.getString("nombre") + " " + ob.getString("apellido"));
          listaTecnicosGrupo.add(b);
        }
      }

      listaRestoTecnicos.clear();
      JSONArray objetoTecnicos = respuesta2.getJSONArray("Tecnicos");

      if (objetoTecnicos != null) {
        for (int i = 0; i < objetoTecnicos.length(); i++) {
          JSONObject ob = objetoTecnicos.getJSONObject(i);
          NombreMail b = new NombreMail();
          b.setMail(ob.getString("correo"));
          b.setNombre(ob.getString("nombre") + " " + ob.getString("apellido"));
          listaRestoTecnicos.add(b);
        }
      }

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Esempio n. 27
0
 // Finds the responsible node for the photon and updates it and the successor of it
 public void findResponsibleNode() {
   String photonJson = requestSender.findSpark();
   try {
     JSONObject temp = new JSONObject(photonJson);
     JSONObject temp2 = temp.getJSONObject("coreInfo");
     String deviceID = temp2.getString("deviceID");
     int convertedID = Key.generate16BitsKey(deviceID);
     NodeInfo responsible = findSuccessor(convertedID);
     // NodeInfo resposibleSuccessor = requestSender.getNodeSuccessor(responsible);
     requestSender.updatePhoton(responsible);
     // requestSender.updatePhoton(resposibleSuccessor);
     System.out.println("PhotonID: " + convertedID);
     System.out.println("Responsible is:\n" + responsible.getID());
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
Esempio n. 28
0
 {
   ByteArrayOutputStream oStream = new ByteArrayOutputStream();
   PrintStream stream = new PrintStream(oStream);
   JourneyPattern jp = new JourneyPattern();
   ObjectReference objectRef = new ObjectReference(jp);
   objectRef.print(stream, new StringBuilder(), 1, true);
   String text = oStream.toString();
   JSONObject res = null;
   try {
     res = new JSONObject(text);
     Assert.assertEquals(
         res.getString("type"), TYPE.journey_pattern, "wrong object reference type");
     Assert.assertEquals(res.getString("id"), jp.getObjectId(), "wrong object referenced id");
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
Esempio n. 29
0
 // Updates the photon of this node
 @PUT
 @Path("/update-photon/")
 public Response updatePhoton(NodeInfo target) {
   String photonJson = requestSender.findSpark();
   try {
     photon = new JSONObject(photonJson);
     JSONObject coreInfo = photon.getJSONObject("coreInfo");
     String deviceID = coreInfo.getString("deviceID");
     photonId = Key.generate16BitsKey(deviceID);
     System.out.println("deviceID returned: " + deviceID);
     System.out.println("deviceID int returned: " + photonId);
     isPhotonActive = true;
     createPhotonUpdateTimer();
   } catch (JSONException e) {
     e.printStackTrace();
   }
   // System.out.println("Spark returned:\n" + photonJson);
   return Response.status(200).entity(photon).build();
 }
Esempio n. 30
0
  private void generateResults(MessageContext messageContext, boolean resultStatus) {
    ResultPayloadCreater resultPayload = new ResultPayloadCreater();

    String responce = "<result><success>" + resultStatus + "</success></result>";

    try {
      OMElement element = resultPayload.performSearchMessages(responce);
      resultPayload.preparePayload(messageContext, element);

    } catch (XMLStreamException e) {
      log.error(e.getMessage());
      handleException(e.getMessage(), messageContext);
    } catch (IOException e) {
      log.error(e.getMessage());
      handleException(e.getMessage(), messageContext);
    } catch (JSONException e) {
      log.error(e.getMessage());
      handleException(e.getMessage(), messageContext);
    }
  }