I am trying to send sms text in my mvc3 application to an sms gateway a but I get error in my application that
"An object reference is required for the non-static field, method, or
property 'UrWeb.SMS.send(string)'"
Reference Controller
SMS.send(ViewBag.Message);
SMS.cs
private const string _user = "XXX";
private const string _pass = "XXX";
private const string _url = "http://sms.com/api/http.php";
private const string Phone="000000000";
public SMS(string _user, string _pass, string _url)
{
user = _user;
pass = _pass;
url = _url;
}
public string send(string Phone, string Message)
{
string strData = SMSGData(Phone, Phone, Message);
return SendSms(url, strData);
}
.........
Any help in this direction will be highly appreciated
Make your method static
public static string send(string Phone, string Message)
{
....
Related
I am working on a spring boot project, I have a customer model which consists of properties, including image paths which I am storing in the file system or folder and uploading the entire form with image paths in DB, I have successfully implemented my target task however I was wondering if there is a better and nicer way to achieve this, your answers, comments, and feedbacks are appreciated here is my code
Customer model:
public class Customer {
private String contactMode = "Mobile Number";
#Pattern(regexp ="(251|0)[0-9]{9}" , message = "Invalid phone number")
private String phoneNumber; // phone number
private String identityType = "101-ID [0]";
#NotNull(message = "ID number is required")
private String idNumber;
private String countryOfIssue = "XXXXXXX";
#NotNull(message = "Issue date is required")
#PastOrPresent(message = "Issue date cannot be future date")
private Date issueDate;
#Future(message = "Expiry date cannot be in the past or present")
#NotNull(message = "Expiry date is required")
private Date expiryDate;
// storing customerImage , customerID and customerSignature paths in DB
private String customerImage;
private String customerID;
private String customerSignature;
}
Customer Service:
private String path = "C:\Users\User\Desktop\docs\uploaded_files\";
public Customer saveCustomer(Customer customer, MultipartFile customerImage, MultipartFile customerID,
MultipartFile customerSignature) throws Exception {
final String PATH = path + customer.getContactDetail();
Customer phoneNumberExists = customerRepository.findByContactDetail(customer.getContactDetail());
byte[] imageBytes = customerImage.getBytes();
byte[] idBytes = customerID.getBytes();
byte[] signatureBytes = customerSignature.getBytes();
Path customerImagePath = Paths.get
(PATH + "_photo_" + customerImage.getOriginalFilename());
Files.write(customerImagePath, imageBytes);
Path customerIDPath =
Paths.get(PATH + "_ID_" + customerID.getOriginalFilename());
Files.write(customerIDPath, idBytes);
Path customerSignaturePath =
Paths.get(PATH + "_Sign_" + customerSignature.getOriginalFilename() + "");
Files.write(customerSignaturePath, signatureBytes);
if (phoneNumberExists != null) {
throw new PhoneNumberTakenException("Phone number is taken ");
}
customer.setAge(new Date().getYear() - customer.getDateOfBirth().getYear());
customer.setCustomerImage(String.valueOf(customerImagePath));
customer.setCustomerID(String.valueOf(customerIDPath));
customer.setCustomerSignature(String.valueOf(customerSignaturePath));
customer.setFromDate(LocalDate.now());
customer.setStatus(Customer.Status.Submitted);
Customer customerRecord = customerRepository.saveAndFlush(customer);
return customerRecord;
}
Customer Controller : look at how iam passing multipart files and other fields in the controller to service
#PostMapping()
public ResponseEntity<Customer> createCustomer(#Valid #RequestPart("customer") String customer, MultipartFile customerImage, MultipartFile customerID, MultipartFile customerSignature
) throws Exception {
ObjectMapper customerMapper = new ObjectMapper();
Customer savedCustomer = customerMapper.readValue(customer, Customer.class);
Customer customerRecord = customerService.saveCustomer(savedCustomer, customerImage, customerID, customerSignature);
log.debug("inside createCustomer() controller : {}", customerRecord);
return ResponseEntity.status(HttpStatus.CREATED).body(customerRecord);
}
Postman post request to the endpoint:
Postman response :
I am trying to send a http request but keep getting a error 500 or sometime media type error. Any sugestion and also an example from postman trying to do
Postman post Example
// Email model
private String module;
private String notificationGroupType;
private String notificationGroupCode;
private String notificationType;
private String inLineRecipients;
private String eventCode;
private HashMap<String, Object> metaData;
public EmailModel() {
this.module = "tset";
this.notificationGroupType ="test";
this.notificationGroupCode =test"tset";
this.notificationType = "EMAIL";
this.inLineRecipients ="[test]";
this.eventCode = "DEFAULT";
this.metaData = metaData;
}
//Controller code
private EmailModel em;
#RequestMapping(value = "test", method = RequestMethod.GET)
public void post() throws Exception {
String uri= "";
EmailModel em = new EmailModel();
EmailModel data =em;
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.headers("Content-Type", "application/json")
.uri(URI.create(uri))
.POST(HttpRequest.BodyPublishers.ofString(String.valueOf(data)))
.build();
HttpResponse<?> response = client.send(request, HttpResponse.BodyHandlers.discarding());
System.out.println(em);
System.out.println(response.statusCode());
}
These are my headers: Headers
This error cropped up out of nowhere. I've been sending POST requests to my application without error for a while now. My Post method reads:
Controller:
#PostMapping(path = "/generateCredential", consumes="multipart/form-data")
#ApiOperation(value = "User can register using this Api", response = RegisterForPluginResponse.class)
public ResponseEntity<Object> generateCredential(#Valid #RequestBody RegisterForPluginRequest registerForPlugin) {
...
}
dto:
public RegisterForPluginRequest() {
super();
}
public RegisterForPluginRequest(#Email #NotEmpty String clientName, #NotEmpty int packageId, String phone, String email) {
super();
this.clientName = clientName;
this.packageId = packageId;
this.phone = phone;
this.email = email;
}
What could cause a 415 error where previously there was none? I did recently make changes to make changes to my application's SQL table by adding 2 columns, I wonder if this could be the source of my problem?
In our application user can write a message based on user id or screen name.
class Message {
public final Long userId;
public final String screenName;
public final String text;
#JsonCreator
public Message(#JsonProperty(value = "user_id", required = ???) Long userId,
#JsonProperty(value = "screen_name", required = ???) String screenName,
#JsonProperty(value = "text", required = true) String text) {
this.userId = userId;
this.screenName = screenName;
this.text = text;
}
}
Fields userId and screenName can't be optional at same time, one should be provided.
How in Spring Boot to mark that they are semi-required?
This seems like more of a validation concern rather than deserialization.
Create a Validator then put #Valid within the #RequestMapping on the controller.
See more here:
Spring REST Validation Example
From jenkov tutorials:
#JsonValue
The Jackson annotation #JsonValue tells Jackson that Jackson should
not attempt to serialize the object itself, but rather call a method
on the object which serializes the object to a JSON string. Note that
Jackson will escape any quotation marks inside the String returned by
the custom serialization, so you cannot return e.g. a full JSON
object. For that you should use #JsonRawValue instead (see previous
section).
The #JsonValue annotation is added to the method that Jackson is to
call to serialize the object into a JSON string. Here is an example
showing how to use the #JsonValue annotation:
public class PersonValue {
public long personId = 0;
public String name = null;
#JsonValue
public String toJson(){
return this.personId + "," + this.name;
}
}
The output you would get from asking Jackson to serialize a
PersonValue object is this:
"0,null"
So you can use #JsonValue and put your code either to ignore or not from some fields when you try to convert into JSON
#JsonValue
public String toJson(){
//ignore fields or include them here
}
Just throw an IllegalArgumentException. The best case would be to deserialize, then run through a validator though so you separate the concerns of serialization, and domain validation.
class Message {
public final Long userId;
public final String screenName;
public final String text;
#JsonCreator
public Message(#JsonProperty(value = "user_id", required = false) Long userId,
#JsonProperty(value = "screen_name", required = false) String screenName,
#JsonProperty(value = "text", required = true) String text) {
if(userId == null && screenName == null) {
throw new IllegalArgumentException("userId or screenName must be provided.");
}
this.userId = userId;
this.screenName = screenName;
this.text = text;
}
}
Hi how to add extra field to the writable for passing additional content to the data map , for example i want to able to pass url for image thus allow image sharing , how to go about , am mostly js dev , so not really how to implement add new features to work sinch server
public final class WritableMessage {
private static final int HEADER_MAX_SIZE = 1024;
private final String messageId;
private String textBody;
private string extraContent;// added here for passing img url
private List<String> recipientIds;
private Map<String, String> headers;
private int headerSize;
public WritableMessage(String recipientUserId, String textBody, extraContent) {
this();
this.addExtra(extraContent); // but the sinch doesnt allow overide
this.addRecipient(recipientUserId);
this.setTextBody(textBody);
}
Use addHeader to add extra stuff to you message
public WritableMessage(String recipientUserId, String textBody, string imageUrl) {
this();
this.addHeader("imageUrl", imageUrl);
this.addRecipient(recipientUserId);
this.setTextBody(textBody);
}