Tuesday, 19 March 2019

Liferay DXP using API to get Weather details.


You can fetch the Live weather data using  api in Liferay.
You can make ajax call .

Follow these steps.

1) Create a Liferay Module Project.
   Open the view. jsp and paste the below code

<head>
  <title></title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>

  <script type="text/javascript">
  jQuery(function($){
    function getWeather(){
      $.ajax('http://api.wunderground.com/api/c6dc8e785d943109/conditions/q/AZ/Chandler.json', {
        dataType: 'jsonp',
        success: function(json) {
          $('div#city strong').text(json.current_observation.display_location.full)
          $('div#icon').html('<img src=' + json.current_observation.icon_url + '>')
          $('div#weather').text(json.current_observation.temperature_string + " " + json.current_observation.weather);
          $('div#time').text(json.current_observation.observation_time_rfc822);
        }
      });
    }
    $('a.get_weather').click(function(e) {
      e.preventDefault();
      $(this).hide();
      getWeather();
      $('#result').fadeIn(1000);
    });
    $('a.hide').click(function(e) {
      e.preventDefault();
      $('#result').hide();
      $('a.get_weather').show();
    })
  })
  </script>

    <header class="seats-header">
  <h1>Weather</h1>
</header>

  <div><a href="#" class="get_weather">Get weather</a></div>
  <div id="result" style="display: none">
    <div id="icon"></div>
    <div id="city"><strong></strong></div>
    <div id="weather"></div>
    <div id="time"></div>
    <div><a href="#" class="hide">Hide</a>
  </div>


</body>



2) Add Javascript CDN in your code
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>


3)No w go to  https://openweathermap.org/api website and get the url which gives you
whether report based on city name  and country which we are passing as inputs.


Now deploy and check it will show current weather based on your Input.

Friday, 15 March 2019

Creating PDF in Liferay 7,.

Follow the below steps to export your data as PDF.

1) Create a Liferay Module Project build type as Maven. Her  we are using Liferay resourceURL
when button  is clicked PDF will be generated.

Add the following content in view.jsp


<portlet:resourceURL var="submitFormDetailsResourceURL" id="createPDF" escapeXml="false"/>
<br><br><br>
<form action="${submitFormDetailsResourceURL}" method="post">
<input type="submit" value="Create PDF" name="createPDF">
</form>

2) Now write the resource method in Controller class . use the below  method in your controller.

@ResourceMapping("createPDF")
public void createPdf(ResourceRequest request, ResourceResponse response) throws DocumentException, IOException
{

System.out.println("Inside create PDF");
String[] headers = new String[]{ "Instructor Id", "Course Name", "Course Description", "Instructor Name" };
     
        Document document = new Document(PageSize.LETTER.rotate());
        PdfWriter.getInstance(document,
                new FileOutputStream(new File("C:/Users/CC130/Desktop/PDF/pdf/table.pdf")));
//C:/Users/CC130/Desktop/PDF/pdf/table.pdf in this location pdf will be generated.
        document.open();
        Font font = new Font();
     
        Font fontHeader = new Font(font.TIMES_ROMAN, 12, Font.BOLD);
        Font fontRow = new Font(font.TIMES_ROMAN, 10, Font.NORMAL);
     
        PdfPTable table = new PdfPTable(headers.length);
        for (String header : headers) {
            PdfPCell cell = new PdfPCell();
            cell.setGrayFill(0.9f);
            cell.setPhrase(new Phrase(header.toUpperCase(), fontHeader));
            table.addCell(cell);
        }
        table.completeRow();
   
     
        List<pdf.creator.model.Course> courseList= new ArrayList<pdf.creator.model.Course>();
    pdf.creator.model.Course course = new pdf.creator.model.Course();
    course.setInstructorId(12323);
    course.setCourseName("java");
    course.setCourseDescription("Java Bascis");
    course.setInstructorName("Sunil");
    pdf.creator.model.Course course1 = new pdf.creator.model.Course();
    courseList.add(course);
    course1.setInstructorId(12323);
    course1.setCourseName("Js");
    course1.setCourseDescription("JS Bascis");
    course1.setInstructorName("ram");
      courseList.add(course1);
     
     
       // List<Course> courseList = CourseLocalServiceUtil.getCourses(-1, -1);
        System.out.println(courseList.size());
        for(pdf.creator.model.Course c:courseList) {

        long l = c.getInstructorId();
        String str = Long.toString(l);
table.addCell(str);
table.addCell( c.getCourseName());
table.addCell( c.getCourseDescription());
table.addCell(c.getInstructorName());


}
     
     
     
        document.addTitle("PDF Table Demo");
        document.add(table);
        document.close();
    System.out.println(" created PDF");
   
    //create csv file
    String csv = "C:/Users/CC130/Desktop/PDF/pdf/table.csv";
   
    FileWriter fileWriter = new FileWriter(csv);
    CSVWriter csvWriter = null;
    //CSVWriter writer = new CSVWriter(new FileWriter(csv));
   
 
    ColumnPositionMappingStrategy<pdf.creator.model.Course> mappingStrategy =
    new ColumnPositionMappingStrategy<pdf.creator.model.Course>();
   
    mappingStrategy.setType(pdf.creator.model.Course.class);
   
    csvWriter = new CSVWriter(fileWriter,
                CSVWriter.DEFAULT_SEPARATOR,
                CSVWriter.NO_QUOTE_CHARACTER,
                CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                CSVWriter.DEFAULT_LINE_END);
   

csvWriter.writeNext(headers);

for (pdf.creator.model.Course customer : courseList) {
String[] data = {
String.valueOf(customer.getInstructorId()),
customer.getCourseName(),
customer.getCourseDescription(),
customer.getInstructorName()};

csvWriter.writeNext(data);
}
   
fileWriter.close();
csvWriter.close();
   
        //Result set

    //writer.writeAll(data);
 
    System.out.println("CSV File Created");


}


3) Here i am using Course as a Model Class in which i have already stored some records in database
here is the Model Class. You can just fetch Liferay users and create PDF. i just used my own model.

package pdf.creator.model;

public class Course {
private  long instructorId;
private String courseName;
private String courseDescription;
private String instructorName;


public Course() {
super();
// TODO Auto-generated constructor stub
}
public Course(long instructorId, String courseName, String courseDescription, String instructorName) {
super();
this.instructorId = instructorId;
this.courseName = courseName;
this.courseDescription = courseDescription;
this.instructorName = instructorName;
}
public long getInstructorId() {
return instructorId;
}
public void setInstructorId(long instructorId) {
this.instructorId = instructorId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseDescription() {
return courseDescription;
}
public void setCourseDescription(String courseDescription) {
this.courseDescription = courseDescription;
}
public String getInstructorName() {
return instructorName;
}
public void setInstructorName(String instructorName) {
this.instructorName = instructorName;
}


}

4)  Make sure that you have the same dependencies in pom.xml

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>com.liferay.portal.kernel</artifactId>
<version>2.6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.portlet</groupId>
<artifactId>portlet-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.service.component.annotations</artifactId>
<version>1.3.0</version>
<scope>provided</scope>
</dependency>


<dependency>
         <groupId>org.apache.pdfbox</groupId>
         <artifactId>pdfbox</artifactId>
         <version>2.0.1</version>
      </dependency> 
 
      <dependency>
         <groupId>org.apache.pdfbox</groupId>
         <artifactId>fontbox</artifactId>
         <version>2.0.0</version>
      </dependency>
     
      <dependency> 
         <groupId>org.apache.pdfbox</groupId>
         <artifactId>jempbox</artifactId>
         <version>1.8.11</version>
      </dependency>
       
      <dependency>
         <groupId>org.apache.pdfbox</groupId>
         <artifactId>xmpbox</artifactId>
         <version>2.0.0</version>
      </dependency>
   
      <dependency>
         <groupId>org.apache.pdfbox</groupId>
         <artifactId>preflight</artifactId>
         <version>2.0.0</version>
      </dependency>
   
      <dependency>
         <groupId>org.apache.pdfbox</groupId>
         <artifactId>pdfbox-tools</artifactId>
         <version>2.0.0</version>
      </dependency>
     
      <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
   <dependency>

<groupId>com.lowagie</groupId>

<artifactId>itext</artifactId>

    <version>2.1.7</version>

</dependency>
    <!-- https://mvnrepository.com/artifact/com.itextpdf.tool/xmlworker -->

   
      <!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.1.2</version>
</dependency>

<dependency>
<groupId>edcst.course</groupId>
<artifactId>edcst-course-api</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.opencsv/opencsv -->
<dependency>
  <groupId>com.opencsv</groupId>
  <artifactId>opencsv</artifactId>
  <version>4.4</version>
</dependency>



</dependencies>

5) Deploy your portlet  and it willl generate PDfF file in System's Specified Location.

Monday, 11 March 2019

Sending Mail in Liferay 7.1 using template.

I am going to explain you how to send mail in liferay 7.1 using templates.
Follow these Steps :

1) Create a Liferay Module Project .

2) Create a mail template , Create a folder content inside the resource and create template.tmpl file
with below content

 <h3>Dear [$Name$],</h3>
<br/>
<h2><font color=red>[$comment$]</font></h2>
<br/>
your email content here.
<br/>
<h3>Thanks for contacting us</h3>
<br/>
<h3>
Best Regards,<br/>
XXXXXX Support
</h3>.

In this example i am using template from Liferay web content i m not using external templates here.
In Liferay Create  web content like this
public void sendMail(ActionRequest actionRequest, ActionResponse actionResponse)
          {
//fetach the web content created in step 2.
JournalArticle journalArticle = null;
try {
journalArticle = JournalArticleLocalServiceUtil.getLatestArticleByUrlTitle(groupIdd,urlTitle,
ContactPortletCommonConstants.ACTIVE);
} catch (Exception e1) {
_logger.info("Error While Fetching The Web Content");
}
//after getting journal read the content section from web content which contains our template
Document document = SAXReaderUtil.read(journalArticle.getContentByLocale(Locale.ENGLISH.toString()));
Node brandNode = document.selectSingleNode("/root/dynamic-element[@name='content']/dynamic-content");
String content = brandNode.getText();



InternetAddress fromAddress = null;
InternetAddress toAddress = null;

content = StringUtil.replace(content, new String[] { "[$firstName$]", "[$comment$]" },
new String[] { user.getFullName(),description });
try {
fromAddress = new InternetAddress("aaccc@gmail.com");
toAddress = new InternetAddress("bbccc@gmail.com");
MailMessage mailMessage = new MailMessage();
mailMessage.setTo(toAddress);
mailMessage.setFrom(fromAddress);
mailMessage.setSubject("Send mail by Using Tempelate");
mailMessage.setBody(content );
mailMessage.setHTMLFormat(true);
MailServiceUtil.sendEmail(mailMessage);
System.out.println("Send mail by Using Tempelate");
} catch (AddressException e) {
e.printStackTrace();
}
}

4)Now you need to Configure Gmail form Liferay Control Panel , Go to Configuration -> Server adminstration -> mail  . enter below details.

5) Now you need enable gmail permission to use gmail in your application.
Login to ur Gmail account and open this link and give permission to use your Gmail through other Apps.
Open this link in browser and enable access.


Now you can deploye and check your portlet . it will send the mail to your provided email.