asif

asif

(0 comments, 21 posts)

This user hasn't shared any profile information

Posts by asif

bash one-liners: grep, sed, awk, find

#READ ARGS IN CMD LINE:
for arg in $@
do
    printf $arg
done
 
#READ LINES OF A FILE
while read line; do 
    printf $line
done < in.txt
 
#FIND MIN, MAX, AVERAGE USING AWK
awk 'NR == 1 { max=$1; min=$1; sum=0 } { if ($1>max) max=$1; if ($1<min) min=$1; sum+=$1;} END {if(NR>0) printf "%d,%d,%d", min, max, sum/NR}'
 
 
#COUNT OF EACH UNIQ ITEM
sort| uniq -c
 
sed 's/:/ /g'
 
grep -v 'patt' file
 
#!/bin/sh
 
for filename in /tmp/*
do
  echo $filename
done;
 
 
awk '{ sum += $6 } END { print sum }' filename 
awk '{sub(/[ \t]+$/, "");print}' filename 
awk '/Dog/,/Cat/' filename 
awk '/virtual/{n++}; END {print n+0}' filename 
awk '{print FNR "\t" $0}' files*
 
#Convert Windows/DOS newlines (CRLF) to Unix newlines (LF) from Unix
awk '{ sub(/\r$/,""); print }'
#Convert Unix newlines (LF) to Windows/DOS newlines (CRLF) from Unix
awk '{ sub(/$/,"\r"); print }'
#Print the sum of fields in every line
awk '{ s = 0; for (i = 1; i <= NF; i++) s = s+$i; print s }'
#Print the sum of fields in all lines
awk '{ for (i = 1; i <= NF; i++) s = s+$i }; END { print s+0 }'
sed -n '45,50p' filename           # print line nos. 45-50 of a file
 
#Calculate total size of a directory in Mb
 
ls –al |awk '{total +=$5};END {print "Total size: " total/1024/1024 " Mb"}'
 
 
#find examples
find . -name '*OR*.xls' -exec du '{}' \;
#Finding the Top 5 Big Files
find . -type f -exec ls -s {} \; | sort -n -r | head -5
#Find all directories
find . -type d
#Find files bigger than the given size
# find ~ -size +100M
Comments (0)

Spring File Upload Tutorial

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 
    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="100000"/>
</bean>
<form method="post" action="upload.form" enctype="multipart/form-data">
            <input type="file" name="file"/>
            <input type="submit"/>
        </form>
public class FileUploadController extends SimpleFormController {
 
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,
            Object command, BindException errors) throws ServletException, IOException {
 
 
        FileUploadBean bean = (FileUploadBean) command;
 
 
        byte[] file = bean.getFile();
        if (file == null) {
             // did not upload anything
        }
        ...........                 
    }
 
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
        throws ServletException {
 
        binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
 
    }
}
 
public class FileUploadBean {
 
    private byte[] file;
 
    public void setFile(byte[] file) {
        this.file = file;
    }
 
    public byte[] getFile() {
        return file;
    }
}

Jars:
lib/commons-fileupload-1.2.1.jar
lib/commons-io-1.4.jar

Comments (0)

OpenSessionInViewInterceptor for Spring + Hibernate3

- keeps the hibernate session open long enough for the view to render what is needed before it is closed
- allows access to lazy loaded associations without “LazyInitializationException” exception

applicationContext.xml
 
<bean id="openSessionInViewInterceptor"
    class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
    <property name="sessionFactory">
        <ref local="sessionFactory"/>
    </property>
    <property> name="flushModeName">
        <value>FLUSH_AUTO</value>
    </property>
</bean>
 
<property name="interceptors">
  <list>
    <ref bean="openSessionInViewInterceptor" />
  </list>
</property>

OpenSessionInViewFilter

web.xml
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
 
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
Comments (0)

Log4j configuration in Spring

web.xml
 
   <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.xml</param-value>
    </context-param>
 
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
log4j.xml
 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
    <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %-5p %c{1}:%L %m %n" />
<!--
ConversionPattern format specification
%d      inserts the date; you can specify the format (%d{yyyy-MM-dd HH:mm:ss,SSS})
%-5p    inserts the priority log level, 5 characters, left justified
%c{1}   inserts the name of the class
%L      inserts the line number
%m      inserts the user message
%n      inserts the separator (for example, a new line)
-->
            <param name="MaxFileSize" value="512KB" />
            <param name="MaxBackupIndex" value="10" />
        </layout>
    </appender>
 
    <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
        <param name="Threshold" value="INFO" />
        <param name="File" value="${webapp.root}/WEB-INF/logs/helloworld.log"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %-5p %c{1}:%L %m %n" />
        </layout>
    </appender>
 
 
    <logger name="org.springframework">
        <level value="error"/>
    </logger>
 
    <logger name="org.hibernate">
        <level value="error"/>
    </logger>
 
 
    <logger name= "net.pack">
        <level value="debug"/>
    </logger>
 
 
    <root>
        <priority value="info"></priority>
        <appender-ref ref="stdout"/>
        <appender-ref ref="fileAppender"/>
    </root>
</log4j:configuration>
 
public class TestController {
 
    private static final Logger logger = Logger.getLogger(TestController.class);
 
     public ModelAndView addTest(@ModelAttribute("test") Test test, BindingResult result) {
        logger.debug("test logging --debug");
     }
 
}
Comments (0)

ActiveMQ configuration in Spring web application

Point to Point (using Queue)

applicationContext.xml
 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd">
 
  <context:component-scan base-package="jms" />
    <context:annotation-config />
 
    <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL">
            <value>tcp://localhost:61616</value>
        </property>
    </bean>
 
    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="testQueue"/>
    </bean>
 
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
        <property name="defaultDestination" ref="destination"/>
    </bean>
 
    <jms:listener-container connection-factory="connectionFactory">
        <jms:listener destination="testQueue" ref="messageReceiver" method="receive"/>
    </jms:listener-container>
 
</beans>
MessageReceiver.java
 
@Component
public class MessageReceiver {
 
	public void receive(Map message) throws Exception {
 
	    String msg = (String) message.get("message");
 
	  }
}
MessageSender.java
 
@Controller
@RequestMapping("/sendMsg")
public class MessageSender {
 
    @Autowired
    private JmsTemplate jmsTemplate;
 
    @RequestMapping(method=RequestMethod.GET)
    public String send() {
        System.out.println("Sending...");
        sendMessage("how u doin!!");
        return "";
    }
 
    public void sendMessage(final String msg) {
        jmsTemplate.send(
                new MessageCreator() {
                    public Message createMessage(Session session) throws JMSException {
                        MapMessage mapMessage = session.createMapMessage();
 
                        mapMessage.setString("message", msg);
                        return mapMessage;
                    }
                }
        );
 
        System.out.println("Message sent> " + msg);
    }
}

Publisher – Subscriber (using Topic)

 
    <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL">
            <value>tcp://localhost:61616</value>
        </property>
    </bean>
 
    <bean id="destination" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg value="testTopic"/>
    </bean>
 
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
        <property name="defaultDestination" ref="destination"/>
    </bean>
 
    <bean id="smsNotifListener" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory"/>
        <property name="destination" ref="destination"/>
        <property name="messageListener" ref="smsSubscriber"/>
    </bean>
 
    <bean id="emailNotifListener" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory"/>
        <property name="destination" ref="destination"/>
        <property name="messageListener" ref="emailSubscriber"/>
    </bean>

Required Jars:
1. activemq-all-5.5.0 jar
2. log4j-1.2.16
3. slf4j-api-1.5.8
4. slf4j-log4j12-1.5.8
5. jcl-over-slf4j-1.5.8

Tutorial

Comments (0)
asif's RSS Feed
Go to Top