public void handleDirections(Update update) throws InvalidObjectException {
    Message message = update.getMessage();
    if (message != null && message.hasText()) {
      if (languageMessages.contains(message.getFrom().getId())) {
        onLanguageSelected(message);
      } else {
        String language =
            DatabaseManager.getInstance().getUserLanguage(update.getMessage().getFrom().getId());
        if (message.getText().startsWith(Commands.setLanguageCommand)) {
          onSetLanguageCommand(message, language);
        } else if (message.getText().startsWith(Commands.startDirectionCommand)) {
          onStartdirectionsCommand(message, language);
        } else if ((message.getText().startsWith(Commands.help)
                || (message.getText().startsWith(Commands.startCommand)
                    || !message.isGroupMessage()))
            && DatabaseManager.getInstance().getUserDestinationStatus(message.getFrom().getId())
                == -1) {
          sendHelpMessage(message, language);
        } else if (!message.getText().startsWith("/")) {
          if (DatabaseManager.getInstance().getUserDestinationStatus(message.getFrom().getId())
                  == WATING_ORIGIN_STATUS
              && message.hasReplayMessage()
              && DatabaseManager.getInstance()
                      .getUserDestinationMessageId(message.getFrom().getId())
                  == message.getReplyToMessage().getMessageId()) {
            onOriginReceived(message, language);

          } else if (DatabaseManager.getInstance()
                      .getUserDestinationStatus(message.getFrom().getId())
                  == WATING_DESTINY_STATUS
              && message.hasReplayMessage()
              && DatabaseManager.getInstance()
                      .getUserDestinationMessageId(message.getFrom().getId())
                  == message.getReplyToMessage().getMessageId()) {
            onDestinationReceived(message, language);
          } else if (!message.hasReplayMessage()) {
            if (DatabaseManager.getInstance().getUserDestinationStatus(message.getFrom().getId())
                == -1) {
              sendHelpMessage(message, language);
            } else {
              SendMessage sendMessageRequest = new SendMessage();
              sendMessageRequest.setText(
                  LocalisationService.getInstance().getString("youNeedReplyDirections", language));
              sendMessageRequest.setChatId(message.getChatId().toString());
              SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
            }
          }
        }
      }
    }
  }
 public void addMessage(Message message) {
   data.add(message);
   Message last = data.get(data.size() - 1);
   if (last.getText().length() > MESSAGE_LENGTH) {
     System.out.println(RED + "WARNING: long message (more than 140 symbols)." + END);
   }
   System.out.println("Successfully added: " + last.getFormattedMessage());
   log("ADD " + last.getId() + " " + last.getAuthor() + " " + last.getText());
   saveMessagesToJsonFile(MESSAGES_EXTERNAL_STORAGE);
 }
Exemplo n.º 3
0
  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");

    Message message = (Message) context.getBean("message");

    logger.info("Message is: {}", message.getText());
  }
  private void onDestinationReceived(Message message, String language) {
    String origin = DatabaseManager.getInstance().getUserOrigin(message.getFrom().getId());
    String destiny = message.getText();
    List<String> directions =
        DirectionsService.getInstance().getDirections(origin, destiny, language);
    SendMessage sendMessageRequest = new SendMessage();
    sendMessageRequest.setChatId(message.getChatId().toString());
    ReplyKeyboardHide replyKeyboardHide = new ReplyKeyboardHide();
    replyKeyboardHide.setSelective(true);
    sendMessageRequest.setReplayMarkup(replyKeyboardHide);
    sendMessageRequest.setReplayToMessageId(message.getMessageId());
    Message sentMessage = null;
    for (String direction : directions) {
      sendMessageRequest.setText(direction);
      SenderHelper.SendApiMethodAsync(
          sendMessageRequest,
          TOKEN,
          new SentCallback<Message>() {
            @Override
            public void onResult(BotApiMethod<Message> method, JSONObject jsonObject) {
              Message sentMessage = method.deserializeResponse(jsonObject);
              if (sentMessage != null) {
                DatabaseManager.getInstance().deleteUserForDirections(message.getFrom().getId());
              }
            }

            @Override
            public void onError(BotApiMethod<Message> method, JSONObject jsonObject) {}
          });
    }
  }
Exemplo n.º 5
0
 /**
  * Waits for a string message from the board. Maximum wait time is 2s.
  *
  * @return The message
  * @throws InterruptedException
  */
 public String getMessage() throws InterruptedException {
   final String mn = "getMessage";
   //		logger.logp(Level.INFO, this.getClass().getName(), mn,
   //				"> synchronizing");
   System.out.println("--- getMessage() ---");
   synchronized (receivedMessage) {
     //			logger.logp(Level.INFO, this.getClass().getName(), mn,
     //					"synchronized");
     long start = System.currentTimeMillis();
     try {
       receivedMessage.wait(TIMEOUT);
     } catch (InterruptedException e) {
       e.printStackTrace();
       throw e;
     }
     long passed = System.currentTimeMillis() - start;
     if (passed >= TIMEOUT) {
       String msg = "Timeout of " + TIMEOUT + " reached";
       //				logger.logp(Level.WARNING, this.getClass().getName(), mn, msg);
       receivedMessage.setText(msg);
     }
   }
   String retval = receivedMessage.getText();
   receivedMessage.setText("");
   //		logger.logp(Level.INFO, this.getClass().getName(), mn, "< " + retval);
   return retval;
 }
Exemplo n.º 6
0
  public void runHibernate() {
    // ############################################################################
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = session.beginTransaction();
    Message message = new Message("Hello World");
    session.save(message);
    tx.commit();
    session.close();
    // ############################################################################
    Session secondSession = HibernateUtil.getSessionFactory().openSession();
    Transaction secondTransaction = secondSession.beginTransaction();
    List messages = secondSession.createQuery("from Message m order by m.text asc").list();
    System.out.println(messages.size() + " message(s) found:");
    for (Iterator iter = messages.iterator(); iter.hasNext(); ) {
      Message loadedMsg = (Message) iter.next();
      System.out.println(loadedMsg.getText());
    }
    secondTransaction.commit();
    secondSession.close();
    // ############################################################################
    Session thirdSession = HibernateUtil.getSessionFactory().openSession();
    Transaction thirdTransaction = thirdSession.beginTransaction();
    // message.getId() holds the identifier value of the first message
    Message loadedMessage = (Message) thirdSession.get(Message.class, message.getId());
    loadedMessage.setText("Greetings Earthling");
    loadedMessage.setNextMessage(new Message("Take me to your leader (please)"));
    thirdTransaction.commit();
    thirdSession.close();
    // ############################################################################
    // Final unit of work (just repeat the query)
    // TODO: You can move this query into the thirdSession before the
    // commit, makes more sense!
    Session fourthSession = HibernateUtil.getSessionFactory().openSession();
    Transaction fourthTransaction = fourthSession.beginTransaction();
    messages = fourthSession.createQuery("from Message m order by m.text asc").list();
    System.out.println(messages.size() + " message(s) found:");
    for (Iterator iter = messages.iterator(); iter.hasNext(); ) {
      Message loadedMsg = (Message) iter.next();
      System.out.println(loadedMsg.getText());
    }
    fourthTransaction.commit();
    fourthSession.close();

    // Shutting down the application
    HibernateUtil.shutdown();
  }
Exemplo n.º 7
0
 @Transient
 public String getText(Locale locale) {
   if (messages != null) {
     Message message = messages.get(locale);
     if (message != null) {
       return message.getText();
     }
   }
   return null;
 }
Exemplo n.º 8
0
 private void emitDefault(TypeElement baseType, Log log, Message message) {
   TypeElement rootEnclosing = Utils.findRootEnclosingType(getMessageElement());
   if (rootEnclosing != null
       && Utils.typeEquals(baseType.asType(), rootEnclosing.asType())
       && this == message.getOriginalContainer()) {
     log.message(
         message.getKind(),
         getMessageElement(),
         getMessageAnnotation(),
         getMessageAnnotationValue(),
         message.getText());
   } else {
     MessageContainer original = message.getOriginalContainer();
     log.message(
         message.getKind(),
         baseType,
         null,
         null,
         wrapText(
             original.getMessageElement(), original.getMessageAnnotation(), message.getText()));
   }
 }
Exemplo n.º 9
0
  public void addMessage(Message msg) {
    String query = "INSERT INTO messages(text, author, timestamp, isDeleted) values(?, ?, ?, ?)";

    try {
      PreparedStatement statement = connection.prepareStatement(query);
      statement.setString(1, msg.getText());
      statement.setString(2, msg.getAuthor());
      statement.setString(3, msg.getStingTimestamp());
      statement.setInt(4, 0);
      statement.execute();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
 private void searchByKeyword(String keyword) throws Exception {
   System.out.println("BY KEYWORD: " + keyword);
   int counter = 0;
   for (Message i : data) {
     if (i.getText().contains(keyword)) {
       System.out.println(i.getFormattedMessage());
       counter++;
     }
   }
   if (counter == 0) {
     System.out.println("nothing found");
     log("SEARCH by keyword: " + keyword + ", nothing found");
   } else {
     log("SEARCH by keyword: " + keyword + ", found: " + counter);
   }
 }
 private void searchByRegex(String regex) throws Exception {
   System.out.println("BY REGULAR EXPRESSION: " + regex);
   int counter = 0;
   for (Message i : data) {
     if (Pattern.matches(regex, i.getText())) {
       System.out.println(i.getFormattedMessage());
       counter++;
     }
   }
   if (counter == 0) {
     System.out.println("nothing found");
     log("SEARCH by regex: " + regex + ", nothing found");
   } else {
     log("SEARCH by regex: " + regex + ", found: " + counter);
   }
 }
 private void onLanguageSelected(Message message) throws InvalidObjectException {
   String[] parts = message.getText().split("-->", 2);
   SendMessage sendMessageRequest = new SendMessage();
   sendMessageRequest.setChatId(message.getChatId().toString());
   if (LocalisationService.getInstance().getSupportedLanguages().containsKey(parts[0].trim())) {
     DatabaseManager.getInstance().putUserLanguage(message.getFrom().getId(), parts[0].trim());
     sendMessageRequest.setText(
         LocalisationService.getInstance().getString("languageModified", parts[0].trim()));
   } else {
     sendMessageRequest.setText(LocalisationService.getInstance().getString("errorLanguage"));
   }
   sendMessageRequest.setReplayToMessageId(message.getMessageId());
   ReplyKeyboardHide replyKeyboardHide = new ReplyKeyboardHide();
   replyKeyboardHide.setHideKeyboard(true);
   replyKeyboardHide.setSelective(true);
   sendMessageRequest.setReplayMarkup(replyKeyboardHide);
   SenderHelper.SendApiMethod(sendMessageRequest, TOKEN);
   languageMessages.remove(message.getFrom().getId());
 }
Exemplo n.º 13
0
  @TargetApi(Build.VERSION_CODES.KITKAT)
  protected JSONObject doInBackground(Message... params) {
    JSONObject jsonResponse = new JSONObject();
    try {
      // on ouvre la connexion au site
      URL url = new URL(LOGIN_URL);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("POST");

      // on recupere le message
      // Log.d("id prof ", Integer.toString(message.getidProf()));
      message = params[0];
      String urlParameters =
          "idUser="******"&idGroupe="
              + message.getNbGrp()
              + "&message="
              + message.getText();

      byte[] postData = urlParameters.getBytes();
      connection.setRequestProperty("Content-Length", "" + postData.length);

      try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
        wr.write(postData);
      }

      connection.connect();

      // decode response
      InputStream is = new BufferedInputStream(connection.getInputStream());
      jsonResponse = new JSONObject(convertStreamToString(is));

    } catch (IOException e) {
      Log.e("IOException", "Error");
    } catch (JSONException e) {
      Log.e("JSONException1", jsonResponse.toString());
    }
    return jsonResponse;
  }
Exemplo n.º 14
0
 protected void onPostExecute(JSONObject result) {
   try {
     // check if connection status is OK
     int loginOK = result.getInt(FLAG_SUCCESS);
     if (loginOK != 0) {
       Intent intent = new Intent(activity, MainActivity.class);
       intent.putExtra("SUCCESS", true);
       activity.startActivity(intent);
       activity.finish();
       Log.d("send", "success");
     } else {
       Intent intent = new Intent(activity, CreateMessage.class);
       intent.putExtra("SUCCESS", false);
       intent.putExtra("MESSAGEMES", message.getText());
       intent.putExtra("MESSAGEGP", message.getNbGrp());
       activity.startActivity(intent);
       Log.d("send", "fail");
     }
   } catch (JSONException e) {
     Log.e("JSONException2", "Error2");
   }
 }
Exemplo n.º 15
0
  public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;

    if (row == null) {
      LayoutInflater inflater =
          (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      row = inflater.inflate(R.layout.activity_chat_singlemessage, parent, false);
    }

    singleMessageContainer = (LinearLayout) row.findViewById(R.id.wholeContainer);
    singleMessageContent = (LinearLayout) row.findViewById(R.id.singleMessageContent);
    Message chatMessageObj = getItem(position);
    chatText = (TextView) row.findViewById(R.id.singleMessage);
    chatText.setText(chatMessageObj.getText());
    //		chatText.setBackgroundResource(chatMessageObj.left ? R.drawable.bubble_b :
    // R.drawable.bubble_a_old);

    chatText = (TextView) row.findViewById(R.id.singleMessageTime);
    //		getChangeDate(chatMessageObj.getDate());

    chatText.setText(
        chatMessageObj.getDate().split(" ")[1]
            + " "
            + chatMessageObj.getDate()
                .split(" ")[2]); // getChangeDate(chatMessageObj.getDate())[0]);

    chatText = (TextView) row.findViewById(R.id.singleMessageDate);
    //		getChangeDate(chatMessageObj.getDate());
    chatText.setText(
        chatMessageObj.getDate().split(" ")[0]); // getChangeDate(chatMessageObj.getDate())[1]);

    singleMessageContent.setBackgroundResource(
        chatMessageObj.left ? R.drawable.bubble_b : R.drawable.bubble_a_old);
    singleMessageContainer.setGravity(chatMessageObj.left ? Gravity.LEFT : Gravity.RIGHT);
    return row;
  }
Exemplo n.º 16
0
  public String insertMessage(Message message) throws SQLException {
    String r = "New  message inserted!";

    if (isFriend(
        message.getSender(),
        message.getReceiver())) { // Check if the sender and receiver are friends
      try {
        // creates a SQL Statement object in order to execute the SQL insert command
        stmt = conn.createStatement();
        stmt.execute(
            "INSERT INTO MESSAGES (Sender, Receiver, Text, DateMsg, TimeMsg, IsDelivered ) "
                + "VALUES ("
                + getProfileID(message.getSender())
                + ", "
                + getProfileID(message.getReceiver())
                + ", '"
                + message.getText()
                + "' , '"
                + message.getDateMsg()
                + "' , '"
                + message.getTimeMsg()
                + "',"
                + message.isDelivered()
                + ")");
        stmt.close();
        // System.out.println("Requête executée");
      } catch (SQLException e) {
        // System.err.println(e.toString());
        r = e.toString();
        throw e;
      }
      return r;
    } else {
      return "WARNING : Can't insert message in database : the sender and receiver are not friends !";
    }
  }
Exemplo n.º 17
0
 @Transient
 public String getDefaultText() {
   Message message = getDefaultMessage();
   return message != null ? message.getText() : null;
 }
Exemplo n.º 18
0
 // private utility method to create exception
 private ParserException createException(Message message, Object... params) {
   final String description = message.getText(params);
   return ParserException.create(description, this.line);
 }
 // ***************************************
 // Private methods
 // ***************************************
 private void displayResponse(Message response) {
   Toast.makeText(this, response.getText(), Toast.LENGTH_LONG).show();
 }