tag:blogger.com,1999:blog-81816920973341924902024-03-09T03:20:58.525+05:30Learning bLogSome#random('thoughts'); // technical, non technicaltechmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.comBlogger35125tag:blogger.com,1999:blog-8181692097334192490.post-50901768300786725792021-05-23T15:41:00.002+05:302021-05-23T15:41:11.945+05:30No bluetooh headphone mic on Ubuntu 18.04<p> Recently I purchased the <a href="https://www.amazon.in/gp/product/B07XJWTYM2/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1">realme Buds Wireless in-Ear Bluetooth </a>headphone for my work from home setup, when I setup the headphone I found that Ubuntu is not able to detect the headphone mic, after installing APTX, ophone and doing numerous tweaks I;m not able to connect to mic.</p><p>Then I came to know about its limitation of PulseAudio and there is new audio lib PipeWire which is better than PulseAudio.</p><p><br /></p><p>Follow below steps in order to get you mic back.</p><p><span style="font-family: courier;">sudo add-apt-repository ppa:pipewire-debian/pipewire-upstream</span></p><p><span style="font-family: courier;">sudo apt update</span></p><p><span style="font-family: courier;">sudo apt install pipewire gstreamer1.0-pipewire libspa-0.2-bluetooth</span></p><p><span style="font-family: courier;">sudo apt install pipewire-audio-client-libraries </span></p><p><span style="font-family: courier;"><br /></span></p><p><span style="font-family: courier;">sudo touch /etc/pipewire/media-session.d/with-pulseaudio</span></p><p><span style="font-family: courier;">sudo sed -i 's/.*bluez5.msbc-support.*/ bluez5.msbc-support = true/' /etc/pipewire/media-session.d/bluez-monitor.conf</span></p><p><span style="font-family: courier;">sudo sed -i 's/.*bluez5.sbc-xq-support.*/ bluez5.sbc-xq-support = true/' /etc/pipewire/media-session.d/bluez-monitor.conf</span></p><p><span style="font-family: courier;"><br /></span></p><p><span style="font-family: courier;">systemctl --user daemon-reload</span></p><p><span style="font-family: courier;">systemctl --user --now disable pulseaudio.service pulseaudio.socket</span></p><p><span style="font-family: courier;">systemctl --user --now enable pipewire pipewire-pulse</span></p><p><span style="font-family: courier;">systemctl --user --now enable pipewire-media-session.service</span></p><p><span style="font-family: courier;">systemctl --user mask pulseaudio</span></p><p><span style="font-family: courier;"><br /></span></p><p><span style="font-family: courier;">sudo shutdown -r now</span></p>techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com1tag:blogger.com,1999:blog-8181692097334192490.post-21661898250254065882019-03-13T22:30:00.001+05:302019-03-13T22:30:31.189+05:30Login Loop in Ubuntu 18.04If you are like me frustrated and pulling hairs for fixing login loop in Ubuntu GNOME DE, and you tried everything that's written their on internet like purging nvidia, removing .Xauthority file, chmod/chown /tmp folder and so on... then let me tell you my friends what really works for me :)<br />
<br />
First of all there is something kicking out us from spawning DE and in order to see that we must see the logs and understand if anything not happening right, for that just scroll the logs<br />
<br />
<span style="font-family: Courier New, Courier, monospace;">ctrl + alt + f1</span><br />
<span style="font-family: Courier New, Courier, monospace;">$ journalctl -xe | less</span><br />
<br />
and here my friends after closer look I found that gnome-shell extension are messing up with my DE boot, and just simply removing extension dir, voila I can login đ<br />
<br />
<span style="font-family: Courier New, Courier, monospace;">$ rm -rf ~/.local/share/gnome-shell/extensions</span><br />
<span style="font-family: Courier New, Courier, monospace;">$ reboot</span><br />
<br />
I hope this solves your issue too..techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com1tag:blogger.com,1999:blog-8181692097334192490.post-90414932810960497532018-01-03T21:12:00.001+05:302018-01-05T23:19:52.732+05:30Installing i3lock-color on Ubuntui3lock is fancy lock screen for Linux. There is <a href="https://packages.ubuntu.com/xenial/x11/i3lock">i3lock dep</a> available on Ubuntu but its not what I was looking for; I was more interested in <a href="https://github.com/PandorasFox/i3lock-color">i3lock-color</a>. Lets see how we can install the same on ubuntu.<br />
<br />
PS: I'm using Ubuntu 16.04<br />
<br />
<h3>
<span style="font-size: small;">Get source code for i3lock-color</span></h3>
<span style="font-family: "courier new" , "courier" , monospace;">$ git clone https://github.com/PandorasFox/i3lock-color.git </span><br />
<span style="font-family: "courier new" , "courier" , monospace;">$ cd i3lock-color</span><br />
<br />
<h3>
<span style="font-size: small;">Install required packages to build i3lock </span></h3>
<span style="font-family: "courier new" , "courier" , monospace;">$ apt install libev-dev</span><br />
<span style="font-family: "courier new" , "courier" , monospace;">$ apt install libxcb-composite0 libxcb-composite0-dev libxcb-xinerama0 libxcb-randr0 </span><br />
<span style="font-family: "courier new" , "courier" , monospace;">$ apt install libxcb-xinerama0-dev </span><br />
<span style="font-family: "courier new" , "courier" , monospace;">$ apt install libxcb-xkb-dev </span><br />
<span style="font-family: "courier new" , "courier" , monospace;">$ apt install libxcb-image0-dev </span><br />
<span style="font-family: "courier new" , "courier" , monospace;">$ apt install libxcb-util-dev</span><br />
<span style="font-family: "courier new" , "courier" , monospace;">$ apt install libxkbcommon-x11-dev</span><br />
<span style="font-family: "courier new" , "courier" , monospace;">$ apt install libjpeg-turbo8-dev </span><br />
<span style="font-family: "courier new" , "courier" , monospace;">$ apt install libpam0g-dev</span><br />
<br />
<h3>
<span style="font-size: small;">Build </span></h3>
<span style="font-family: "courier new" , "courier" , monospace;">$ autoreconf -i && ./configure && make</span><br />
<br />
<h3>
<span style="font-size: small;">Execute</span></h3>
<span style="font-family: "courier new" , "courier" , monospace;">$ ./lock.sh</span><br />
<h3>
<span style="font-family: inherit;">Assign Shortcut</span></h3>
<div>
<span style="font-family: inherit;">In order to assign shortcut, install compizconfig</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace;"><br /></span></div>
<div>
<span style="font-family: Courier New, Courier, monospace;">$ sudo apt-get install compizconfig-settings-manager compiz-plugins-extra</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace;"><br /></span></div>
<div>
<span style="font-family: inherit;">and then go to commands option and assign i3lock script (e.g. lock.sh) to some key (I have assign that script to Ctrl + Super + L)</span></div>
<span style="font-family: "courier new" , "courier" , monospace;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-SzW9T2B2zdM/Wkz5jTCSA7I/AAAAAAAAC40/9aM9hwUDaLAph7CTX1lfq3Ha_aVvhynJgCLcBGAs/s1600/screenshot.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="900" data-original-width="1600" height="360" src="https://1.bp.blogspot.com/-SzW9T2B2zdM/Wkz5jTCSA7I/AAAAAAAAC40/9aM9hwUDaLAph7CTX1lfq3Ha_aVvhynJgCLcBGAs/s640/screenshot.png" width="640" /></a></div>
<span style="font-family: "courier new" , "courier" , monospace;"><br /></span>techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com5tag:blogger.com,1999:blog-8181692097334192490.post-2223723041357490922017-04-03T23:16:00.000+05:302017-04-03T23:16:29.061+05:30Ubuntu 16.04: Office WiFI not connectingI recently changed my office login password and after messing with my current wifi settings am not able to connect to wifi given credentials and all other expected settings are correct. This happens on Ubuntu 16.04 and found out that you need to manually enter settings into a disk file and make changes there..<br />
<br />
Strangely, you wont find this settings in network manager UI, you have to manually enter this settings into file..<br />
<br />Open your wifi network file at below location and add/edit below properties.<br /><pre><code><span style="font-family: Courier New, Courier, monospace;">$ /etc/NetworkManager/system-connections/<<networkname>>
[802-1x]
eap=peap;
identity=<<login-name>>
phase2-auth=mschapv2
password-flags=0
password=<<seecret>>
system-ca-certs=false</seecret></login-name></networkname></span></code></pre>
techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-47360545093278051772016-08-05T23:15:00.000+05:302016-08-05T23:15:03.096+05:30Ubuntu SetupI just moved to Ubuntu from Windows for numerous reasons and as I'm setting up my Ubuntu I have listed few points for future me. Here it goes..<br />
<h2>
Update Java</h2>
Ubuntu 14.04 comes default with Java 7, I need Java 8 for new projects and Java 6 for some legacy projects.<br /><br />
<a href="http://ubuntuhandbook.org/index.php/2014/09/install-oracle-java-ubuntu-1410/">http://ubuntuhandbook.org/index.php/2014/09/install-oracle-java-ubuntu-1410/</a><br />
<a href="https://ubuntuforums.org/showthread.php?t=2218888">https://ubuntuforums.org/showthread.php?t=2218888</a><br />
<h3>
<b>Clean existing JDK</b></h3>
<span style="font-family: Courier New, Courier, monospace;">sudo apt-get purge openjdk*</span><br />
<span style="font-family: Courier New, Courier, monospace;">sudo apt-get purge icedtea-* openjdk-*</span><br />
<span style="font-family: Courier New, Courier, monospace;">sudo dpkg --list | grep -i jdk</span><br />
<span style="font-family: Courier New, Courier, monospace;">java -version</span><br />
<span style="font-family: Courier New, Courier, monospace;">javac -version</span><br />
<span style="font-family: Courier New, Courier, monospace;">which javaws</span><br />
<h3>
<b>Update</b></h3>
<span style="font-family: Courier New, Courier, monospace;">sudo add-apt-repository ppa:webupd8team/java</span><br />
<span style="font-family: Courier New, Courier, monospace;">sudo apt-get update</span><br />
<span style="font-family: Courier New, Courier, monospace;">sudo apt-get install oracle-java8-installer</span><br />
<span style="font-family: Courier New, Courier, monospace;">java -version</span><br />
<span style="font-family: Courier New, Courier, monospace;">sudo apt-get install oracle-java6-installer</span><br />
<span style="font-family: Courier New, Courier, monospace;">java -version</span><br />
<span style="font-family: Courier New, Courier, monospace;">sudo apt-get install oracle-java8-set-default</span><br />
<span style="font-family: Courier New, Courier, monospace;">java -version</span><br />
<br />
<h2>
Update GIT</h2>
<span style="font-family: Courier New, Courier, monospace;">sudo add-apt-repository ppa:git-core/ppa</span><br />
<span style="font-family: Courier New, Courier, monospace;">sudo apt-get update</span><br />
<span style="font-family: Courier New, Courier, monospace;">sudo apt-get install git</span><br />
<span style="font-family: Courier New, Courier, monospace;">git --version</span><br />
<br />
<br />
<h2>
Eclipse - Install Neon</h2>
<br />
<a href="http://ubuntuhandbook.org/index.php/2016/01/how-to-install-the-latest-eclipse-in-ubuntu-16-04-15-10/">http://ubuntuhandbook.org/index.php/2016/01/how-to-install-the-latest-eclipse-in-ubuntu-16-04-15-10/</a><br />
<br />
<br />
<h2>
Brightness Issue</h2>
<br />
<a href="https://itsfoss.com/fix-brightness-ubuntu-1310/">https://itsfoss.com/fix-brightness-ubuntu-1310/</a><span class="Apple-tab-span" style="white-space: pre;"> </span><br />
<br />
<br />
<h2>
maven</h2>
<br />
manual install - unzip tar.gz and set PATH<br />
<br />
<br />
<h2>
tomcat</h2>
<br />
manual install and set PATH<br />
<br />
<br />
<h2>
postgres</h2>
<br />
Please make sure about version, keep consistent version as a suffix.<br />
<a href="https://help.ubuntu.com/community/PostgreSQL">https://help.ubuntu.com/community/PostgreSQL</a><br />
<a href="https://www.postgresql.org/download/linux/ubuntu/">https://www.postgresql.org/download/linux/ubuntu/</a><br />
<a href="http://www.saintsjd.com/2014/08/13/howto-install-postgis-on-ubuntu-trusty.html">http://www.saintsjd.com/2014/08/13/howto-install-postgis-on-ubuntu-trusty.html</a><br />
<br />
<br />
<h2>
Update Kernel (for dual screen support)</h2>
<br />
<a href="https://wiki.ubuntu.com/Kernel/LTSEnablementStack">https://wiki.ubuntu.com/Kernel/LTSEnablementStack</a><br />
<br />
<br />
<h2>
minimize app (click same button to minimize)</h2>
<br />
<a href="http://askubuntu.com/questions/36433/can-i-use-the-unity-launcher-icon-to-minimize-applications-windows/436542#436542">http://askubuntu.com/questions/36433/can-i-use-the-unity-launcher-icon-to-minimize-applications-windows/436542#436542</a><br />
<div>
<br /></div>
techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-42856602515007338192016-02-19T21:45:00.000+05:302016-02-19T21:45:11.427+05:30Serlizing JSON polymorphically when type field is in parent JSON using JacksonToday, I came across a json parsing situation where the sub-type field is outside the type json. Genrally we seen a situation like this<br />
<br />
<span style="font-family: Courier New, Courier, monospace;">@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")</span><br />
<span style="font-family: Courier New, Courier, monospace;">class Animal{}</span><br />
<br />
<span style="font-family: Courier New, Courier, monospace;">class Dog extends Animal{</span><span style="font-family: 'Courier New', Courier, monospace;">}</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">class Cat extends Animal{</span><span style="font-family: 'Courier New', Courier, monospace;">}</span><br />
<br />
and it de-serialize to json like this:<br />
<span style="font-family: Courier New, Courier, monospace;">{ </span><br />
<span style="font-family: Courier New, Courier, monospace;"> "@class" : "x.y.z.Cat", ...</span><br />
<span style="font-family: Courier New, Courier, monospace;">}</span><br />
<br />
In my project I need to parse json like this<br />
<span style="font-family: Courier New, Courier, monospace;">{</span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>"status": "OK",</span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>"messageName": "x.y.z.Success",</span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>"messagePayload": {</span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>"foo": "cd3a5697",</span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>"bar": 224</span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>}</span><br />
<span style="font-family: Courier New, Courier, monospace;">}</span><br />
<span style="font-family: Courier New, Courier, monospace;">{</span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>"status": "ERROR",</span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>"messageName": "x.y.z.Error",</span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>"messagePayload": {</span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>"errorCode": "APPLICATION_ERROR",</span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>"errorInstanceId": "b292b864",</span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>"errorDetailedMessage": "Invalid UUID string (Length mismatch)"</span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>}</span><br />
<span style="font-family: Courier New, Courier, monospace;">}</span><br />
<br />
Now only thing that differs here is the messagePayload and the property that makes it different is either messageName or status. I googled this kind of json serializing problem but didn't get the expected results. All results gave example shown in above Animal class.<br />
<br />
How I solved it - well its very simple trick that strike me next day. I was trying the make @JsonTypeInfo on messagePayload, which is not working as sub-type field is outside the payload json. When I used the @JsonTypeInfo on whole message it works:<br />
<br />
<span style="font-family: Courier New, Courier, monospace;">@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.EXTERNAL_PROPERTY, property = "messageName")</span><br />
<span style="font-family: Courier New, Courier, monospace;">@JsonSubTypes({</span><br />
<span style="font-family: Courier New, Courier, monospace;"> @JsonSubTypes.Type(value = Success.class, name = "x.y.z.Success"),</span><br />
<span style="font-family: Courier New, Courier, monospace;"> @JsonSubTypes.Type(value = Error.class, name = "x.y.z.Error")})</span><br />
<span style="font-family: Courier New, Courier, monospace;">public abstract class Response {</span><br />
<span style="font-family: Courier New, Courier, monospace;"> private String status;</span><br />
<span style="font-family: Courier New, Courier, monospace;"> public abstract Payload getMessagePayload();</span><br />
<span style="font-family: Courier New, Courier, monospace;">}</span><br />
<br />
<span style="font-family: Courier New, Courier, monospace;">public abstract class Payload {}</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">public class SuccessPayload extends Payload {</span><br />
<span style="font-family: Courier New, Courier, monospace;"> private String foo;</span><br />
<span style="font-family: Courier New, Courier, monospace;"> private Long bar;</span><br />
<span style="font-family: Courier New, Courier, monospace;">}</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">public class ErrorPayload extends Payload {</span><br />
<span style="font-family: Courier New, Courier, monospace;"> private String errorCode;</span><br />
<span style="font-family: Courier New, Courier, monospace;"> private String errorInstanceId;</span><br />
<span style="font-family: Courier New, Courier, monospace;"> private String errorDetailedMessage;</span><br />
<span style="font-family: Courier New, Courier, monospace;">}</span><br />
<br />
Now using this I get the correct serialized payload depending upon the message class am getting in json. hope this helps.<br />
<br />techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-82884031399825783982016-02-07T13:00:00.000+05:302016-02-07T22:37:42.689+05:30My first C program: now and thenI was searching for some documents in gmail and found a mail that I sent to company X for their hiring process. It was a c program for searching word in file. I do not know how much time I have taken for it but it was basic search utility function.<br />
<br />
The point of this blog is not discuss that program but to discuss how time makes you better programmer.<br />
<br />
Here are the few things I would like to share myself -<br />
<br />
<ul>
<li>It takes some learning to write clean code. </li>
<li>Reed books like clean code.</li>
<li>You need mentor to learn from his experience.</li>
<li>Get a github account and see how experts are writing code.</li>
</ul>
This is not the complete list, there are many things you will acquire over a period of time which make you better programmer.<br />
<br />
PS: If you are wondering how that program used to look like, then see <a href="https://github.com/sagarr/a-program-as-per-your-request">this</a> repo.techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com1tag:blogger.com,1999:blog-8181692097334192490.post-69144446171852138752014-02-22T12:31:00.000+05:302014-02-22T12:36:01.015+05:30Again writing fast & maintainable integration tests using in-memory db, liquibase, gradle and spring mvc testThis blog is improvisation to previously blogged <a href="http://techmythoughts.blogspot.in/2013/06/writing-fast-maintainable-integration.html">testing effectively with database blog</a>. In this blog we will remove the jetty setup and instead
use <a href="https://github.com/spring-projects/spring-test-mvc">Spring MVC Test</a> framework which kind of simulate the request/response for your controllers via Spring Web Application context (no deployment, to http client tests)
Here, we will write Spring MVC tests and -
<br />
<ul>
<li>Create the HSQLDB in-memory instance (instantiating datasource instance)</li>
<li>and run Liquibase scripts against them. (using <a href="http://www.liquibase.org/documentation/spring.html">Spring Lqiuibase</a> bean)</li>
</ul>
1. Setup your web-service.
<p>Write usual Controller->Service->Repository layer.</p>
<pre class="java" name="code">
@Controller
@RequestMapping("/reports")
public class MapAnomalyReportEndpoint {
@Autowired
private MapAnomalyReportService reportService;
@ResponseBody
@RequestMapping(method = RequestMethod.GET)
public Collection<AnomalyReport> getReports() {
return reportService.getReports();
}
}
</pre>
2. Create Spring Java Config (No XML)
<p>Configure the controllers.</p>
<pre class="java" name="code">
@Configuration
@EnableWebMvc
@Import(JdbcConfig.class)
@ComponentScan(basePackages = "com.rohankar.playground")
public class WebConfig {
@Bean
public InternalResourceViewResolver viewResolver() {
final InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
return resolver;
}
}
</pre>
Configure the data source. I'm taking JDBC parameters from context, you can very well read them from .properties or system prop.
<pre class="java" name="code">
@Configuration
public class JdbcConfig {
@Autowired
private Environment env;
@Bean(destroyMethod = "close")
public DataSource getDataSource() throws NamingException {
final Context ctx = new InitialContext();
final BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName((String)ctx.lookup("java:comp/env/report/db/driverClass"));
ds.setUrl((String)ctx.lookup("java:comp/env/report/db/url"));
ds.setUsername((String)ctx.lookup("java:comp/env/report/db/user"));
ds.setPassword((String)ctx.lookup("java:comp/env/report/db/password"));
return ds;
}
@Bean
public JdbcTemplate getJdbcTemplate() throws NamingException {
return new JdbcTemplate(getDataSource());
}
}
</pre>
3. Create Spring Java Config for tests
<p>This config is purely for running liquibase scripts on datasource. </p>
<pre class="java" name="code">
@Configuration
@Import(WebConfig.class)
public class TestConfig {
@Autowired
private DataSource dataSource;
@Bean
public SpringLiquibase getLiquibase() {
final SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setDataSource(dataSource);
liquibase.setChangeLog("classpath:setup-db.xml");
return liquibase;
}
}
</pre>
4. Write integration test
In setUp method, we're populating a context object with in-memory db parameters.
<pre class="java" name="code">
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {TestConfig.class})
public class MapAnomalyReportEndpointIntTest {
@Autowired
private WebApplicationContext context;
@BeforeClass
public static void setup() throws IllegalStateException, NamingException {
final SimpleNamingContextBuilder context = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
context.bind("java:comp/env/report/db/driverClass", "org.hsqldb.jdbc.JDBCDriver");
context.bind("java:comp/env/report/db/url", "jdbc:hsqldb:mem:reportdb;shutdown=false");
context.bind("java:comp/env/report/db/user", "sa");
context.bind("java:comp/env/report/db/password", "");
context.bind("java:comp/env/report/db/schema", "report");
context.activate();
}
@Test
public void testGetReports() throws Exception {
MockMvcBuilders.webAppContextSetup(context).build() //
.perform(get("/reports")) //
.andDo(print()) //
.andExpect(status().isOk()) //
.andExpect(content().contentType("application/json;charset=UTF-8")) //
.andExpect(jsonPath("$[0].id").value(1)); // TODO assert other values
}
}
</pre>
5. Run the tests, this wont require you to configure jetty, deploy the ws and run test against them!
<p>
You can clone the whole project from <a href="https://github.com/sagarr/angular-spring-gradle-playground">here</a>.</p>
<p>
PS: The given project is built using Gradle as I want to learn it.</p>
techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-68211462909898687432013-06-13T17:53:00.000+05:302013-06-15T21:09:46.910+05:30Writing fast & maintainable integration tests using test double, in-memory db, jetty, maven and spring<p>
Writing an integration test which test end to end flow of your application can become cumbersome activity if you really hitting real db and services. The best way to mock, test double your external dependencies and thus speed up your test execution.
</p>
<p>
I created a dummy map-service project which demonstrate about writing maintainable and speedy integration tests using mocking, test double pattern, spring and automating them using maven and jetty.
You can find the project at my github location: <a href="https://github.com/sagarr/maps-service">https://github.com/sagarr/maps-service</a>
</p>
<p>
Here are some code snippets explaining the important steps in configuring your project.
</p>
<ol>
<li> POM - Configure jetty for deploying your app and running tests against it.</li>
<pre class="xml" name="code">.
<!-- Jetty -->
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jettyVersion}</version>
<configuration>
<webApp>
<contextPath>/${project.artifactId}</contextPath>
</webApp>
<stopPort>8005</stopPort>
<stopKey>STOP</stopKey>
<scanIntervalSeconds>5</scanIntervalSeconds>
<useTestScope>true</useTestScope>
<connectors>
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
<port>8080</port>
<maxIdleTime>60000</maxIdleTime>
</connector>
</connectors>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Run only integration tests -->
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12</version>
<configuration>
<includes>
<include>**/integration/**Test.java</include>
</includes>
</configuration>
<executions>
<execution>
<phase>integration-test</phase>
</execution>
</executions>
</plugin>
.
.
</pre>
<li>MockBeanInjector.java - In order to test double database and service calls</li>
<pre class="java" name="code">
public class MockBeanInjector implements BeanPostProcessor {
private final static Logger LOG = LoggerFactory.getLogger(MockBeanInjector.class);
@Override
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
if (bean instanceof DataSource) {
LOG.info("Mocking DataSource instance: " + bean);
final EmbeddedDatabaseBuilder embeddedDatabaseBuilder = new EmbeddedDatabaseBuilder();
final EmbeddedDatabase embeddedDatabase =
embeddedDatabaseBuilder.addScript("schema.sql").addScript("data.sql").build();
return embeddedDatabase;
// else
// return new ClassPathXmlApplicationContext("applicationContext-test.xml").getBean("dataSource");
}
if (bean instanceof AuthserverGateway) {
LOG.info("Mocking AuthserverGateway instance: " + bean);
final AuthserverGateway mockAsGateway = mock(AuthserverGateway.class);
final ResponseEntity<String> response = new ResponseEntity<String>(HttpStatus.NO_CONTENT);
when(mockAsGateway.callAuthorizeService("12345")).thenReturn(response);
return mockAsGateway;
} else {
return bean;
}
}
}
</pre>
<li>Finally tests</li>
<pre class="java" name="code">
public class PoiWsRestClientTest {
@Test
public void should_create_poi() {
// given
final Poi poi = new Poi();
poi.setName("Pizza Center");
poi.setLatitude(new BigDecimal("23.23212"));
poi.setLongitude(new BigDecimal("34.231312"));
// when
final URI location = new RestTemplate().postForLocation("http://localhost:8080/maps-service/pois", poi);
// then
assertThat(location.getPath(), endsWith("/pois/102"));
}
@Test
public void should_read_poi() {
// when
final Poi poi = new RestTemplate().getForObject("http://localhost:8080/maps-service/pois/100", Poi.class);
// then
assertThat(poi.getId(), is("100"));
}
@Test
public void should_delete_poi() {
// given
final HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "12345");
final HttpEntity<String> httpEntity = new HttpEntity<String>(headers);
// when
final ResponseEntity<String> response =
new RestTemplate().exchange("http://localhost:8080/maps-service/pois/101", HttpMethod.DELETE, httpEntity,
String.class);
// then
assertThat(response.getStatusCode(), is(HttpStatus.NO_CONTENT));
}
}
</pre>
</ol>techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-83703676051558078962013-06-12T21:17:00.001+05:302013-06-13T17:56:10.404+05:30Code Kata - good way to learn new language<p>
Recently, I started exploring and learning Scala and functional programming. So far, it is a good experience and as a programmer gives you new "functional" thought process about problem.
</p>
<p>
The best way to learn Scala or any language for that matter is to start writing Katas in that language.
Coding Kata, if you're not familiar with it then must visit <a href="http://codingdojo.org">codingdojo.org</a>. In short, coding kata is programming practice mostly done in TDD way, which makes you better programmer.
</p>
<p>
BTW, If you're wondering where are my katas in Scala, you can find them here: <a href="https://github.com/sagarr/scala-dojo">https://github.com/sagarr/scala-dojo</a>
</p>techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-69438423346597894512013-04-08T13:36:00.002+05:302013-04-08T13:41:37.305+05:30A Day of Innovation: TomTom Pune DevDay 2013<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-KunggeaEOJk/UWI_50nAOCI/AAAAAAAABAg/aQFonO7q_eo/s1600/TT_devday_fantom.jpg" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" height="268" src="http://3.bp.blogspot.com/-KunggeaEOJk/UWI_50nAOCI/AAAAAAAABAg/aQFonO7q_eo/s320/TT_devday_fantom.jpg" width="320" /></a></div>
Friday (6 April 2013) was a day of innovation and engineering, fun and quiz, it was a first TomTom Pune
Engineering DevDay.<br />
<br />
Key Highlights of the day:<br />
<br />
<ul style="padding-right: 5px;">
<li>Kick started with U2 public concert video, a good way to wakeup people.</li>
<li>Many speaker talked about how we can extend and experiment with our new generation map editing tool Cartopia</li>
<li>I talked about function programming and how we can achieve it using Scala.</li>
<li>There were coffee breaks with testers which showcase some really cool technologies like puppet, test automation using FlexPilot and risk based testing's.</li>
<li>Day end with exciting quiz, prize distribution and beer :)</li>
</ul>
<br />
If you want to be a part of next TomTom devday, join us <a href="http://www.tomtom.jobs">http://www.tomtom.jobs</a>techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0Pune, Maharashtra, India18.5204303 73.85674369999992518.2795338 73.534020199999929 18.761326800000003 74.17946719999992tag:blogger.com,1999:blog-8181692097334192490.post-57460940733531301712012-12-07T15:02:00.000+05:302012-12-08T19:10:09.546+05:30Adjustable flex datagrid row height for multi-level tree component<p>Note: This blog is extension to the post blogged <a href="http://www.flex888.com/712/datagrid-with-flexible-row-height.html">here</a>, the OP has used one level tree to display in grid, whereas I used multilevel tree.</p>
<p>From last 2-3 months I'm working on Flex, developing our in-house map editor. We've a requirement to show a grid with some column containing multilevel tree data, I googled it and found the above link which was matching to our requirement but got one problem, it didn't work correctly for multilevel tree. The problem is -
<ul>
<li>It failed to adjust height when you expand inner child element.</li>
<li>The whole tree get collapsed when you collapse the inner element.</li>
</ul>
</p>
<p>To provide a solution to above problems, you have to -
<ul>
<li>Keep a flag which tells if root is closing or not, if root is closing keep the original height.</li>
<li>For all other child expansion, count the children from existing "open items" and adjust height accordingly.</li>
</ul>
<p>The below code explains it all.
<pre class="xml" name="code">
<mx:Tree xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:fx="http://ns.adobe.com/mxml/2009"
dataProvider="{data.xml}"
itemOpen="switchStatus(event, true)"
itemClose="switchStatus(event, false)"
variableRowHeight="true">
<fx:Script>
<![CDATA[
import mx.controls.DataGrid;
import mx.events.TreeEvent;
private var treeOpen : Boolean = false;
private var rootClosing : Boolean = false;
private function switchStatus(event : TreeEvent, o : Boolean) : void
{
treeOpen = o;
var dg : DataGrid = (this.parentDocument.outerDocument as MyTaskGrid).dg;
rootClosing = getItemIndex(event.item) == 0 && !treeOpen;
// causes row height to adjust
if (dg != null)
{
this.invalidateSize();
}
}
override protected function measure() : void
{
super.measure();
var rc : int = 1;
if (dataProvider != null)
{
if (!rootClosing)
{
rc += countTreeNodes(dataProvider.source[0]);
}
}
this.measuredHeight = rc * rowHeight;
// tree will be collapsed after invalidateList - we need to open it
if (treeOpen)
{
expandItem(dataProvider[0], treeOpen);
}
}
private function countTreeNodes(xmlData : XML) : int
{
var count : int = 0;
for each (var xml : XML in openItems)
{
count += xml.children().length();
}
return count;
}
]]>
</fx:Script>
</mx:Tree>
</pre>
</p>techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-84687051168430399492012-08-20T13:23:00.001+05:302012-08-20T13:23:45.257+05:30Tests your logs using logback<p>You want to test what your application logging and you don't know how to do that in simplest manner, well we've logback to rescue. (If your using slf4j but with other than logback as a implementation, then you have to add logback as a test dependency with logback.xml in src/test/resources)</p>
<p>One (not exactly) caveat is that, for testing logs using logback we need to use Mockito for creating mock Appnder and asserting for the exact log string in argument.
</p>
<p>Here is the actual code-</p>
1. Create a base test class for log testing.
<pre class="java" name="code">
public abstract class BaseLoggerTest {
final Appender mockAppender = mock(Appender.class);
@Before
public void setup() {
when(mockAppender.getName()).thenReturn("MOCK");
(ch.qos.logback.classic.Logger)LoggerFactory
.getLogger(ACCESS_LOGGER_NAME))
.addAppender(mockAppender);
}
protected void verifyLog(final String expectedLog, final Level level) {
verify(mockAppender, atLeastOnce())
.doAppend(Matchers.argThat(new ArgumentMatcher() {
@Override
public boolean matches(final Object argument) {
return ((LoggingEvent)argument).getLevel().equals(level)
&& ((LoggingEvent)argument).getFormattedMessage()
.contains(expectedLog);
}
}));
}
}
</pre>
2. Extend logger base class to verify actual logging
<pre class="java" name="code">
public class MyClassLoggerTest extends BaseLoggerTest {
@Test
public void testLogSomethingShouldLogSomething() throws IOException {
// given
MyClass object = new MyClass();
// when
object.logSomething();
// then
verifyLog("I just logged something.", Level.INFO);
}
}
</pre>
Simple.
techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-82744958702741167642012-06-27T15:40:00.001+05:302012-08-15T11:49:14.703+05:30Good Vs Better ProgrammerWe always have some good programmers around us who are capable of doing work at hand, but to success in long term we need better programmers.<br />
Here are some traits I found important to become better programmer.<br />
<br />
<ol>
<li>Good programmer start coding right away after picking up the task, better programmer first do some little design upfront (may be draw some UML, flowcharts etc), write the simplest readable tests first and then write minimum production code which makes that test pass.</li>
<li>Good programmer stick to the tool, framework, workflow he/she knows best, better programmer keep the affinity towards any technology aside and evaluate and use the best possible tool, framework available. </li>
<li>Good programmer focuses on working code, better programmer too focused on working code but also gives the utmost importance to code readability, flexibility and <a href="http://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdf">other design principles</a>.</li>
<li>Good programmer ever read technology books when he/she was in college, better programmer subscribed to feeds, question/answers on technology forum and sometimes blogs.</li>
<li>Better programmers embrace the <a href="http://www.mountaingoatsoftware.com/blog/the-forgotten-layer-of-the-test-automation-pyramid">test pyramid</a> and write unit, integration and UI/acceptance tests in order to flag given task as delivered.</li>
</ol>
<div>
You can certainly guess that better programmers are no one but Agile Programmer. <span style="background-color: white;">The list is not limited to this only. There are other stuff you want to read to learn more about better programming, like </span><a href="http://programmer.97things.oreilly.com/wiki/index.php/97_Things_Every_Programmer_Should_Know" style="background-color: white;">97 Things Every Programmer Should Know</a><br />
Update: I came across <a href="http://dotnet.dzone.com/articles/characteristics-great">DZ article</a> which speaks what I was trying to cover here.</div>
techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-5985235217231979762012-03-10T13:52:00.002+05:302012-03-10T13:55:22.518+05:30How to test objects equality if they don't implement Object#equals()<br />
Problem: There are cases when you want to test whether two objects are equal, mean did they contain same state or not ? This occurs mostly when you're trying to test JAXB generated beans or any VO/DTO which doesnât' implement Object#equals() method or/and whose source code you can't modify .<br />
<br />
Solution: I knew there is a class (Commons lib's EqualsBuilder class) available which "reflectively" creates the equals method for you taking care all the rules for writing good equals method. But that class doesnât have a method to test whether two object are equal or not.<br />
At back of my mind, I know Mockito library internally uses the same commons class to solve my problem. I quickly scan the mockito jar and found this class. Here is the code snippet for the same (please note, you have to add mockito jar on classpath for this)<br />
<pre class="java" name="code">
import org.mockito.internal.matchers.apachecommons.ReflectionEquals;
.
.
.
public <T> void assertObjectEquals(final T expected, final T actual) {
assertTrue(new ReflectionEquals(actual,
(String[])null).matches(expected));
}
</pre>
This why Mockito is so famous, it makes your testing easy especially with mocks.<br />techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com2tag:blogger.com,1999:blog-8181692097334192490.post-17523209649256660502011-12-08T12:52:00.000+05:302011-12-14T22:08:37.631+05:30PIT Tests, a Mutation Testing<p>While wondering over internet, I just come across the "mutation testing" and here I blog about it. The blog largely said about one such framework "<a href="http://pitest.org/">PIT tests</a>".</p>
<p>When we say my code coverage is 80%, that only mean, in simple term, your unit tests cover 80% of your code base. Do they really tell you what your tests are really testing? - No.
To answer this, there is a thing that called as "mutation testing". The framework I am talking about is PIT tests; they said itâs like automation tests for your tests. Cool!</p>
<p>How does it work?</p>
<p>Well in plain simple language, it mutate (modify the byte code at runtime) some logical part, decision taking part of your code and then run tests against such modified code, if your test fail (called as mutation killed), your test is OK, if its passed (called mutation survived), beware, there might be some bug hidden there. So, more the mutation killed more good your tests are.</p>
<p>Example:</p>
<p>The simplest example might be,
<pre name="code" class="java">
if ( i < 5)
return "hi";
else
return "bye";
</pre>
Consider you write tests for it, and all are passing. Now, when pit tests executes over such tests, they mutated to this runtime as
<pre name="code" class="java">
if ( i < 5) // operator < mutate to <=
return "hi";
else
return "bye";
</pre>
And tests are rerun over such mutated code, if you really test such methods for boundary condition; everything will be good otherwise bug will occurs.
</p>
<p>There is few <a href="http://pitest.org/quickstart/mutators/">default mutators</a> that are applied while mutation testing using PIT.</p>
<p>Thatâs all, give it a try and see if its suits in your organization culture ;).</p>
<p>Whatâs missing?</p>
<p>Only thing I felt that need to improve for PIT tests are the HTML report visibility, the report doesnât clearly states how many test got the problem, means how many tests are killed and how many are survived. I think this info should be aggregated on index page.</p>techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-24512116464695992672011-10-09T11:25:00.000+05:302012-01-15T13:53:49.360+05:30Not 10, but 6 things about jMeterI list down some "good to know" things about jMeter. Hope it helps you while considering the jMeter scripts design, development and execution.<br />
<div class="MsoListParagraphCxSpFirst" style="mso-list: l0 level1 lfo1; text-indent: -.25in;">
</div>
<ol>
<li><span style="font: normal normal normal 7pt/normal 'Times New Roman';"> </span>Its open source Java tool for functional and
load testing.</li>
<li>Can be "extended" to create new
sampler, controller etc.</li>
<li>Module Controller - If your scripts are going
heavy and you found many copy-paste steps; in that case just create a module of
those steps. Module is like a function in programming.</li>
<li>Include controller - Some modules are global and
can be used in many scripts, in that case just include that JMX into your main
JMX, like you include JSP tag.</li>
<li>Parameterized Controller - Third party
controller which enable us to pass various runtime parameters to sample.
Usually sits on top of module controller.
<a href="http://code.google.com/p/jmeter-plugins/">http://code.google.com/p/jmeter-plugins/</a></li>
<li>jMeter scripts can be executed from ANT, it help
in automating the daily execution of scripts. (Can be triggered from nightly
build process from your CI server):
<a href="http://www.programmerplanet.org/pages/projects/jmeter-ant-task.php">http://www.programmerplanet.org/pages/projects/jmeter-ant-task.php</a> The same
site also got one XSLT for transforming your JTL (jMeter log of sript
execution) to HTML report. </li>
</ol>
I''ll update this list as I explore jMeter more!techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-39055751861597117112011-06-04T13:32:00.000+05:302012-01-15T13:51:50.732+05:30VM arguments in spring contextIn case you trying to access the VM arguments in spring application context, then just add the below bean definition in context file:<br />
<pre name="code" class="xml">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"></property>
</bean>
</pre><br />
And access the VM args as ${vm_property}, e.g if you passed the âDfoo=bar, which can be access as,<br />
<pre name="code" class="xml">
<bean class="com.company.test.MyClazz">
<property name="myProperty" value="${foo}"></property>
</bean>
</pre>techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-1729884874778790572011-04-08T20:53:00.000+05:302011-04-08T20:53:29.583+05:30Quick Fix: Selenium + FireFox 4Being a firefox fan, I just updated my current FF (3.6.x) to FF 4, everything goes well and I could see much improved FF both performance and UI wise, but I couldn't use selenium IDE with it (Yes, some time I do UI testing), so after some googling found 2 solutions:<br />
<br />
Solution #1: If you already have the selenium installed but its disabled because it's not supported by FF 4 yet, the fix (hack) is explained <a href="http://groups.google.com/group/selenium-users/browse_thread/thread/c7a225f0b0ec7670">here</a> (See Mark Collin reply)<br />
<br />
Solution #2: If you don't have selenium IDE installed, then simply download the latest supported but not yet released selenium IDE installer from <a href="http://groups.google.com/group/selenium-users/browse_thread/thread/c7a225f0b0ec7670">here</a> and install it just by dragging or opening it to FF window.techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-66257366472319154442011-03-13T13:37:00.000+05:302012-02-17T17:37:29.608+05:30What I've learned from TDDTDD, I'm practicing development using unit test from 1 year now and frankly speaking I'm loving it. I listed some points/notes/importance I learned from TDD. You might like to add some points or want to correct me, so please comment.<br />
<br />
Here the list goes:<br />
<ol>
<li>Caught 80% of bugs at first place before your code goes to production.</li>
<li>Explore and forces to think the development and design in proper Object Oriented way, means less class dependencies, loose coupling's, SRP etc.</li>
<li>You can fearlessly do refactoring and enhance the quality of existing code if you have enough unit test code surrounding. </li>
<li>If you have been reported any bug/issue in production code, write the unit test that produce that bug and fail(red), then fix the code(refactor) and ultimately make the unit test to success( green).</li>
<li>Gives idea about the usage of API you're developing.</li>
</ol>
I know this are not the only points which make TDD incredibly great practice, but I'll update this blog for some more points as they come along into my practices.<br />
<br />
Updates: Some TDD Quote.<br />
<br />
<blockquote>
Whenever you are tempted to type something in a print statement or a debugger expression, write it as a test. - Martin Fowler</blockquote>techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-33188210947012853892010-08-07T18:47:00.000+05:302011-01-16T19:48:38.783+05:30GlassFish V3 admin console taking too much time to load.If you have installed Glassfish V3 and trying to load admin console, but after signing in, is it taking too much time to get to the main page ? Do you have server.log entry like this:<br />
<code><br />
admin console: initSessionAttributes()<br />
Cannot refresh Catalog : Connection timed out<br />
</code><br />
then its time to tweak some files. Here its how:<br />
<br />
1. Update the %GLASSFISH_HOME/glassfish/domains/domain1/domain.xml<br />
<pre name="code" class="xml"><java-config>
<jvm-options>-Dcom.sun.enterprise.tools.admingui.NO_NETWORK=true</jvm-options>
</java-config>
</pre>This will block up the News item, the registration item, etc<br />
<br />
2. Remove update tool jar<br />
(Backup and remove this JAR)<br />
<blockquote>%GLASSFISH_HOME/glassfish/modules/console-updatecenter-plugin.jar</blockquote>Delete this dir:<br />
<blockquote>%GLASSFISH_HOME/glassfish/domains/domain1/osgi-cache</blockquote><blockquote>%GLASSFISH_HOME/glassfish/domains/domain1/generated</blockquote><br />
Now start the server (bin/asadmin start-domain) and you will see the admin console won't be hang up and take you directly to main page.techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com11tag:blogger.com,1999:blog-8181692097334192490.post-78760425854410374082010-06-02T19:56:00.000+05:302011-07-21T18:49:08.340+05:30Read file outside the JARHi All, Iâm back from loooong vacation. Actually havenât done anything great to blog about, only update is, I switched the companyâŚ<br />
<br />
Here is recent Java trick I found and I think I should share it..<br />
Problem: Iâm wondering about how can I read the file which is in the same directory of my executable JAR ?<br />
[Edited: Read the comment to get easy and obvious answer :)]<br />
Solution: Its simple, just get the current directory and append the file you want to access whose path is relevant to the JAR. Like<br />
<code><br />
/mydir/Myjar.jar<br />
/mydir/my.properties<br />
</code><br />
In order to read the âmy.propertiesâ, I just used the following code.<br />
<pre name="code" class="java">FileReader reader = new FileReader(new File(new File(â.â), âmy.propertiesâ));
</pre><br />
Simple.techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com2tag:blogger.com,1999:blog-8181692097334192490.post-16759158065376813992009-11-20T22:51:00.000+05:302009-12-28T12:44:28.213+05:30Easy Start with JNAJNA (Java Native Access) is the good and easy answer to the JNI(Java Native Interface). Those who find it cumbersome to to call C, C++ DLL functions using JNI, then JNA is for you. The project is hosted at <a href="https://jna.dev.java.net/">https://jna.dev.java.net/</a> .<br /><br />Here is my first encounter(experiment) with the JNA.<br /><br />Problem: I want to call one DLL function in Java program<br /><br />Solution: The first thing that comes into my mind is JNI, coz I heard a lot about it whenever something "native" has to be called in Java. Just while surfing for the more information on basic JNI programming, I came across the JNA project/api and find it interesting to give it try.<br /><br />Here are the basic two things you need to have in order to use JNA<br />1) JNA api JAR file (jna.jar):<br /><blockquote>Download it from <a href="https://jna.dev.java.net/source/browse/*checkout*/jna/trunk/jnalib/dist/jna.jar?rev=HEAD">here</a></blockquote><br />2) DLL which you want to call in your Java program<br /><blockquote>Now this may be the big thing for a guy who haven't worked on VC++, DLL, MFC etc things. So here is the quick link about how to create the DLL<br />http://www.icynorth.com/development/createdlltutorial.html</blockquote><br />This is the best about JNA, you don't need to write header file as that we need to do in JNI<br /><br />JAVA Code<br /><pre name="code" class="java"><br />import com.sun.jna.*;<br />import com.sun.jna.ptr.*;<br />/** Simple example of JNA interface mapping and usage. */<br />public class HelloWorld {<br /> // This is the standard, stable way of mapping, which supports extensive<br /> // customization and mapping of Java to native types.<br /> public interface TestLibrary extends Library {<br /> TestLibrary INSTANCE = (TestLibrary)<br /> Native.loadLibrary("TestDLL", TestLibrary.class);<br /> // Call C/c++ function<br /> void helloWorld(int n); <br /> }<br /><br /> public static void main(String[] args) {<br /> int n = TestLibrary.INSTANCE.helloWorld(1); <br /> }<br />}<br /></pre><br />C/C++ Code<br /><pre name="code" class="c"><br />extern "C" __declspec(dllexport) int helloWorld (int divider)<br />{<br /> return 77/divider;<br />}<br /></pre>techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com0tag:blogger.com,1999:blog-8181692097334192490.post-17266973200433956912009-08-24T22:21:00.000+05:302012-01-15T13:49:04.132+05:30How to know when FORM (bean) values changed by user or notMany times, developer want to know whether user has changed the HTML FORM value or values so that at server side action they can take the necessary action if some values has been changed or not changed at all. For example, once someone has requirement regarding whether user changed the IP address fields in the UPDATE HTML FORM, because if that value has been changed by the user, then he need to make several heavy network calls, which he wants to avoid if user doesn't change that single value. Also, recently someone wants to know if the FORM has changed by single value or submitted as it without any change.<br />
<br />
For this above scenario, there are two (best) possible solutions:<br />
<br />
<blockquote>
1. If you want to observe the value change for particular bean property, then use dummy variable in bean and if you do not wish to create one, then pass the previous bean value in query string.</blockquote>
<br />
How to make it:<br />
<pre class="java" name="code">public class MyForm
{
private String name;
private Integer number;
// I like to know if this 'number' value was changed or not
// Crete a dummy variable for this "number"
private Integer number_;
/////////////////////////////
public String getName() {
return name;
}
public void setName(String string) {
name = string;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer i) {
number = i;
}
// Getter and setter for number_
public Integer getNumber_() {
return number;
}
public void setNumber_(Integer i) {
number = i;
}
}</pre>
<br />
OR<br />
<br />
If you don't wanna create extra dummy variable, pass value as query string.<br />
<pre>
<!-- pass the number value as query string to the action -->
<form action="/MyAction.do?number=${requestScope.number}>
Name: <input type="text" name="name"/>
Number: <input type="text" name="number"/>
<input type="submit" value="Submit"/>
</form>
</pre>
<br />
The action path will be:<br />
<span style="font-style: italic;">/MyAction.do?number=123</span><br />
<br />
<blockquote>
2. If you're not concerned about any particular value change but like to know whether form values are different than the previously shown values, then use Object#hashCode();</blockquote>
<br />
How to make it:<br />
<pre class="java" name="code">public class MyForm
{
private String name;
private Integer number;
/////////////////////////////
public String getName() {
return name;
}
public void setName(String string) {
name = string;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer i) {
number = i;
}
@Override
/**
* This is my logic for getting unique hashcode or you can implement you own
*/
public int hashCode() {
String hashCode = name.hashCode() + "" + number.hashCode();
return hashCode.hashCode();
}
}</pre>
<br />
You have to pass the populated beans hashcode to the action class and compare it with the current bean instance; If they are same then it mean the bean values are unchangedâŚtechmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com2tag:blogger.com,1999:blog-8181692097334192490.post-23731559825900803652009-07-09T18:57:00.000+05:302009-08-09T19:51:07.390+05:30Syntax Highlighter for BloggerUpdate: Here is the simple two steps which will add "Syntax Highlighter" widget for blogger hosted blogs <br /><br />1. Go to : <a href="http://fazibear.googlepages.com/blogger.html" target="_blank">http://fazibear.googlepages.com/blogger.html</a><br />2. And click to : <a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://www.blogger.com/img/add/add2blogger_sm_b.gif"><img style="cursor:pointer; cursor:hand;width: 104px; height: 17px;" src="http://www.blogger.com/img/add/add2blogger_sm_b.gif" border="0" alt="" /></a><br />---------------------------------------------------------------------------------------<br />Today, one of my JR mate asked me about How did I add that syntax highlighter code in blogger ? OK, I knew I installed it from some blog, but not remembering the name of that site, so I googled it and all the hits shows me the way to install it using CSS defined and uploaded at googlepages site.<br />Here is the code project site for same from Google:<br /><a href="http://code.google.com/p/syntaxhighlighter/" target="_blank">http://code.google.com/p/syntaxhighlighter/</a> <br /><br />I tried this too, but with little success. Its not that easy.<br /><br />But, finally I found that blog and thus that post where author created the Blogger widget for syntax highlighter. Just add it and you can add code snippet in you blog.<br /><br />Here is that useful link:<br /><a href="http://fazibear.blogspot.com/2007/09/blogger-syntax-higlighter.html" taget="_blank">http://fazibear.blogspot.com/2007/09/blogger-syntax-higlighter.html</a>techmythoughtshttp://www.blogger.com/profile/10919524272960119315noreply@blogger.com6