Search This Blog

Wednesday, December 27, 2017

Cassandra to connect from remote

#comment the below keys
#listen_address

#change to your ip
seeds
rpc_address

#uncomment the below keys and add ur ip
broadcast_address
broadcast_rpc_address

#restart cassandra


note: you should not give any space in front of each keys..


in your command prompt, 

cqlsh 
or
cqlsh 

Thursday, December 21, 2017

Error: The server encountered an error processing the request. See server logs for more details

This issue comes into picture whenever there is any issue at WCF service.
So see more details about the issue, you need to includeexceptiondetailInfaults attribute to true in servicedebug tag.

Go to your web.config


<servicebehaviors>
        <behavior name="myServiceBehavior">
          <servicedebug includeexceptiondetailinfaults="true" />
        </behavior>
</servicebehaviors>

Either you can also add class attribute to the service class.

Tuesday, November 28, 2017

Cassandra Group By clause in Select command

1. Go to C:\Program Files\DataStax-DDC\apache-cassandra\conf\cassandra.yaml
change false to true

enable_user_defined_functions: true


2. Paste below functions in cqlsh window

CREATE OR REPLACE FUNCTION state_group_and_count( state map, type text )
CALLED ON NULL INPUT
RETURNS map
LANGUAGE java AS '
Integer count = (Integer) state.get(type);  if (count == null) count = 1; else count++; state.put(type, count); return state; ' ;

CREATE OR REPLACE AGGREGATE group_and_count(text)
SFUNC state_group_and_count
STYPE map 
INITCOND {};


3. execute the query like below

--select group_and_count(column) from table;
-- ex
-- select group_and_count(item) from skutable;



4. you may see like this 
Failed to format value OrderedMapSerializedKey([(u'xxx', 4)]) : 'NoneType' object has no attribute 'sub_types'
this is a cqlsh error. so you can try from programming languages like java..., it may work perfectly.

Friday, November 10, 2017

Java UniRest to call POST Http/Https Protocols

add - unirest, httpasynclient, httpcore-nio jars

// to get https post

HttpResponse response = Unirest.post ( "https://www.infovijay.com/api/call" ).header ( "content-type", "application/json" ).header ( "cache-control", "no-cache" ).body ( "{\"id\":\"12345\",\"name\":\"vijay\"}\r\n" ).asString ();

System.out.println ( response.getStatus () );
System.out.println ( response.getStatusText () );
System.out.println ( response.getHeaders () );
System.out.println ( response.getBody () );



// to file download

HttpResponse is = Unirest.get ( "https://www.infovijay.com/api/file.pdf" ).asBinary ();
byte [] buffer = new byte[is.getRawBody ().available ()];
is.getRawBody ().read ( buffer );

File targetFile = new File ( "d:/abc.pdf" );
OutputStream outStream = new FileOutputStream ( targetFile );
outStream.write ( buffer );

Java HttpClient to call POST Http/Https Protocols

                String url = "https://www.infovijay.com/api/call";
                JSONObject json = new JSONObject ();
json.put ( "id", "123" );
json.put ( "name", "vijay" );
StringEntity params = new StringEntity ( json.toString () );

/*
* HttpClient httpClient = new DefaultHttpClient();
* HttpPost httpPost = new HttpPost(url);
* ResponseHandler responseHandler = new BasicResponseHandler();
* String responseBody = null;
* try {
* httpPost.setEntity(params);
* httpPost.setHeader("Content-type", "application/json");
* httpPost.setHeader("Cache-Control", "no-cache");
* responseBody = httpClient.execute(httpPost, responseHandler);
* } catch (IOException e) {
* throw e;
* } finally {
* httpClient.getConnectionManager().shutdown();
* }
* System.out.println ( responseBody );
*/


HttpPost post = null;
HttpClient httpClient = HttpClientBuilder.create ().build ();
HttpResponse httpResponse = null;
BufferedReader br = null;
String result = null;

try
{
StringEntity jsonParams = new StringEntity ( json.toString () );
post = new HttpPost ( url );
post.setEntity ( jsonParams );
post.setHeader ( "Content-type", "application/json" );
post.setHeader ( "Cache-Control", "no-cache" );
httpResponse = httpClient.execute ( post );

br = new BufferedReader ( new InputStreamReader ( httpResponse.getEntity ().getContent () ) );
result = br.readLine ();
}
catch ( Exception e )
{
e.printStackTrace ();
}
finally
{
try
{
httpResponse = null;
post = null;
httpClient = null;

if ( br != null )
{
br.close ();
}
}
catch ( IOException e )
{
e.printStackTrace ();
}
}
System.out.println( result );
}

Monday, August 21, 2017

NodeJs Access Form-Data Property Values

For recent version of NodeJs, You have to install multer plugin.

Package.json

{
  "name": "form-data-nodejs",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "body-parser": "~1.15.1",
    "cookie-parser": "~1.4.3",
    "express": "~4.13.4",
    "multer": "^1.3.0"
  }
}

app.js

const express = require('express')
const app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

//let multer = require('multer');
//let upload = multer();
//if let gives error, use var

var multer = require('multer');


var upload = multer();

app.post('/send', upload.fields([]), (req, res) => {
  let formData = req.body;
  console.log('form data', formData.test);
  res.sendStatus(200);
});


>> node install --save
>> node app.js




https://github.com/expressjs/multer




Wednesday, June 14, 2017

Dynamic Web Module 3.0 requires Java 1.6 or newer” in Maven Projects

Open your project’s pom.xml and add this plugin tag
<build>
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
    </plugins>
</build>
Finally, right click on your project > Maven > Update Project

Tuesday, May 16, 2017

Docker - Setup with Two Tomcat with Nginx / SFTP

imp commands
************
find / -name tomcat8


Oracle jdk 1.8
**************
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

#this will give all ip and other details
docker inspect


imp commands
+++++++++++++
docker run -it ubuntu
apt-get update
apt-get install vim
apt-get install net-tools
apt-get install python-software-properties
apt-get install software-properties-common
add-apt-repository ppa:webupd8team/java
apt-get update
apt-get install oracle-java8-installer
apt-get install -y net-tools
apt-get update
apt-get install tomcat7 vim
echo $JAVA_HOME
export JAVA_HOME=/usr/lib/jvm/java-8-oracle
vim /etc/default/tomcat7
# now ensure in tomcat7 file
# remove the comment
JAVA_HOME=/usr/lib/jvm/java-8-oracle
ifconfig
service tomcat7 start

wget localhost:8080

docker commit/push/pull
docker ps -a
docker commit
docker push drvijayy2k2/ubuntutomcat1
docker pull drvijayy2k2/ubuntutomcat1


to show all process - ps aux


Now instead of exiting the container, detach from it back to your terminal by typing:
ctrl-p then ctrl-q
(If you’re using gnu screen, remember it’s ctrl-a a ctrl-p, then ctrl-q)


uninstall
*********
sudo apt-get purge docker-engine
sudo apt-get autoremove --purge docker-engine

umount /var/lib/docker/overlay #check and remvoe all the containers
umount /var/lib/docker/overlay2

rm -rf /var/lib/docker # This deletes all images, containers, and volumes

dettach
ctrl + a + p + q

80, 8080,8081,8082, 8888 - opened for outside

tomcat1
docker run --name tomcat1 -p 8080:8080 -it drvijayy2k2/tomcat8
service tomcat8 start
wget localhost:8080
ctrl + a + p + q
browser - http://ip-1:8080/

you can change the root file
apt-get install vim
find / -name tomcat8
vi /var/lib/tomcat8/webapps/ROOT/index.html
vi /usr/share/tomcat8/startup.sh

tomcat2
docker run --name tomcat2 -p 8081:8080 -it drvijayy2k2/tomcat8
service tomcat8 start
wget localhost:8080
backgroun [ -d is not working] - ctrl + a + p + q
browser - http://ip-2:8081/


nginx
172.17.0.3
#sudo docker run --name docker-nginx -p 80:80 -d -v ~/docker-nginx/tml:/usr/share/nginx/html nginx

docker run --name ubuntu-nginx -it -p 80:80 drvijayy2k2/nginx
vi /etc/nginx/conf.d/default.conf
service nginx start
ctrl + a + p + q
browser http://ip-3
docker attach

#add host entry c:\windows\system32\drivers\etc\hosts
ip-3 docker.poc.com
open browser
http://docker.poc.com
#stop the tomcat to see or refersh, it will do the roundrobin by default

SFTP - ip-4
*******
docker run -it -p 8081:22 drvijayy2k2/sftp
service vsftpd start
service ssh start
ctrl + a p q

open winscp
type ur public ip ip-4
port 8081
user john
pwd test123

copy some files to www folder

Sunday, February 26, 2017

Spring

Spring focuses around providing a way to manage your business objects.

Spring is an application framework in which spring MVC is
one of the modules of spring framework. Spring uses the
concept of IOC/DI where the objects are not hard coded in
java but they are injected using construtor/setter
injection.

Spring is an ideal framework for test driven projects

Applications built using Spring are very easy to unit tes

Spring can make the use of EJB an implementation choice, rather than the determinant of application architecture. You can choose to implement business interfaces as POJOs or local EJBs without affecting calling code

Spring provides a consistent framework for data access

this consistency in the Spring approach to JDBC, JMS, JavaMail, JNDI and many other important APIs.

Spring's main aim is to make J2EE easier to use and promote good programming practice

no logging packages in Spring, no connection pools, no distributed transaction coordinator

Spring container manages relationships between objects

Dependency Injection is a form of IoC that removes explicit dependence on container API, two major flavors of Dependency Injection are Setter Injection (injection via JavaBean setters); and Constructor Injection (injection via constructor arguments)

highly configurable MVC web framework

Spring's MVC model is most similar to that of Struts, although it is not derived from Struts

Spring Controller is similar to a Struts Action in that it is a multithreaded service object


Spring provides a very clean division between controllers, JavaBean models, and views

Spring MVC is truly view-agnostic. You don't get pushed to use JSP if you don't want to; you can use Velocity, XLST or other view technologies

custom view mechanism - for example, your own templating language - you can easily implement the Spring View interface to integrate it


Steps:-
++++++++

1. Open MyEclipse Editor [or] any editor
2. Create a new Project [java project]
3. Add neccessary Jar Files in lib [ spring, hibernate core 3.1, jre 1.5+ ]
4. Create your DB
5. Create spring-hibernate.xml
6. Create xxxFormBean.hbm.xml
7. Write a xxxFormBean.java
8. Write a DAO
9. Write a program to call


Sample DB Create [MYSQL]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

create database springdb;
use springdb;

create table employee ( id int(10) unsigned NOT NULL auto_increment primary key, name varchar(20), age int(3), salary numeric(10,2));

insert into `employee`(`id`,`name`,`age`,`salary`) values ( NULL,'vijay','25','10000');
insert into `employee`(`id`,`name`,`age`,`salary`) values ( NULL,'kumar','20','5000');


spring-hibernate.xml  [save inside src folder]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="myDataSource"
        class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/springdb" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="mappingResources">
            <list>
                <value>./Employee.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.HSQLDialect
            </value>
        </property>
    </bean>

    <bean id="hibernateTemplate"
        class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory">
            <ref bean="mySessionFactory" />
        </property>
    </bean>

    <bean id="employeeDao" class="spring.hibernate.EmployeeDao">
        <property name="hibernateTemplate">
            <ref bean="hibernateTemplate" />
        </property>
    </bean>


</beans>


Employee.hbm.xml
~~~~~~~~~~~~~~~~~~~

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="spring.hibernate.Employee" table="employee" lazy="false">
    <id name="id" column="id">
        <generator class="increment"/>
    </id>

    <property name="name">
        <column name="name"/>
    </property>
    <property name="age">
        <column name="age"/>
    </property>
    <property name="salary">
        <column name="salary"/>
    </property>
</class>
</hibernate-mapping>


Employee.java
~~~~~~~~~~~~~

package spring.hibernate;

public class Employee {

    private int id;
    private String name;
    private int age;
    private double salary;

    public Employee() {
    }

    public int getId(){
        return id;
    }

    public void setId(int id){
        this.id = id;
    }

    public String getName(){
        return name;
    }

    public void setName(String name){
        this.name = name;
    }

    public int getAge(){
        return age;
    }  

    public void setAge(int age){
        this.age = age;
    }

    public double getSalary(){
        return salary;
    }

    public void setSalary(double salary){
        this.salary = salary;
    }

    public String toString(){
        return "Id = " + id + ", Name = " + name + ", Age = "
            + age + ", Salary = " + salary;
    }
}


EmployeeDao.java
~~~~~~~~~~~~~~~~~~~

package spring.hibernate;

import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import spring.hibernate.Employee;

public class EmployeeDao
{

    private HibernateTemplate    hibernateTemplate;

    public void setHibernateTemplate ( HibernateTemplate hibernateTemplate )
    {
        this.hibernateTemplate = hibernateTemplate;
    }

    public HibernateTemplate getHibernateTemplate ()
    {
        return hibernateTemplate;
    }

    public Employee getEmployee ( final int id )
    {
        HibernateCallback callback = new HibernateCallback () {
            public Object doInHibernate ( Session session ) throws HibernateException, SQLException
            {
                return session.load ( Employee.class, id );
            }
        };
        return (Employee) hibernateTemplate.execute ( callback );
    }

    public void saveOrUpdate ( final Employee employee )
    {
        HibernateCallback callback = new HibernateCallback () {
            public Object doInHibernate ( Session session ) throws HibernateException, SQLException
            {
                session.saveOrUpdate ( employee );
                return null;
            }
        };
        hibernateTemplate.execute ( callback );
    }
}


SpringTest.java
~~~~~~~~~~~~~~~~~

package spring.hibernate;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class SpringTest
{

    public static void main ( String [] args )
    {

        Resource resource = new FileSystemResource ( "bin/spring-hibernate.xml" );
        BeanFactory factory = new XmlBeanFactory ( resource );

        Employee employee = new Employee ();
        employee.setId ( 123 );
        employee.setName ( "ABC" );
        employee.setAge ( 20 );
        employee.setSalary ( 15000.00d );

        EmployeeDao employeeDao = (EmployeeDao) factory.getBean ( "employeeDao" );
        //employeeDao.saveOrUpdate ( employee );

        Employee empResult = employeeDao.getEmployee ( 1 );
        System.out.println ( empResult );
    }
}

drvijayy2k2@gmail.com

Hit Counter


View My Stats