Thursday, 2 March 2017

how to get src value from normal Text in javascript

<html>
<head>
</head>
<title>|| Video Uploader || </title>
<body>
<input type="text" id="video_url" name="video_url" value="<iframe   width='420' height='315'    src='https://www.youtube.com/embed/XGSy3_Czz8k'></iframe>"  />
<button id = "opener" onclick="insertURL()">Show URL </button>

<script type="text/javascript">
<!-- If User's Provide direct URL or Full iframe innerhtml-->
    function insertURL(){
        var ishare_url = document.getElementById("video_url").value;
       
        if(undefined!==ishare_url.split('src=')[1]){
        var src = ishare_url.split('src=')[1].split(/[ >]/)[0];
        if(src){
            var decode_ishare_url = decodeURI(src.trim());
            var replace_String = decode_ishare_url.replace(/%22/g, '');
            var replaceQuotes = replace_String.replace(/['"]+/g, '');
            document.getElementById("video_url").value = replaceQuotes;//Assign updated value
           
            }
        }else {
            if (ishare_url){
            var decode_ishare_url = decodeURI(ishare_url.trim());
            var replace_String = decode_ishare_url.replace(/%22/g, '');
            var replaceQuotes = replace_String.replace(/['"]+/g, '');

            document.getElementById("video_url").value = replaceQuotes;//Assign updated value
            }
            }
            alert("SRC ::    "+document.getElementById("video_url").value);
    }   
   
    function clearFieldValue() {
    // Clear urls Fields here
    document.getElementById("video_url").value = "";
}
window.onload = clearFieldValue;       
</script>
</body>
</html>

Thursday, 9 February 2017

How to Add Javascript,CSS inside Javascript

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var CSSURL="https://fonts.googleapis.com/css?family=Hind";
$(document).ready(function(){
    $("p").click(function(){
       alert("Hi");
  $.getScript("https://code.jquery.com/ui/1.12.1/jquery-ui.js", function(){

   alert("Script loaded but not necessarily executed.");

});
    });
});

var linkElem = document.createElement('link');
document.getElementsByTagName('head')[0].appendChild(linkElem);
linkElem.rel = 'stylesheet';
linkElem.type = 'text/css';
linkElem.href = CSSURL;
</script>
</head>
<body>


<p>Click Here to load JS and CSS As well !</p>

</body>
</html>

Saturday, 7 January 2017

How to Read XLSX File in Java Using apache Poi API

Here we will implement the code to read XLSX file using apache POI API :
and download required jars based on below snapshot






Code : -


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.test.XLS;

import java.io.*;
import java.util.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

/**
 *
 * @author anand
 */
public class XLSReader {

    static final String fileName = "FriendsZone.xlsx";
    FileInputStream file = null;

    public void readXLSFile() {
        try {
            file = new FileInputStream(new File(fileName));

            XSSFWorkbook workbook = new XSSFWorkbook(file);

            XSSFSheet sheet = workbook.getSheetAt(0);

            Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext()) {

                Row row = rowIterator.next();

                Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext()) {

                    Cell cell = cellIterator.next();

                    switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_NUMERIC:

                            System.out.print(cell.getNumericCellValue() + "\t");

                            break;

                        case Cell.CELL_TYPE_STRING:

                            System.out.print(cell.getStringCellValue() + "\t");

                            break;
                    }
                }

                System.out.println("");
            }

            file.close();

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (file != null) {

                try {

                    file.close();

                } catch (IOException ex) {

                    //Logger.getLogger(XLSReader.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    public static void main(String[] args){
     
            new XLSReader().readXLSFile();
         
     
    }
}



For any Doubt please comment it . Thanks 

Tuesday, 20 December 2016

Converting JSONArray into CSV file in java

package com.loginController;

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONObject;
/**
 *
 * @author anand
 *
 */
public class ConvertArray {
    public static void main(String myHelpers[]){
        String jsonArrayString = "{\"fileName\": [{\"name\": \"Anand\",\"last\": \"Dwivedi\",\"place\": \"Bangalore\"}]}";

        JSONObject output;
        try {
            output = new JSONObject(jsonArrayString);


            JSONArray docs = output.getJSONArray("fileName");

            File file=new File("JSONSEPERATOR.csv");
            String csv = CDL.toString(docs);
            FileUtils.writeStringToFile(file, csv);
            System.out.println("Data has been Sucessfully Writeen to "+file);
        } catch (Exception e) {
            e.printStackTrace();
        }    
    }

}

Sunday, 18 December 2016

Custom Sorting in Java

How Custom Sorting will work in java

# Some time we may got the requirement to Sort generic Class level list into Default Sorting order in that case we will have to write own custom logic for that . below is the code to perform Custom logic in java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com;

import java.util.*;

/**
 *
 * @author anand
 */
public class CustomSorting {

    private String username;
    private String userplace;
    private String userdesignation;

    static List<CustomSorting> details = null;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUserplace() {
        return userplace;
    }

    public void setUserplace(String userplace) {
        this.userplace = userplace;
    }

    public String getUserdesignation() {
        return userdesignation;
    }

    public void setUserdesignation(String userdesignation) {
        this.userdesignation = userdesignation;
    }

    public CustomSorting(String username, String userplace, String userdesignation) {
        this.username = username;
        this.userplace = userplace;
        this.userdesignation = userdesignation;
    }

    public static void main(String[] args) {
        details = new ArrayList<CustomSorting>();

        CustomSorting customDetails = new CustomSorting("Anand", "Bangalore", "Software Developer");
        CustomSorting customDetails1 = new CustomSorting("Ajeet", "Pune", "Testing Lead");
        CustomSorting customDetails3 = new CustomSorting("Antrish", "Chennai", "C# Lead");
        CustomSorting customDetails5 = new CustomSorting("Sachin", "Rewa", "SBI Manager");
        CustomSorting customDetails6 = new CustomSorting("Anand", "Mumbai", "Software Developer");

        details.add(customDetails);
        details.add(customDetails1);
        details.add(customDetails3);
        details.add(customDetails5);
        details.add(customDetails6);

        System.out.println("==========Before Sorting==============");
        for (CustomSorting custom : details) {
            System.out.println(custom.getUsername());
        }

        Collections.sort(details, new Comparator<CustomSorting>() {

            @Override
            public int compare(CustomSorting t, CustomSorting t1) {
                if (t.getUsername().equals(t1.getUsername())) {
                    return t.getUserplace().compareTo(t1.getUserplace());
                } else {

                    return t.getUsername().compareTo(t1.getUsername());
                }

            }

        });

        System.out.println("===========After Sorting =============");
        for (CustomSorting custom : details) {
            System.out.println(custom.getUsername()+"\t"+custom.getUserplace());
        }
    }

}

Saturday, 17 December 2016

How to read CSV File in Java

Here we can learn how to read CSV file comma seprated in java below is the code

--> Use apache API to read CSV or use BufferReader
--> here i have used Buffer Reader


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
 *
 * @author anand
 *
 */
public class ReadCSVFile {

    public static void main(String[] args) {

     
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ","; //Comma seprated

        try {

            br = new BufferedReader(new FileReader("Your_CSV_FILE_NAME"));
            while ((line = br.readLine()) != null) {
                System.out.println("Content \t"+line);

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }}

Saturday, 19 November 2016

Attribute Override in Hibernate

Model Class

/**
 *
 */
package com.learnjavabyanand;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author ananddw
 *
 */
@Entity
@Table(name="student_details")
public class Student {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int studentrollnumber;

@Column(name="student_name")
private String studentName;


@AttributeOverrides({
@AttributeOverride(name="company_location",column=@Column(name="company1_location")),
@AttributeOverride(name="company_name",column=@Column(name="company1_name"))})
private CompanyDetails comany_detalils;



public CompanyDetails getComany_detalils2() {
return comany_detalils2;
}

public void setComany_detalils2(CompanyDetails comany_detalils2) {
this.comany_detalils2 = comany_detalils2;
}

@Embedded
private CompanyDetails comany_detalils2;


public CompanyDetails getComany_detalils() {
return comany_detalils;
}

public void setComany_detalils(CompanyDetails comany_detalils) {
this.comany_detalils = comany_detalils;
}

public int getStudentrollnumber() {
return studentrollnumber;
}

public void setStudentrollnumber(int studentrollnumber) {
this.studentrollnumber = studentrollnumber;
}

public String getStudentName() {
return studentName;
}

public void setStudentName(String studentName) {
this.studentName = studentName;
}




}



Model Class 2 : 


package com.learnjavabyanand;

import javax.persistence.Embeddable;

@Embeddable
public class CompanyDetails {
private String company_name;
private String company_location;
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getCompany_location() {
return company_location;
}
public void setCompany_location(String company_location) {
this.company_location = company_location;
}

}


Hibernate Client : 


package com.learnjavabyanand;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
/**
 * @author ananddw
 *
 */
public class StudentClient {

public static void main(String[] args) {
// TODO Auto-generated method stub

Student student= new Student();
student.setStudentName("Anand Dwivedi");
CompanyDetails comp= new CompanyDetails();
comp.setCompany_name("Rediff");
comp.setCompany_location("Bangalore");
CompanyDetails comp2= new CompanyDetails();
comp2.setCompany_name("Google");
comp2.setCompany_location("Hyderabad");
student.setComany_detalils(comp);
student.setComany_detalils2(comp2);
try{
SessionFactory factory=new AnnotationConfiguration().configure().buildSessionFactory();
Session session=factory.openSession();
session.beginTransaction();
session.save(student);
session.getTransaction().commit();
session.close();
}catch(Exception e){
e.printStackTrace();
}
}

}


hibernate Configuration 


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
  <!--  Postgres DB Details  -->
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/hibernate</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password">password</property>
      <!--  Postgres DB Details End  -->
    
    <!-- Postgres Dialect has information of list of  queries avil in Postgres DB -->
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <!-- Postgres Dialect End -->
    
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    
    <!--  Echo show Query  -->
    <property name="show_sql">true</property>
     <!--  Echo show Query End  -->
    
    <property name="format_sql">true</property>
    
    <!--  Create every time table and insert Data -->
    <property name="hibernate.hbm2ddl.auto">create</property>
    <!--  Create every time table and insert Data End -->
    
    <!--  Define Package for mapping class -->
    
    <mapping class="com.learnjavabyanand.Student"/>
    <!--  Define Package for mapping class End -->
   
  </session-factory>
</hibernate-configuration>



Snapshot : 




PS: Add all the required jars

Java Interview question and answer

  Java Backend Interview Prep — Q&A Guide Java Backend Interview Prep 24 topics · 287 questions Expand all Collap...