working on it ...

Filters

Explore Public Snippets

Sort by

Found 2,047 snippets

    public by sukhjinderkahlon  296  3  5  0

    Convert Milliseconds to Time hours, minutes and seconds as String.

    public class Main {
        public static void main(String[] args) {
            long totalTimeInMils=6003000;
            convertMillisToTime(totalTimeInMils);
            
            //Covert from Dates
            String strStartDate = "2018/08/16 17:10:00";
            String strEndDate = "2018/08/16 17:20:01";
    
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date date = sdf.parse(strStartDate);
            Date endDate = sdf.parse(strEndDate);
            
            long millis = (endDate.getTime()- date.getTime());
            convertMillisToTime(millis);
    
        }
    
        public static String convertMillisToTime(long Millis){
            String convert = String.format("Total Time Taken: %d hour(s), %d minute(s), and %d second(s)",
                    Millis/(1000*60*60), (Millis%(1000*60*60))/(1000*60), ((Millis%(1000*60*60))%(1000*60))/1000);
            System.out.println(convert);
            return convert;
        }
    }
    						

    public by nala58008  213  1  3  0

    TcpClientExample

    /*
     * 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.devdungeon.tcpexamples;
    
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.InputStreamReader;
    import java.net.Socket;
    
    /**
     *
     * @author dtron
     */
    public class TcpClientExample {
    
        public static void main(String[] args) throws Exception {
            String sentence;
            String modifiedSentence;
            BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    
            Socket clientSocket = new Socket("localhost", 6789);
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    
            System.out.println("Enter some text to send to the server: ");
            sentence = inFromUser.readLine();
    
            outToServer.writeBytes(sentence + '\n');
            modifiedSentence = inFromServer.readLine();
    
            System.out.println("FROM SERVER: " + modifiedSentence);
            clientSocket.close();
    
        }
    }
    

    public by gajendragusain  3717  36  4  0

    JavaFX dynamic tableview using MySQL

    This is a simple JavaFX frontend to manage your database
    /*
     * Created by gajendra on 8/28/2016.
     */
    
    import javafx.application.Application;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.geometry.Insets;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.control.TableColumn.CellDataFeatures;
    import javafx.scene.control.cell.TextFieldTableCell;
    import javafx.scene.layout.HBox;
    import javafx.scene.layout.StackPane;
    import javafx.scene.layout.VBox;
    import javafx.scene.paint.Color;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    
    import java.sql.*;
    import java.util.ArrayList;
    
    public class App extends Application {
        private DbHelper db=DbHelper.getInstance();
        private TableView<ObservableList<String>> table;
        private ObservableList<ObservableList<String>> data;
        private Label query_status;
        private Label tableEditable;
        private Button add;
        private HBox dropdownHolder;
        private HBox radioBox;
        private VBox vbox;
        private ComboBox<String> databaseDropdown, tableDropdown;
        private TextArea queryBox;
        private Button submitQuery;
        private ToggleGroup radioGroup;
        private RadioButton r1,r2;
    
        public static void main(String[] args) {
            launch(args);
        }
    
        @Override
        public void start(Stage primaryStage) {
            initComponents();
    
            databaseDropdown.valueProperty().addListener(new ChangeListener<String>() {
    
                @Override
                public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                    tableDropdown.getItems().clear();
                    table.getItems().clear();
                    table.getColumns().clear();
                    query_status.setText("");
                    queryBox.clear();
                    db.setDB_URL(newValue);
                    getTables();
                }
            });
            
            tableDropdown.valueProperty().addListener(new ChangeListener<String>() {
    
                @Override
                public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                    table.getItems().clear();
                    table.getColumns().clear();
                    query_status.setText("");
                    queryBox.clear();
                    getData(newValue);
                }
            });
    
            submitQuery.setOnAction(new EventHandler<ActionEvent>() {
    
                @Override
                public void handle(ActionEvent event) {
                    table.getColumns().clear();
                    table.getItems().clear();
                    String query = queryBox.getText();
                    try{
                        Connection con = db.getConnection();
                        Statement s=con.createStatement();
                        if(r1.selectedProperty().getValue()) {
                            ResultSet rs = s.executeQuery(query);
                            populateTable(rs,false);
                            query_status.setText("Query Ok");
                            query_status.setTextFill(Color.GREEN);
                        }
                        else
                        {
                            if(s.executeUpdate(query)>0)
                            {
                                query_status.setText("Query Ok");
                                query_status.setTextFill(Color.GREEN);
                                String tableName = tableDropdown.getValue();
                                ResultSet rs =s.executeQuery("select *from "+tableName+"");
                                populateTable(rs,false);
                            }
                        }
                        s.close();
                        con.close();
                    }
                    catch(Exception e){
                        query_status.setText(e.toString());
                        query_status.setTextFill(Color.RED);
                        e.printStackTrace();
                    }
                }
            });
    
            getShemas();
            dropdownHolder.getChildren().addAll(databaseDropdown, tableDropdown,tableEditable);
            radioBox.getChildren().addAll(r1,r2,submitQuery);
            vbox.getChildren().addAll(dropdownHolder,table,query_status,queryBox,radioBox);
            StackPane stack =new StackPane();
            stack.getChildren().add(vbox);
            Scene scene = new Scene(stack);
            primaryStage.setScene(scene);
            primaryStage.show();
        }
        
        public void initComponents()
        {
            table=new TableView<>();
            table.setColumnResizePolicy(TableView.UNCONSTRAINED_RESIZE_POLICY);
            data = FXCollections.observableArrayList();
            dropdownHolder = new HBox();
            dropdownHolder.setSpacing(5);
            dropdownHolder.setPadding(new Insets(5,5,5,5));
            radioBox = new HBox();
            radioBox.setSpacing(10);
            radioBox.setPadding(new Insets(5,5,5,0));
            vbox = new VBox();
            vbox.setPadding(new Insets(5,5,5,5));;
            query_status = new Label();
            query_status.setPadding(new Insets(5,5,5,5));
            tableEditable = new Label();
            tableEditable.setPadding(new Insets(5,0,0,5));
            add = new Button("Add");
            databaseDropdown = new ComboBox<>();
            tableDropdown = new ComboBox<>();
            queryBox = new TextArea();
            queryBox.setPromptText("Enter your Custom Query here.");
            submitQuery = new Button("Submit Query");
            radioGroup = new ToggleGroup();
            r1= new RadioButton("Select Query");
            r2 = new RadioButton("Update queries: insert, update delete");
            r1.setToggleGroup(radioGroup);
            r2.setToggleGroup(radioGroup);
            r1.selectedProperty().setValue(true);
            r1.setPadding(new Insets(5,0,0,0));
            r2.setPadding(new Insets(5,0,0,0));
        }
    
        public ArrayList<String> getUniqueKeys(String tableName)
        {
            ArrayList<String> indexes = new ArrayList<>();
            try{
                Connection con = db.getConnection();
                DatabaseMetaData dbmd = con.getMetaData();
                ResultSet rs = dbmd.getIndexInfo(null,null,tableName,true,true);
                while(rs.next())
                {
                    System.out.println(rs.getString("COLUMN_NAME"));
                    indexes.add(rs.getString("COLUMN_NAME"));
                }
                rs.close();
                con.close();
            }catch(Exception e){
                e.printStackTrace();
            }
            return indexes;
        }
    
        public ArrayList<String> getTableMetaData(String tableName)
        {
            ArrayList<String> columnList =new ArrayList<>();
            try{
                Connection con = db.getConnection();
                Statement s=con.createStatement();
                ResultSet rs=s.executeQuery("select *from "+tableName);
                ResultSetMetaData rm = rs.getMetaData();
                for(int i=1;i<=rm.getColumnCount();i++)
                {
                    columnList.add(rm.getColumnName(i));
                }
                rs.close();
                s.close();
                con.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            return columnList;
        }
    
        public void setEditable(TableColumn c)
        {
            c.setCellFactory(TextFieldTableCell.forTableColumn());
            c.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<ObservableList<String>,String>>() {
    
                @Override
                public void handle(TableColumn.CellEditEvent<ObservableList<String>,String> event) {
                    ObservableList<String> currentRow = event.getTableView().getItems().get(event.getTablePosition().getRow());
                    String oldval = event.getOldValue();
                    String newval = event.getNewValue();
                    String currentColumnName = event.getTableColumn().getText();
    
    //                System.out.println("id: "+currentColumnName);
                    int currentColumnIndex = event.getTableView().getColumns().indexOf(event.getTableColumn());
                    ArrayList<String> unique_indexes = getUniqueKeys(tableDropdown.getValue());
                    ArrayList<String> columnNames = getTableMetaData(tableDropdown.getValue());
                    int uniqueColumnIndex = columnNames.indexOf(unique_indexes.get(0));
                    String value = currentRow.get(uniqueColumnIndex);
                    if(updateTable(currentColumnName,unique_indexes.get(0),value,newval)>0)
                    {
                        currentRow.set(currentColumnIndex,newval);
                    }
                    else
                        currentRow.set(currentColumnIndex,oldval);
                }
            });
        }
    
        public int updateTable(String currentField, String uniqueColumnName, String uniqueColumnId, String newval)
        {
            int n=0;
            String tableName = tableDropdown.getValue();
            System.out.println("Table Name: "+tableName);
            try{
                Connection con=db.getConnection();
                Statement s=con.createStatement();
                String query = "update `"+tableName+"` set `"+currentField+"`='"+newval+"' where `"+uniqueColumnName+"`='"+uniqueColumnId+"'";
                query_status.setText(query+" ; Query Ok");
                query_status.setTextFill(Color.GREEN);
                System.out.println("UPdate Query: "+query);
                n=s.executeUpdate(query);
                s.close();
                con.close();
            }
            catch(Exception e){
                query_status.setText(e.toString());
                query_status.setTextFill(Color.RED);
                e.printStackTrace();
            }
            System.out.println("n: "+n);
            return n;
        }
    
        public void getTables()
        {
            try{
                Connection con=db.getConnection();
    
                DatabaseMetaData dmd= con.getMetaData();
    
                ResultSet rs=dmd.getTables(null,null,null,null);
    
                while(rs.next())
                {
                    System.out.println(rs.getString("TABLE_NAME"));
                    tableDropdown.getItems().add(rs.getString("TABLE_NAME"));
                }
                tableDropdown.setPromptText("Select a Table");
    //            tableDropdown.setValue(tableDropdown.getItems().get(0));
                rs.close();
                con.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    
        public void getShemas()
        {
            try{
                Connection con=db.getConnection();
                DatabaseMetaData dmd= con.getMetaData();
                ResultSet rs=dmd.getCatalogs();
                while(rs.next())
                {
                    System.out.println(rs.getString(1));
                    databaseDropdown.getItems().add(rs.getString(1));
                }
    //            databaseDropdown.setValue(databaseDropdown.getItems().get(0));
                databaseDropdown.setPromptText("Select a Database");
                rs.close();
                con.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    
        public void getData(String tableName)
        {
            data.clear();
            try{
                Connection con=db.getConnection();
                Statement s=con.createStatement();
                ResultSet r=s.executeQuery("select *from "+tableName);
                populateTable(r,true);
                s.close();
                con.close();
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    
        public void populateTable(ResultSet r, boolean isEditable)
        {
            if(isEditable)
            {
                table.setEditable(true);
                tableEditable.setText("Table is Editable: You can make changes in a Table-Cell by double-clicking on it.");
                tableEditable.setTextFill(Color.GREEN );
            }
            else
            {
                table.setEditable(false);
                tableEditable.setText("Table is not Editable");
                tableEditable.setTextFill(Color.RED);
            }
            ResultSetMetaData rm = null;
            try {
                rm = r.getMetaData();
                for(int i=0 ; i<rm.getColumnCount(); i++) {
    
                    //We are using non property style for making dynamic table
                    final int k = i;
                    String columnName = rm.getColumnName(i+1);
                    System.out.println(columnName);
                    TableColumn col = new TableColumn(columnName);
    
                    // Reference: http://blog.ngopal.com.np/2011/10/19/dyanmic-tableview-data-from-database/comment-page-1/
                    col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
                        public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
                            return new SimpleStringProperty(param.getValue().get(k).toString());
                        }
                    });
    
                    table.getColumns().add(col);
                    setEditable(col);
                }
                while(r.next())
                {
                    ObservableList<String> tableRow = FXCollections.observableArrayList();
    
                    for(int i=1;i<=rm.getColumnCount();i++)
                    {
                        String val = String.valueOf(r.getString(i));    // safeguards against null exceptions
                        String str=(String.valueOf(r.getString(i)).equals("null"))?"":r.getString(i);
                        System.out.println(str);
                        tableRow.add(str);
                    }
                    data.add(tableRow);
                }
                table.setItems(data);
                r.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    
    
    
    /* 
      DBhelper Class
      make sure you have appropriate jdbc driver in your classpath; mine is mysql jdbc
    */
      
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    /**
     * Created by gajendra on 8/25/2016.
     */
    public class DbHelper {
        private static final String DRIVER = "com.mysql.jdbc.Driver";
        private static final String URL = "jdbc:mysql://localhost/";
        private static String DB_URL=URL;
        private static final String USER = "root";
        private static final String PASS = "";
        private static Connection con;
        private static DbHelper helper = new DbHelper();
        private DbHelper()
        {
    
        }
    
        public static void setDB_URL(String url)
        {
            DB_URL=URL+url;
        }
        public static String getDB_URL()
        {
            return DB_URL;
        }
        public static DbHelper getInstance()
        {
            return helper;
        }
    
        protected static Connection getConnection()
        {
            try{
                Class.forName(DRIVER);
                con = DriverManager.getConnection(DB_URL,USER,PASS);
            }
            catch(ClassNotFoundException e){
                e.printStackTrace();
            }
            catch(Exception e){
                e.printStackTrace();
            }
    
            return con;
        }
    }
                                                

    public by sukhjinderkahlon  3375  1  5  0

    Java Property File Reader

    This code will read properties files in java.
    package Helper.Functions;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.util.Properties;
    
    public class PropertyFileReader {
    	public static String GetValue(String key)
    	{
    		// Read from properties file
    		File file = new File("src\\main\\resources\\constants.properties");
    
    		FileInputStream fileInput = null;
    		try {
    			fileInput = new FileInputStream(file);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		Properties prop = new Properties();
    
    		//load properties file
    		try {
    			prop.load(fileInput);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    
    		//Get Data from File
    		String str = prop.getProperty(key);
    		// return the value
    		return strL;
    	}
    
    }
    

    public by sherazam  2620  0  6  0

    How to Load Visible Sheets & Skip Invisible Sheet while Loading Workbook in Android Apps

    // Enter here the actual content of the snippet.   // The following code demonstrates how to load visible sheets only.
    
    File sdDir = Environment.getExternalStorageDirectory();
    String sdPath = sdDir.getCanonicalPath();
    
    String filePath = sdPath + "/Sample.out.xlsx"
    
    // Create a sample workbook
    // and put some data in first cell of all 3 sheets
    Workbook createWorkbook = new Workbook();
    createWorkbook.getWorksheets().get("Sheet1").getCells().get("A1").setValue("Aspose");
    createWorkbook.getWorksheets().add("Sheet2").getCells().get("A1").setValue("Aspose");
    createWorkbook.getWorksheets().add("Sheet3").getCells().get("A1").setValue("Aspose");
    // Keep Sheet3 invisible
    createWorkbook.getWorksheets().get("Sheet3").setVisible(false);
    createWorkbook.save(samplePath);
    
    // Load the sample workbook
    LoadDataOption loadDataOption = new LoadDataOption();
    loadDataOption.setOnlyVisibleWorksheet(true);
    LoadOptions loadOptions = new LoadOptions();
    loadOptions.setLoadDataAndFormatting(true);
    loadOptions.setLoadDataOptions(loadDataOption);
    
    Workbook loadWorkbook = new Workbook(samplePath, loadOptions);
    
    System.out.println("Sheet1: A1: " + loadWorkbook.getWorksheets().get("Sheet1").getCells().get("A1").getValue());
    System.out.println("Sheet2: A1: " + loadWorkbook.getWorksheets().get("Sheet2").getCells().get("A1").getValue());
    System.out.println("Sheet3: A1: " + loadWorkbook.getWorksheets().get("Sheet3").getCells().get("A1").getValue());
    
    System.out.println("Data is not loaded from invisible sheet");
     
             

    public by christophh  2667  0  5  0

    Dumper

    print "<pre>".Dumper()."</pre>";

    public by JeffMorrison  316497  1  4  0

    com.javarush.test.level03.lesson08.task02;

    package com.javarush.test.level03.lesson08.task02;
    
    /* Зарплата через 5 лет
    Ввести с клавиатуры отдельно Имя, число1, число2. Вывести надпись:
    «Имя» получает «число1» через «число2» лет.
    Пример: Коля получает 3000 через 5 лет.
    */
    
    import java.io.*;
    
    public class Solution
    {
        public static void main(String[] args) throws Exception
        {
         BufferedReader r = new BufferedReader(new InputStreamReader(System.in ));
    String a = r.readLine();
    String s = r.readLine();;
    String d = r.readLine();
    int n = Integer.parseInt(s);
    int t = Integer.parseInt(d);
    System.out.println(a+" получает "+s+" через "+d+" лет.");   //Напишите тут ваш код
        }
    }

    public by lbottaro  2005  2  5  0

    Java enum example

    Enum class with private constructor and toString() as overridden method
    public enum MyEnum {
    	
    	Enum_enable("enable"), 
    	Enum_test("test");
    
    	private final String enumName;
    
    	private MyEnum(final String name) {
    		this.enumName = name;
    	}
    
    	@Override
    	public String toString() {
    		return this.enumName;
    	}
    
    }

    public by dieuph  2172  0  5  1

    Liferay prevent duplicate submission of a form

    // get portlet url from action request
    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
    String portletName = (String) actionRequest.getAttribute(WebKeys.PORTLET_ID);
    actionResponse.sendRedirect(redirectURL.toString());
    PortletURL redirectURL = PortletURLFactoryUtil.create(
        PortalUtil.getHttpServletRequest(actionRequest),
        portletName, themeDisplay.getLayout().getPlid(),
        PortletRequest.RENDER_PHASE);
    
    // set parameter
    redirectURL.setParameter("view", "abc");
    
    // redirect by actionReponse
    actionResponse.sendRedirect(redirectURL.toString());            

    public by markymark87  1589  1  6  0

    Add Auth Header to HTTP Request

    Add Auth Header to HTTP Request
    public static void addAuthHeader(HttpURLConnection http, String uid, String pwd) {
    	String hdr = uid + ":" + pwd;
    	String encode = base64Encode(hdr);
    	http.addRequestProperty("Authorization", "Basic " + encode);
    }            
    • Public Snippets
    • Channels Snippets