Dynamically pass domain name into an a href link in Spring Jpa - java

I am trying to create a dynamic link in an email which am sending out using Spring Jpa. I created a variable in my application.properties file so that whenever I am pushing to server I can easily change that variable from localhost to the domain name for live deployment. However, when I try to pass the domain name value, the link becomes inactive. I would appreciate if you could point me in the right direction.
Here is the application.properties snippet below:
server.port=8008
spring.jpa.database=POSTGRESQL
spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://41.207.248.189:xxxx/xxx
spring.datasource.username=****
spring.datasource.password=****
##GMAIL PROPERTIES
senderEmail = xxxxx
spring.mail.host=xxxx
spring.mail.port=xxx
spring.mail.username=xxxxxx
spring.mail.password=xxxxxxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.ssl.trust=xxxxxxx
domain-name=localhost:4200
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
Here is the snippet for the a href I need to pass the domain-name into:
"\n" +
"<a href='{domain-name}/payments/"+hashlink+"' target='_blank'>Click Here</a>"+
"\n" +
This approach above is not working but when I pass the link manually, the "click here" link works:
"<a href='http://127.0.0.1:4200/payments/"+hashlink+"' target='_blank'>Click Here</a>"+
I would appreciate your help. Thanks
UPDATE
Below is the html for the email body where I am setting the domain-name
try {
emailService.sendEmail("PAYMENT NOTIFICATION",
"<p>Dear sir/ma,</p>\n" +
"\n" +
"\n" +
"<h4>LETTER OF NOTICE </h4>\n" +
"\n" +
"\n" +
"<p>This is to notify you of the status of your organisation ..... </p>\n" +
"<p>You are hereby put on notice to remit the outstanding amount on or before ....</p>\n" +
"<p>Kindly follow the link below to make....\n</p>\n" +
"\n" +
"<a href='{domain-name}/payments/"+hashlink+"' target='_blank'>Click Here</a>"+
"\n" +
"\n" +
"<p>Thank you.</p> \n" +
"\n"
, org.getEmail());
} catch (
MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("Email Service error");
e.printStackTrace();
}
}
I hope this helps... I look forward to getting a solution. Thanks.

Based on the comments/discussion here's what you need to do:
Read/Inject the property to a String variable using #Value
#Value("${domain-name}") String domainName;
Use the variable to construct your href
Full code:
application.properties
domain-name=www.abc.com
DomainNameApp:
package domainname;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
#SpringBootApplication
public class DomainNameApp {
public static void main(String[] args) {
SpringApplication.run(DomainNameApp.class, args);
}
}
#RestController
class Ctrl {
#Value("${domain-name}")
String domainName; // or use constructor injection
#GetMapping("a")
void a() {
String hashlink = "jsdklfsdklflsdf";
String html = "<p>" +
"<a href='" + domainName + "/payments/" + hashlink + "' target='_blank'>Click Here</a>" +
"</p>";
System.out.println(html);
}
}

Based on answers by #gtiwari333... I made some corrections to my code. I decided to detail the changes I made for future readers.
First of all, I added http:// to the parameter in my application.properties, as below:
domain-name=http://localhost:4200
next, I added #Value annotation to the top of my class as below:
#Value("${domain-name}")
String domainName;
Then I was able to pass it into the a href link with ease as below:
"<p>Kindly follow the link below to make....\n</p>\n" +
"\n" +
"<a href='" +domainName+ "/payments/payment-make" + link + "' target='_blank'>Click Here</a>" +
"\n" +
"\n" +
"<p>Thank you.</p> \n" +
"\n"
Thanks. I give credit to #gtiwari333 for helping me with this.

Related

Spring REST Docs - fieldWithPath in Junit Test

I have a Spring Boot v1.5.14.RELEASE app., Using Spring Initializer, JPA, embedded Tomcat and following the RESTful API architecture principes. I have created this test
#Test
public void createCustomerChain() throws Exception {
this.mockMvc.perform(post("/customer/createCustomer")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content("{\n" +
" \"subSegment\":\"25\",\n" +
" \"legalLanguage\":\"NL\",\n" +
" \"isRestrictel\":true,\n" +
" \"isCommunicationLanguageForAllAccount\":true,\n" +
" \"isAntiMarketing\":true,\n" +
" \"hotelChain\":{\n" +
" \"legalForm\":\"09\",\n" +
" \"foundationDate\":\"2001-12-17T09:30:47Z\",\n" +
" \"tradingName\":\"COMPANY NAME\",\n" +
" \"printName\":\"TEST PRINT\",\n" +
" \"naceCode\":\"16230\",\n" +
" \"vatNumber\":\"41223334343\", \n" +
" \"countryVatCode\":\"IN\",\n" +
" \"isSubjectToVAT\":true,\n" +
" \"sectorCode\":\"85\",\n" +
" \"legalAddress\": {\n" +
" \"mainkey\":2088512,\n" +
" \"subkey\":3256\n" +
" }\n" +
" },\n" +
" \"isVATNumberOnBill\":true,\n" +
" \"communicationLanguage\":\"EN\"\n" +
"}"))
.andExpect(status().isOk())
.andDo(document("customer-create-request-Chain",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("billingAccountId").description("The billing account id of the newly created customer"),
fieldWithPath("paymentAgreementId").description("The Payment Agreement Id of the newly created customer"),
fieldWithPath("customerId").description("The id of the new created customer"),
fieldWithPath("isNewlyCreated").description("Set to `true` when the customer is newly created")),
requestFields(
fieldWithPath("subSegment").description("Market subsegment"),
fieldWithPath("legalLanguage").description("Legal language"),
fieldWithPath("isAntiMarketing").description("If true, customer does not want to have any marketing contact"),
fieldWithPath("isRestrictel").description("Indicates that the customer is on the orange list. Do not disclose information to other companies for commercial purposes."),
fieldWithPath("hotelChain.legalAddress.mainkey").description("LAM mainkey of the address. If the mainkey and the subkey is given the rest of the address information is not needed."),
fieldWithPath("hotelChain.legalAddress.subkey").description("LAM subkey of the address"),
fieldWithPath("hotelChain.legalForm").description("Legal form"),
fieldWithPath("hotelChain.foundationDate").description("Date of the foundation of a company(mandatory field for 'Chain' customer type)"),
fieldWithPath("hotelChain.vatNumber").description("Enterprise or VAT number"),
fieldWithPath("hotelChain.countryVatCode").description("ISO2 country code of the VAT number"),
fieldWithPath("isVATNumberOnBill").description("Indicates if the VAT number will be shown on the bill"),
fieldWithPath("hotelChain.isSubjectToVAT").description("Indicates if the enterprise number is a real VAT or not"),
fieldWithPath("hotelChain.sectorCode").description("Subtitle Description. Additional information relating to the customer. Name-Value pairs"),
fieldWithPath("hotelChain.tradingName").description("Trading name"),
fieldWithPath("hotelChain.printName").description("Print name of the customer"),
fieldWithPath("hotelChain.naceCode").description("Nace code"),
fieldWithPath("communicationLanguage").description("Communication language"),
fieldWithPath("isCommunicationLanguageForAllAccount")
.description("If true, commercial language of all BGC billing accounts receive the value defined at customer level and users not allowed to change commercial language of any billing account"))));
}
and this is the result of running the test:
org.springframework.restdocs.snippet.SnippetException: Fields with the following paths were not found in the payload: [customerId]
and removing the customerId from fieldWithPath test passed successfully but, I wonder why I don't have the same error for such a field like billingAccountId
This is due to customerId field could be null or absent in some cases. You can use optional for it:
fieldWithPath("customerId").description("Description").optional()
To find a more precise reason, please, post the code of the createCustomer() method.

How can I access the text of the SMS sent thru Twilio to my Spring Boot Controller?

I'm trying to use Twilio to receive SMS messages, and use the body of the SMS to perform various DB functions. The part where I'm stuck is parsing the message that I get from Twilio when they receive a text message.
Here's the controller:
#RequestMapping(
value = "/incomingSMS",
method = RequestMethod.POST)
public void getPhrase(#RequestBody String request) {
System.out.println("***********************************");
System.out.println(request);
System.out.println("***********************************");
}
And here's what is getting printed out (with new lines added for readability, and some numbers censored.):
ToCountry=US&
ToState=statecode&
SmsMessageSid=smsMessageSid&
NumMedia=0&
ToCity=city&
FromZip=zipCode&
SmsSid=SmsSid&
FromState=statecode&
SmsStatus=received&
FromCity=city&
Body=Hello+it%27s+John+&
FromCountry=US&
To=%2B1toPhoneNumber&
ToZip=55401&
NumSegments=1&
MessageSid=messageSid&
AccountSid=accountSid&
From=%2B1fromPhoneNumber&
ApiVersion=2010-04-01
I can see in "Body" my message is hiding. I also see the phone number. Is there any way I can just parse this into a Twilio object that I don't know about, so I can use methods like getBody(), getFrom()?
You can easily manipulate it by using the good old java.util.Properties class.
For the example bellow, I'm using the Apache Common IO lib to transform the String into an InputStream witch is required by Properties class. After that, all you have to do is use getProperty method to get what you need.
package com.pipocandobits.maven;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.util.Properties;
public class App {
public static void main( String[] args ) throws IOException {
System.out.println( "Hello World!" );
String source = "ToCountry=US&\n" +
"ToState=statecode&\n" +
"SmsMessageSid=smsMessageSid&\n" +
"NumMedia=0&\n" +
"ToCity=city&\n" +
"FromZip=zipCode&\n" +
"SmsSid=SmsSid&\n" +
"FromState=statecode&\n" +
"SmsStatus=received&\n" +
"FromCity=city&\n" +
"Body=Hello+it%27s+John+&\n" +
"FromCountry=US&\n" +
"To=%2B1toPhoneNumber&\n" +
"ToZip=55401&\n" +
"NumSegments=1&\n" +
"MessageSid=messageSid&\n" +
"AccountSid=accountSid&\n" +
"From=%2B1fromPhoneNumber&\n" +
"ApiVersion=2010-04-01";
Properties properties = new Properties();
properties.load(IOUtils.toInputStream(source, "UTF-8"));
System.out.println("Message body = " + properties.getProperty("Body"));
}
}
For more on how to use the java.util.Properties class check this link https://www.tutorialspoint.com/java/java_properties_class.htm

JavaFX inserting an image

Ok, I am very, very new to Java and am self taught, so no making fun of my bad coding ;)
I am messing around with Java fx and am trying to insert an image into a borderpane layout.
this is the method that is in the controller I am using to make an image appear but I cant get the filepath to work. It currently has "/images/brownBear.jpg" as the filepath, but I've tried the relative path-
com/jaimependlebury/mammal/images/brownBear.jpg
and the full path and everything in between and i either get a
FileNotFoundException
or
NullPointerErrorException
I'm not even sure I set it up correctly, I've found different things on different websites and have tried to piece information together, so any help would be appreciated.
FXML file
<ImageView fx:id="picture">
</ImageView>
Controller file-
I have the ImageView picture variable declared at the top of the class, I just didn't include it in the code block.
#FXML
public void handleMammalListView()throws FileNotFoundException {
Species species= mammalList.getSelectionModel().getSelectedItem();
picture=new ImageView();
Image img =new Image(new FileInputStream("/images/brownBear.jpg"));
picture.setImage(img);
speciesName.setText(species.getSpeciesName());
details.setText(
"Scientific name: " + species.getScientificName() +"\n"+
"Staus: " + species.getStatus() + "\n" +
"Distribution: " + species.getHabitat() +"\n" +
"Food: " + species.getFood() + "\n" +
"Birth: " + species.getBirth() + "\n" +
"Distinguishing Characteristics: " + species.getBodyType() + "\n"+
"Nursing: " + species.getNurse() + "\n" +
"Type of hair: " + species.getTypeOfHair());
The following line of code:
picture=new ImageView();
Is resetting the reference you set in your FXML - you can just remove it.

Minecraft Chat Message Replacement

I am making a permissions plugin, and want to replace the name of a player with their rank tag. For this, I have the following code:
public void playerChat(AsyncPlayerChatEvent e) {
Player target = e.getPlayer();
String message = e.getMessage().replaceAll(target.getName(), colorize(rFile.getString("players." + target)) + " " + target.getName());
e.setMessage(message);
}
Whenever I send a message to chat, it appears like it would normally.
What am I doing wrong here?
Additionally, I am using a config file (cFile) and a ranks.yml file (rFile).
First off, make sure you include the #EventHandler annotation.
#EventHandler
public void playerChat(AsyncPlayerChatEvent e) {
[...]
}
Next, check if the listener is registered in your onEnable()method.
getServer().getPluginManager().registerEvents(new YourListener(...), this);
(Replace the YourListener with this in case it's your main class)
Finally, as Luftbaum said, use AsyncPlayerChatEvent#setFormat within the event.
Example Usage:
e.setFormat(colorize(rFile.getString("players." + target)) + ": " + e.getMessage());
Edit:
In order to translate color codes such as '&3' to Bukkit's ChatColor format, you can use the ChatColor#translateAlternativeColorCodes method.
ChatColor.translateAlternateColorCodes('&', stringThatContainsCodes);
Useevent.setFormat(playerRank + ": " + event.getMessage());
This basically formats the message to be the way you want. You can use ChatColor to do colors. Also make sure you have #EventHandler.

Search for issues in current sprint in JIRA

I am trying to pull all issues (resolved or not) from the current sprint and display that information. I am using a JIRA REST Java client to achieve this. I am quite new to JIRA and the JRJC so would like all the help I can get really.
This is the code I have written so far:
SearchResult allIssuesInSprint = restClient.getSearchClient().searchJql("sprint = \"" + 29 + "\" order by rank").claim();
Iterable<Issue> allIssues = allIssuesInSprint.getIssues();
for (Issue issue : allIssues) {
System.out.println("Key: " + issue.getKey());
System.out.println("Type: " + issue.getIssueType());
System.out.println("Status: " + issue.getStatus());
System.out.println("Priority: " + issue.getPriority());
}
Again, I am new to JIRA's JAR files, so I'm not certain on how to use them. Any help would be appreciated.

Categories