To launch an AWS/EC2 instance, at first setting up a security group to specify what network traffic is allowed to reach the instance. Then select an AMI and launch an instance from it. And create a volume in the same zone of the instance and attach with it. Format the device and mount it to a directory. After that follow the steps to create SSL for Tomcat: (If any of this command say permission denied , then try to execute command with sudo)
1. For the tomcat we need java, so create a directory to save the Java Binary file.
mkdir /usr/java
cd /usr/java
2. Download jdk binary file (jdk-x-linux-ix.bin) here
Use URL http://www.oracle.com/technetwork/java/archive-139210.html
3. Execute the Binary file
/usr/java/jdk-x-linux-ix.bin
Now we have the Java in our device. Then Download the Tomcat and install it followed by the instructions:-
1. Create a directory to save the tomcat
mkdir /usr/tomcat
cd /usr/tomcat
2. Download tomcat source file (apache-tomcat-x.tar.gz) here
Use URL http://apache.hoxt.com/tomcat/tomcat-6/v6.0.32/bin/
3. Extract that file
tar -zxvf apache-tomcat-x.tar.gz
4. Edit the catalina.sh file
vim /usr/tomcat/apache-tomcat-x/bin/catalina.sh
#** Add at the top **
JAVA_HOME=/usr/java/jdk1.x.x_x
save and exit
5. Start the tomcat
/usr/tomcat/apache-tomcat-x/bin/startup.sh
6. We can see the logs by using the given command
tail -f /usr/tomcat/apache-tomcat-x/logs/catalina.out
7. Take the browser and enter the URL http://localhost
Now we can see the tomcat index page
8. To stop the tomcat
/usr/tomcat/apache-tomcat-x/bin/shutdown.sh
Now configure the SSL Certificate for tomcat. When you choose to activate SSL on your web server you will be prompted to complete a number of questions about the identity of your website and your company. Your web server then creates two cryptographic keys – a Private Key and a Public Key. The Public Key does not need to be secret and is placed into a Certificate Signing Request (CSR) – a data file also containing your details.
Create a self signed certificate authority (CA) and keystore.
1. Make a directory to hold the certs and keystore. This might be something like:
mkdir /usr/tomcat/ssl
cd /usr/tomcat/ssl
2. Generate a private key for the server and remember it for the next steps
openssl genrsa -des3 -out server.key 1024
Generating RSA private key, 1024 bit long modulus
…………………..++++++
…++++++
e is 65537 (0×10001)
Enter pass phrase for server.key:
Verifying – Enter pass phrase for server.key:
3. Generate a CSR (Certificate Signing Request). Give the data after executing this command
openssl req -new -key server.key -out server.csr
Enter pass phrase for server.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter ‘.’, the field will be left blank.
—–
Country Name (2 letter code) [GB]:
State or Province Name (full name) [Berkshire]:
Locality Name (eg, city) [Newbury]:
Organization Name (eg, company) [My Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server’s hostname) []:
Email Address []:
Please enter the following ‘extra’ attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
4. Remove the passphrasse from the key
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
Enter pass phrase for server.key.org:
writing RSA key
5. Generate the self signed certificate
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Signature ok
subject=/C=GB/ST=Berkshire/L=Newbury/O=My Company Ltd
Getting Private key
You should then submit the CSR. During the SSL Certificate application process, the Certification Authority will validate your details and issue an SSL Certificate containing your details and allowing you to use SSL. Typically an SSL Certificate will contain your domain name, your company name, your address, your city, your state and your country. It will also contain the expiration date of the Certificate and details of the Certification Authority responsible for the issuance of the Certificate.
Create a certificate for tomcat and add both to the keystore
1. Change the path to ssl
cd /usr/tomcat/ssl
2. Create a keypair for ‘tomcat’
keytool -genkey -alias tom -keyalg RSA -keystore tom.ks
Enter keystore password:
Re-enter new password:
What is your first and last name?
[Unknown]:
What is the name of your organizational unit?
[Unknown]:
What is the name of your organization?
[Unknown]:
What is the name of your City or Locality?
[Unknown]:
What is the name of your State or Province?
[Unknown]:
What is the two-letter country code for this unit?
[Unknown]:
Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?
[no]: yes
Enter key password for <tom>
(RETURN if same as keystore password):
Re-enter new password:
3. Generate a CSR (Certificate Signing Request) for tomcat
keytool -keystore tom.ks -alias tom -certreq -file tom.csr
Enter keystore password:
4. create unique serial number
echo 02 > serial.txt
(If this say permission denied then, mkfile call serial.txt and chmod of it -> then try)
5. Sign the tomcat CSR
openssl x509 -CA server.crt -CAkey server.key -CAserial serial.txt -req -in tom.csr -out tom.cer -days 365
Signature ok
subject=/C=Unknown/ST=Unknown/L=Unknown/O=Unknown/OU=Unknown/CN=Unknown
Getting CA Private Key
6. Import the server CA certificate into the keystore
keytool -import -alias serverCA -file server.crt -keystore tom.ks
Enter keystore password:
Owner: O=My Company Ltd, L=Newbury, ST=Berkshire, C=GB
Issuer: O=My Company Ltd, L=Newbury, ST=Berkshire, C=GB
Serial number: ee13c90cb351968b
Valid from: Thu May 19 02:12:51 EDT 2011 until: Fri May 18 02:12:51 EDT 2012
Certificate fingerprints:
MD5: EE:F0:69:01:4D:D2:DA:A2:4E:88:EF:DC:A8:3F:A9:00
SHA1: 47:97:72:EF:30:02:F7:82:BE:CD:CA:F5:CE:4E:ED:89:73:23:4E:24
Signature algorithm name: SHA1withRSA
Version: 1
Trust this certificate? [no]: yes
Certificate was added to keystore
7. Add the tomcat certificate to the keystore
keytool -import -alias tom -file tom.cer -keystore tom.ks
Enter keystore password:
Certificate reply was installed in keystore
To configure a secure (SSL) HTTP connector for Tomcat, verify that it is activated in the $TOMCAT_HOME/conf/server.xml file. Edit this file and add the following lines.
Tomcat configuration
1. Edit the given portion of tomcat configuretion file and change the port as 80
vim /usr/tomcat/apache-tomcat-6.0.13/conf/server.xml
“””””” <Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" /> “”””””
<Connector port="80" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
2. Add the given portion to server.xml and give your password in the password portion
<Connector port="443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
keystoreFile="tom.ks"
keystorePass="password"
clientAuth="false" sslProtocol="TLS" />
When you start the Tomcat Your web server will match your issued SSL Certificate to your Private Key. Your web server will then be able to establish an encrypted link between the website and your customer’s web browser.
Start the tomcat with SSL Certificate
1. Restart tomcat
/usr/tomcat/apache-tomcat-6.0.13/bin/shutdown.sh
/usr/tomcat/apache-tomcat-6.0.13/bin/startup.sh
2. Go to https://Public DNS name:443/
Then your browser shows a security issue. Click the Approve button. Then you can enter to the tomcat with your certificate. When a browser connects to a secure site it will retrieve the site’s SSL Certificate and check that it has not expired, it has been issued by a Certification Authority the browser trusts, and that it is being used by the website for which it has been issued. If it fails on any one of these checks the browser will display a warning to the end user letting them know that the site is not secured by SSL.
You are Done !!!
Refer from: http://www.migrate2cloud.com/blog/ssl-for-tomcat-on-awsec2
Search This Blog
Popular Posts
-
Let say we have a String something like below. String sample="abc*123"; We want to split this String by '*'. We can...
-
sound -Convert matrix of signal data to sound Syntax sound(y,Fs) sound(y,Fs,bits) Description sound(y,Fs) sends audio signal y to the speak...
-
There are new phones will remove within next few weeks from sony. Sony xperia tipo, sony xperia tipo dual Sony xperia dual has dual sim...
-
When i try to configure mysql with CAS There were lots of problem occurred and i cannot find a good tutorials about this.I followed some tut...
-
PROBLEM 7 By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st pr...
-
This delete the file f1 File f1 = new File(file); boolean success = f1.delete(); if (!success){ System.out.println("Deleti...
-
PROBLEM The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. ANSWER 142913828...
-
In this post i will show you how to configure tomcat 7.x for SSL protocol in windows First we want to generate certificate file using jav...
-
samsung smart app challenge 2012 This contest offers $4.08 million in cash prizes and mega marketing support for app promotion to the to...
-
If you did not format your flash drive, then check whether the files are in hidden mode. Then follow these steps: Click on the link below ...
Followers
Friday, December 7, 2012
Friday, November 30, 2012
How to convert String to Java.sql.date and Java.sql.time
DateFormat DOB = new SimpleDateFormat("yyyy-MM-dd");
String date ="\"1234-01-01\"";
java.sql.Date convertedDate=null;
try {
convertedDate = new java.sql.Date(DOB.parse(date.replaceAll("\"","")).getTime());
} catch (ParseException ex) {
ex.printStackTrace();
}
System.out.println(convertedDate);
split a String by * in java
Let say we have a String something like below.
String sample="abc*123";
We want to split this String by '*'. We can't do this directly.Because in split the * has a special meaning.
This not working,
String spl[]=sample.split("*");
Therefore, we should use something like below.
String spl[]=sample.split("\\*");
String sample="abc*123";
We want to split this String by '*'. We can't do this directly.Because in split the * has a special meaning.
This not working,
String spl[]=sample.split("*");
Therefore, we should use something like below.
String spl[]=sample.split("\\*");
execute batch of queries in one time using java and JDBC
Let say we have something like below.
String [] queries = { "insert into employee (name, city, phone) values ('A', 'X', '123')", "insert into employee (name, city, phone) values ('B', 'Y', '234')", "insert into employee (name, city, phone) values ('C', 'Z', '345')",}; Connection connection = new getConnection();Statement statemenet = connection.createStatement(); for (String query : queries) { statemenet.execute(query); //execute query one by one}statemenet.close();connection.close(); Execute all the queries one by one.This is not a good practice.We can use something like below.Execute all the queries in once. Connection connection = new getConnection();Statement statemenet = connection.createStatement();for (String query : queries) { statemenet.addBatch(query);}statemenet.executeBatch();statemenet.close();connection.close(); As well as we can avoid sql injection by using something like below. String sql = "insert into employee (name, city, phone) values (?, ?, ?)";Connection connection = new getConnection();PreparedStatement ps = connection.prepareStatement(sql);final int batchSize = 1000;int count = 0;for (Employee employee: employees) { ps.setString(1, employee.getName()); ps.setString(2, employee.getCity()); ps.setString(3, employee.getPhone()); ps.addBatch(); if(++count % batchSize == 0) { ps.executeBatch(); }}ps.executeBatch(); // insert remaining recordsps.close();connection.close(); Tuesday, November 20, 2012
Files on flash drive changed to shortcuts fix
If you did not format your flash drive, then check whether the files are in hidden mode. Then follow these steps:
- Click on the link below and download the file "AutorunExterminator":
- Extract it: Double-click on "AutorunExterminator"
- Plug your pendrive now
- This will remove the autorun.inf files from your pendrive and also from the drives
- Click on Start > Run, type cmd and click OK
- Here it is assumed your pendrive letter is G (change as necessary)
- Enter this command.
attrib -h -r -s /s /d g:\*.*
- Press Enter
- Now check for your files in on the pen drive
- Now download the Malwarebytes' Anti-Malware from this link:http://en.kioskea.net/download/download-105-malwarebytes-anti-malware
- Update it and perform a "Full Scan"
- Note : The default selected option is "Quick Scan"
Thursday, November 8, 2012
Configure CAS SSO with mysql database
When i try to configure mysql with CAS There were lots of problem occurred and i cannot find a good tutorials about this.I followed some tutorials but i failed.Finally i found the way.So i decided to write a post about it.I explain this in localhost
Prerequest
Install mysql on the machine and be sure it's working properly.I used the default settings of mysql.If you used different one, change the configuration according to it.(localhost:3306)
Download apache tomcat and configure it to allow SSL connection.( You can follow my previous post)
Download cas server source code package
Install apache maven
How
<!-- change test as your database name, and give username and password of mysql login credential-->
<bean
id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/test?autoReconnect=true"
p:password=""
p:username="root" />
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
database.hibernate.dialect=org.hibernate.dialect.MySQLDialect
Prerequest
Install mysql on the machine and be sure it's working properly.I used the default settings of mysql.If you used different one, change the configuration according to it.(localhost:3306)
Download apache tomcat and configure it to allow SSL connection.( You can follow my previous post)
Download cas server source code package
Install apache maven
How
- Go to CAS source code location -> cas-server-webapp ->src->main->webapp->WEB-INF
- Open deployerConfigContext.xml in a text editor
- Change the bean serviceRegistryDao in deployerConfigContext.xml to something like this
<bean id="serviceRegistryDao" class="org.jasig.cas.services.JpaServiceRegistryDaoImpl"
p:entityManagerFactory-ref="entityManagerFactory" />
<!-- This is the EntityManagerFactory configuration for Hibernate -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true"/>
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- change test as your database name, and give username and password of mysql login credential-->
<bean
id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/test?autoReconnect=true"
p:password=""
p:username="root" />
- Change following line
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
- Open cas.properties file
database.hibernate.dialect=org.hibernate.dialect.MySQLDialect
- Go to CAS source code location -> cas-server-webapp
- Open pom.xml and add following dependency according to your CAS version
<!--
Apache Commons DBCP
for Java 6 (use version 1.3 for Java 5 or lower)
-->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
<scope>runtime</scope>
</dependency>
<!--
Hibernate Core and Entity Manager
for CAS 3.5.0 and higher
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<!--
Hibernate Entity Manager
for CAS 3.4.2.1
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.5.0-CR-2</version>
</dependency>
<!--
MySQL Connector
-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.20</version>
</dependency>
Friday, October 26, 2012
Configure tomcat for SSL protocol
In this post i will show you how to configure tomcat 7.x for SSL protocol in windows
First we want to generate certificate file using java keytool
1. Open command prompt and go to bin folder of java installation
2. type following commands (i used my password as abcd@1234 (This is called keystore password).Please use your own)
Use alias as tomcat.There will be generate .keystore which is hold your key inside C:\key. Please make
sure there will be a directory called C:\key before type following command ( you can use your own
directory as well). You will be ask some questions.Please give as localhost when asking Your first
and Last Name( Here we give as localhost because we configure it in local machine.If you are configure tomcat in a server, Then you have to give the server name.For an example: If application hosting @ www.myapp.com then you have to use myapp as the Your First and Last Name).Others can be answered as you want.Type same password you use as
keystore password.Other wise there will be some error occurred when running tomcat.
Type following commands as it is.( Change passwords and locations you use as keystore password
and .keystore file generated
Now you having .keystore file inside c:\key (if you use the same location as tutorial) and file called cacerts %JAVA_HOME\jre\security . If you have those files that mean you are successfully generate certificate file.
Now lets configure tomcat
1. Go to tomcat install location and go to conf folder (in my case D:\tomcat\conf)
2. Open server.xml file in your favorite text editor
3. Find the commented line and comment out it
Before
<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->
After
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
4. Add the following lines in to that and change the bolded lines according to your configurations
<Connector port="8443" maxHttpHeaderSize="8192" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" disableUploadTimeout="true"
acceptCount="100" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keystoreFile="C:\Users\madura\Documents\.keystore"
keystorePass="abcd@1234"
truststoreFile="D:\Program Files\Apache Software Foundation\Apache Tomcat 7.0.22\security\cacerts"
SSLEnabled="true" protocol="org.apache.coyote.http11.Http11NioProtocol"/>
Now it is time t test this.
Congratulations.....
If not success please go to from the begining..
First we want to generate certificate file using java keytool
1. Open command prompt and go to bin folder of java installation
- CD %JAVA_HOME%\bin
2. type following commands (i used my password as abcd@1234 (This is called keystore password).Please use your own)
- D:\Program Files\Java\jdk1.6.0\bin>keytool -delete -alias tomcat -keypass abcd@1234
Use alias as tomcat.There will be generate .keystore which is hold your key inside C:\key. Please make
sure there will be a directory called C:\key before type following command ( you can use your own
directory as well). You will be ask some questions.Please give as localhost when asking Your first
and Last Name( Here we give as localhost because we configure it in local machine.If you are configure tomcat in a server, Then you have to give the server name.For an example: If application hosting @ www.myapp.com then you have to use myapp as the Your First and Last Name).Others can be answered as you want.Type same password you use as
keystore password.Other wise there will be some error occurred when running tomcat.
- D:\Program Files\Java\jdk1.6.0\bin>keytool -genkey -alias tomcat -keyalg RSA -keystore c:/key/.keystore
Type following commands as it is.( Change passwords and locations you use as keystore password
and .keystore file generated
- keytool -export -alias tomcat -keypass abcd@1234 -file server.crt -keystore c:/key/.keystore
- keytool -import -file server.crt -keypass abcd@1234 -keystore ..\jre\lib\security\cacerts
Now you having .keystore file inside c:\key (if you use the same location as tutorial) and file called cacerts %JAVA_HOME\jre\security . If you have those files that mean you are successfully generate certificate file.
Now lets configure tomcat
1. Go to tomcat install location and go to conf folder (in my case D:\tomcat\conf)
2. Open server.xml file in your favorite text editor
3. Find the commented line and comment out it
Before
<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->
After
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
4. Add the following lines in to that and change the bolded lines according to your configurations
<Connector port="8443" maxHttpHeaderSize="8192" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" disableUploadTimeout="true"
acceptCount="100" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keystoreFile="C:\Users\madura\Documents\.keystore"
keystorePass="abcd@1234"
truststoreFile="D:\Program Files\Apache Software Foundation\Apache Tomcat 7.0.22\security\cacerts"
SSLEnabled="true" protocol="org.apache.coyote.http11.Http11NioProtocol"/>
Now it is time t test this.
- Open command prompt and go to %CATALINA_HOME%\bin
- Type catalina.bat start (tomcat server will start now)
- Open a web browser and type https://localhost:8443 (If the configurations are ok , you will see the official tomcat server page
Congratulations.....
If not success please go to from the begining..
How to install tomcat in windows
In tnis tutorial i will explain how configure apache tomcat 7.x for SSL protocol (https://)
I used apache tomcat 7.xx for my configuration
1. download apache tomcat fresh copy from the official web site and extract it some location in your hard disk( i used D:/tomcat)
2. Right click on MyComputer and click on properties-> Advaced System Settings -> Environment Variables (in Advanced Tab)
3. Click on the New button in System variables and add Variable Name as CATALINA_HOME
Variable Value as tomcat installation location (in my case D:/tomcat)
Then click on OK
4. Find the path variable in system variable -> Click on Edit and add the ; at end of the value. Then append it to path to bin folder of tomcat (in my case D:/tomcat/bin). Click OK and exit
Now You are install tomcat in windows successfully.Then test the installation as below.
* Open command prompt
* go to tomcat install location/bin
* type catalina.bat start
* open a web browser and go to link localhost:8080
I used apache tomcat 7.xx for my configuration
1. download apache tomcat fresh copy from the official web site and extract it some location in your hard disk( i used D:/tomcat)
2. Right click on MyComputer and click on properties-> Advaced System Settings -> Environment Variables (in Advanced Tab)
Variable Value as tomcat installation location (in my case D:/tomcat)
Then click on OK
4. Find the path variable in system variable -> Click on Edit and add the ; at end of the value. Then append it to path to bin folder of tomcat (in my case D:/tomcat/bin). Click OK and exit
Now You are install tomcat in windows successfully.Then test the installation as below.
* Open command prompt
* go to tomcat install location/bin
- D:
- cd %CATALINA_HOME%
- cd bin
* type catalina.bat start
- There will be new window prompt and tomcat server may start
* open a web browser and go to link localhost:8080
- If tomcat installation successful , then official tomcat page will be loaded.
Monday, October 15, 2012
delete file using javascript
Only work with internet explorer
<script type="text/javascript">
// initialize ActiveXObject and create an object of Scripting.FileSystemObject.
var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.DeleteFile("C:\\Temp\\myFolder\\file.txt", true);
// OR
fso.DeleteFile("C:\\Temp\\myFolder\\*.txt", true);
fso = null;
</script>
create file in local directory using javascript
This is only work with Internet explorer
<html>
<head>
<script language="javascript">
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\Test.txt", true);
s.WriteLine('Hello');
s.Close();
}
</script>
</head>
<body onLoad="WriteToFile()">
</body>
</html>
Sunday, October 14, 2012
replace all html tags in a String using java
StringName.replaceAll("\\<.*?\\>", "").replaceAll("(?s)<!--.*?-->", "");
get data between two special character using java
Let say you want to get data between character ' and " of the below string
String str= 21*90'89"
You can do it really easy by using regular expression and java
Pattern pattern = Pattern.compile("'(.*?)\"");
Matcher matcher = pattern.matcher(str);
if (matcher.find())
{
System.out.println(matcher.group(1));
}
String str= 21*90'89"
You can do it really easy by using regular expression and java
Pattern pattern = Pattern.compile("'(.*?)\"");
Matcher matcher = pattern.matcher(str);
if (matcher.find())
{
System.out.println(matcher.group(1));
}
Tuesday, October 9, 2012
get root element in xml using javascript
var xmlDoc= // DOM object
var root = xmlDoc.documentElement;
var root = xmlDoc.documentElement;
Thursday, September 13, 2012
Google URL shortner
Your website url too long?
Visit http://goo.gl/ and shorten it.It is a google service.
Visit http://goo.gl/ and shorten it.It is a google service.
Friday, September 7, 2012
closing command prompt using java
import java.io.*;
import javax.swing.JOptionPane;
import java.net.BindException;
class Loader
{
public static void main(String as[])
{
try
{
System.out.println("Loading application.........");
//pass the name of your exe in place of my.exe
Process p = Runtime.getRuntime().exec("my.exe");
//getting inputstream reader from process
BufferedReader reader = new BufferedReader
(newInputStreamReader(p.getInputStream()));
String line = reader.readLine();
//exit from this class when get "Loaded" from your application
while (line.equals("Loaded") == false)
{
line = reader.readLine();
}
reader.close();
}
catch (Exception e)
{
}
}
}
make shortcut for program using vbscript
L_Welcome_MsgBox_Message_Text = _
"A shortcut to Notepad" & _
vbcrlf & "will be created on your desktop."
L_Welcome_MsgBox_Title_Text = _
"Windows Scripting Host Sample"
Call Welcome()
Dim WSHShell
Set WSHShell = _
WScript.CreateObject("WScript.Shell")
Dim MyShortcut, MyDesktop, DesktopPath
' Read desktop path using WshSpecialFolders object
DesktopPath = _
WSHShell.SpecialFolders("Desktop")
' Create a shortcut object on the desktop
Set MyShortcut = _
WSHShell.CreateShortcut( _
DesktopPath & "\Shortcut to notepad.lnk")
' Set shortcut object properties and save it
MyShortcut.TargetPath = _
WSHShell.ExpandEnvironmentStrings( _
"%windir%\notepad.exe")
MyShortcut.WorkingDirectory = _
WSHShell.ExpandEnvironmentStrings( _
"%windir%")
MyShortcut.WindowStyle = 4
MyShortcut.IconLocation = _
WSHShell.ExpandEnvironmentStrings( _
"%windir%\notepad.exe, 0")
MyShortcut.Save
WScript.Echo _
"A shortcut to Notepad now exists on your Desktop."
Sub Welcome()
Dim intDoIt
intDoIt = MsgBox(L_Welcome_MsgBox_Message_Text, _
vbOKCancel + vbInformation, _
L_Welcome_MsgBox_Title_Text )
If intDoIt = vbCancel Then
WScript.Quit
End If
End Sub
Java Call main() method of a class using another class in java
public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Class<?> cls = Class.forName("pkg1.pkg2.classname");
Method meth = cls.getMethod("main", String[].class);
String[] params = null; // init params accordingly
meth.invoke(null, (Object) params); // static method doesn't have an instance
}
Wednesday, August 29, 2012
open url in current window using javascript
content.wrappedJSObject.location='http://www.somepage.com'
Monday, August 27, 2012
get substring using javascript
stringName.substring(from, to)
ex:
var mystr="hello";
alert(mystr.substring(0,2));
result: "hel"
alert(mystr(2));
result: "llo"
ex:
var mystr="hello";
alert(mystr.substring(0,2));
result: "hel"
alert(mystr(2));
result: "llo"
get data of a cell in a table using javascript
go to required "td" tag (tdTag)
alert(tdTag.innerHTML);
alert(tdTag.innerHTML);
xpath creater from node using javascript
function createXPathFromElement(elm) {
var allNodes = document.getElementsByTagName('*');
for (segs = []; elm && elm.nodeType == 1; elm = elm.parentNode)
{
if (elm.hasAttribute('id')) {
var uniqueIdCount = 0;
for (var n=0;n < allNodes.length;n++) {
if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++;
if (uniqueIdCount > 1) break;
};
if ( uniqueIdCount == 1) {
segs.unshift('id("' + elm.getAttribute('id') + '")');
return segs.join('/');
} else {
segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]');
}
} else if (elm.hasAttribute('class')) {
segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]');
} else {
for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
if (sib.localName == elm.localName) i++; };
segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
};
};
return segs.length ? '/' + segs.join('/') : null;
};
function lookupElementByXPath(path) {
var evaluator = new XPathEvaluator();
var result = evaluator.evaluate(path, document.documentElement, null,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return result.singleNodeValue;
}
how to make a zip file using windows default zipping in bat file
This will create someArchive.zip file which included english.txt
set FILETOZIP=c:\english.txt
set TEMPDIR=C:\temp738
rmdir %TEMPDIR%
mkdir %TEMPDIR%
copy %FILETOZIP% %TEMPDIR%
echo Set objArgs = WScript.Arguments > _zipIt.vbs
echo InputFolder = objArgs(0) >> _zipIt.vbs
echo ZipFile = objArgs(1) >> _zipIt.vbs
echo CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipIt.vbs
echo Set objShell = CreateObject("Shell.Application") >> _zipIt.vbs
echo Set source = objShell.NameSpace(InputFolder).Items >> _zipIt.vbs
echo objShell.NameSpace(ZipFile).CopyHere(source) >> _zipIt.vbs
echo wScript.Sleep 2000 >> _zipIt.vbs
CScript _zipIt.vbs %TEMPDIR% C:\someArchive.zip
pause
Tuesday, August 21, 2012
how set environment variable using bat file
You can set environment variable using bat file in two different ways.
method 1:
This method is temporary way.It will set environment variable while executing the bat file
let say i want set environment varable MY_HOME as my c://windows drive
set MY_HOME=c://windows
method 2:
This method will set the environment variable permanently to user environment variable category.That mean that variable only valid for that user account.This is use a vb script to set that environment variable.But no need to install vb on your machine.vbscript just like bat commands but different.
write the vb script name in bat file (in my case it's name is demo.vbs)
my bat file:
@echo OFF
demo.vbs
vb script: (in this case inside c://windows folder)
Set objShell = WScript.CreateObject("WScript.Shell")
Set colUsrEnvVars = objShell.Environment("USER")
Set fso = CreateObject("Scripting.FileSystemObject")
colUsrEnvVars("MY_HOME") = fso.GetParentFolderName(wscript.ScriptFullName)
Remeber: This vbscript should be in the directory c://windows folder.Because it's add the system variable as the path where it's included.
**remember to restart the machine after run this bat.
method 1:
This method is temporary way.It will set environment variable while executing the bat file
let say i want set environment varable MY_HOME as my c://windows drive
set MY_HOME=c://windows
method 2:
This method will set the environment variable permanently to user environment variable category.That mean that variable only valid for that user account.This is use a vb script to set that environment variable.But no need to install vb on your machine.vbscript just like bat commands but different.
write the vb script name in bat file (in my case it's name is demo.vbs)
my bat file:
@echo OFF
demo.vbs
vb script: (in this case inside c://windows folder)
Set colUsrEnvVars = objShell.Environment("USER")
Set fso = CreateObject("Scripting.FileSystemObject")
colUsrEnvVars("MY_HOME") = fso.GetParentFolderName(wscript.ScriptFullName)
Remeber: This vbscript should be in the directory c://windows folder.Because it's add the system variable as the path where it's included.
**remember to restart the machine after run this bat.
Monday, August 20, 2012
delete a file using java
This delete the file f1
File f1 = new File(file);
boolean success = f1.delete();
if (!success){
System.out.println("Deletion failed.");
System.exit(0);
}else{
System.out.println("File deleted.");
}
Writing a DOM Document to an XML File
// This method writes a DOM document to a file
public static void writeXmlFile(Document doc, String filename) {
try {
// Prepare the DOM document for writing
Source source = new DOMSource(doc);
// Prepare the output file
File file = new File(filename);
Result result = new StreamResult(file);
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
} catch (TransformerConfigurationException e) {
} catch (TransformerException e) {
}
}
get an input from user using java popup
This will ask input from the user and store it in name variable
String name = JOptionPane.showInputDialog ( "String input text" );
demo:
String name = JOptionPane.showInputDialog ( "String input text" );
demo:
open default web browser using java in widows
This method will open your default web browser in windows and open the url "www.google.lk"
String url="www.google.lk"; //add required url here
try {
String osName = System.getProperty("os.name");
if (osName.startsWith("Windows"))
Runtime.getRuntime().exec(
"rundll32 url.dll,FileProtocolHandler " + url);
} catch (Exception ex) {
}
java swing :Adding and Removing an Item in a JList Component
The default model for a list does not allow the addition and removal of items. The list must be created with a DefaultListModel.
// Create a list that allows adds and removes DefaultListModel model = new DefaultListModel(); JList list = new JList(model); // Initialize the list with items String[] items = {"A", "B", "C", "D"}; for (int i=0; i<items.length; i++) { model.add(i, items[i]); } // Append an item int pos = list.getModel().getSize(); model.add(pos, "E"); // Insert an item at the beginning pos = 0; model.add(pos, "a");
This method replaces an item:
// Replace the 2nd item
pos = 1;
model.set(pos, "b");
These methods are used to remove items:
// Remove the first item pos = 0; model.remove(pos); // Remove the last item pos = model.getSize()-1; if (pos >= 0) { model.remove(pos); } // Remove all items model.clear();refferd from:http://www.exampledepot.com/egs/javax.swing/list_listaddrem.html
java swing : Getting the Selected Items in a JList Component
The following methods return the indices of the selected items:
// To create a list, see Creating a JList Component
// Get the index of all the selected items
int[] selectedIx = list.getSelectedIndices();
// Get all the selected items using the indices
for (int i=0; i<selectedIx.length; i++) {
Object sel = list.getModel().getElementAt(selectedIx[i]);
}
// Get the index of the first selected item
int firstSelIx = list.getSelectedIndex();
// Get the index of the last selected item
int lastSelIx = list.getMaxSelectionIndex();
// Determine if the third item is selected
int index = 2;
boolean isSel = list.isSelectedIndex(index);
// Determine if there are any selected items
boolean anySelected = !list.isSelectionEmpty();
// To create a list, see Creating a JList Component
// Get the index of all the selected items
int[] selectedIx = list.getSelectedIndices();
// Get all the selected items using the indices
for (int i=0; i<selectedIx.length; i++) {
Object sel = list.getModel().getElementAt(selectedIx[i]);
}
// Get the index of the first selected item
int firstSelIx = list.getSelectedIndex();
// Get the index of the last selected item
int lastSelIx = list.getMaxSelectionIndex();
// Determine if the third item is selected
int index = 2;
boolean isSel = list.isSelectedIndex(index);
// Determine if there are any selected items
boolean anySelected = !list.isSelectionEmpty();
Friday, August 17, 2012
how to read xml file using java
This is a really good blog which explain clearly how to read xml file using java.
http://gardiary.wordpress.com/2011/03/10/read-xml-file-in-java-using-sax-parser/
http://gardiary.wordpress.com/2011/03/10/read-xml-file-in-java-using-sax-parser/
what is firebug
Firebug is a nice tool basically developed as firefox extension.Although it is a firefox extension now it also developed as a google chrome extension.Firebug using for debug the web applications.It is help to find the errors in web pages.It shows the html codes and other web page related stuff itself.So user can edit the code and see the results in real time.
Many of web developers use this extension because of the easyness of usage.Also quality assurance people also use this to find element xpath and other related details for testing purposes.So it is really need to having some basic knowledge about this usefull tool.In this post i will give a basic introduction about it.
First of all let's install firebug in firefox.
1.Open firefox browser
2.Go to below link and click install firebug button
http://getfirebug.com/
when install it some popup will come and ask to allow the program.So you have to allow it.After installing firefox asks to restart.So click restart to restart the firefox.
3.After firefox restarting, see the right hand bottom corner of the fire fox.you will see an icon like below.
4.click on that icon.Then firebug will open.
5.Open a any web page and click on the firebug icon.Then firebug window will open.After that right click on an any element of the web page and click inspect element option from the popup menu.
Then all the details about that element will show in the firebug window.Such as element id,name etc..
Also you can edit the html code and see the changes in the webpage in real time.
This is only a basic introduction.If you really interest you can go through some tutorials in the internet.I hope to post another post about how to develop our own extension for firefox and firebug.
Many of web developers use this extension because of the easyness of usage.Also quality assurance people also use this to find element xpath and other related details for testing purposes.So it is really need to having some basic knowledge about this usefull tool.In this post i will give a basic introduction about it.
First of all let's install firebug in firefox.
1.Open firefox browser
2.Go to below link and click install firebug button
http://getfirebug.com/
when install it some popup will come and ask to allow the program.So you have to allow it.After installing firefox asks to restart.So click restart to restart the firefox.
3.After firefox restarting, see the right hand bottom corner of the fire fox.you will see an icon like below.
4.click on that icon.Then firebug will open.
5.Open a any web page and click on the firebug icon.Then firebug window will open.After that right click on an any element of the web page and click inspect element option from the popup menu.
Then all the details about that element will show in the firebug window.Such as element id,name etc..
Also you can edit the html code and see the changes in the webpage in real time.
This is only a basic introduction.If you really interest you can go through some tutorials in the internet.I hope to post another post about how to develop our own extension for firefox and firebug.
Thursday, August 16, 2012
sony new phones
There are new phones will remove within next few weeks from sony.
Sony xperia tipo, sony xperia tipo dual
Sony xperia dual has dual sim facility with android 4.0. This is the first dual sim phone made by sony.
SPECIFICATIONS
for xperia tipo dual: http://www.sonymobile.com/global-en/products/phones/xperia-tipo-dual/
for xperia tipo: http://www.sonymobile.com/global-en/products/phones/xperia-tipo/specifications/#black
Sony xperia tipo, sony xperia tipo dual
Sony xperia dual has dual sim facility with android 4.0. This is the first dual sim phone made by sony.
SPECIFICATIONS
for xperia tipo dual: http://www.sonymobile.com/global-en/products/phones/xperia-tipo-dual/
for xperia tipo: http://www.sonymobile.com/global-en/products/phones/xperia-tipo/specifications/#black
set java home using putty
set jdk home ("/opt/jdk_1.6/" is the path of java installation in server which i use)
export JAVA_HOME=/opt/jdk_1.6/
set jre home
export JRE_HOME=/opt/jdk_1.6/jre
get time stamp using java
class:
package com.mkyong.common;
import java.sql.Timestamp;
import java.util.Date;
public class GetCurrentTimeStamp
{
public static void main( String[] args )
{
java.util.Date date= new java.util.Date();
System.out.println(new Timestamp(date.getTime()));
}
}
output
2010-03-08 14:59:30.252
Tuesday, July 17, 2012
Project Euler Problem 25 in Java
PROBLEM
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits?
ANSWER
4782
JAVACODE
import java.math.BigInteger;
public class Problem25 {
public static void main(String[]args){
int term=3;
BigInteger pr=new BigInteger("1");
BigInteger in=new BigInteger("2");
for (; in.toString().length()<1000; ) {
BigInteger tm=pr;
pr=in;
in=in.add(tm);
term++;
}
System.out.println(term);
}
}
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits?
ANSWER
4782
JAVACODE
import java.math.BigInteger;
public class Problem25 {
public static void main(String[]args){
int term=3;
BigInteger pr=new BigInteger("1");
BigInteger in=new BigInteger("2");
for (; in.toString().length()<1000; ) {
BigInteger tm=pr;
pr=in;
in=in.add(tm);
term++;
}
System.out.println(term);
}
}
Project Euler Problem 16 in Java
PROBLEM
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
ANSWER
1366
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
ANSWER
1366
JAVA CODE
import java.math.BigInteger;
public class Problem16 {
public static void main(String[]args){
BigInteger mul=new BigInteger("1");
BigInteger bg=new BigInteger("2");
for (int i = 0; i < 1000; i++) {
mul=mul.multiply(bg);
}
int sum=0;
String text=mul.toString();
for (int i = 0; i < text.length(); i++) {
sum+=Integer.parseInt(new Character(text.charAt(i)).toString());
}
System.out.println(sum);
}
}
Project Euler Problem 9 in Java
PROBLEM
A Pythagorean triplet is a set of three natural numbers, a b c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
ANSWER
31875000
JAVA CODE
public class Problem9 {
public static void main(String[]args){
int a=3;
int b=4;
int c=1000-(b+a);
int ans=0;
boolean find=false;
for (int i = 4; i < 496; i++) {
for (int j = 5; j < 499; j++) {
if((Math.pow(a,2)+Math.pow(b,2))==Math.pow(c,2)){
ans=a*b*c;
System.out.println("a="+a+"b="+b+"c="+c);
find=true;
break;
}
b=j;
c=1000-(b+a);
}
a=i;
if(find)
break;
}
System.out.println(ans);
}
}
A Pythagorean triplet is a set of three natural numbers, a b c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
ANSWER
31875000
JAVA CODE
public class Problem9 {
public static void main(String[]args){
int a=3;
int b=4;
int c=1000-(b+a);
int ans=0;
boolean find=false;
for (int i = 4; i < 496; i++) {
for (int j = 5; j < 499; j++) {
if((Math.pow(a,2)+Math.pow(b,2))==Math.pow(c,2)){
ans=a*b*c;
System.out.println("a="+a+"b="+b+"c="+c);
find=true;
break;
}
b=j;
c=1000-(b+a);
}
a=i;
if(find)
break;
}
System.out.println(ans);
}
}
java code for eular project problem 20
PROBLEM
n! means n (n 1) ... 3 2 1
For example, 10! = 10 9 ... 3 2 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
ANSWER
648
JAVA CODE
public class Problem20 {
public static void main(String[]args){
int ans=0;
BigInteger val=getNum(100);
String data=val.toString();
for (int i = 0; i < data.length(); i++) {
ans+=Integer.parseInt(new Character(data.charAt(i)).toString());
}
System.out.println(ans);
}
private static BigInteger getNum(int i) {
BigInteger ret=new BigInteger("1");
for (int j = 1; j <= i; j++) {
ret=ret.multiply(new BigInteger(Integer.toString(j)));
}
return ret;
}
}
n! means n (n 1) ... 3 2 1
For example, 10! = 10 9 ... 3 2 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
ANSWER
648
JAVA CODE
public class Problem20 {
public static void main(String[]args){
int ans=0;
BigInteger val=getNum(100);
String data=val.toString();
for (int i = 0; i < data.length(); i++) {
ans+=Integer.parseInt(new Character(data.charAt(i)).toString());
}
System.out.println(ans);
}
private static BigInteger getNum(int i) {
BigInteger ret=new BigInteger("1");
for (int j = 1; j <= i; j++) {
ret=ret.multiply(new BigInteger(Integer.toString(j)));
}
return ret;
}
}
answer java code for eular problem 10
PROBLEM
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
ANSWER
142913828922
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
ANSWER
142913828922
JAVA CODE
public class Problem10 {
public static void main(String[]args){
primeGenerator();
}
private static void primeGenerator() {
int max=2000000;
BigInteger bg=new BigInteger("0");
for (int j = 2; j < max; j++) {
boolean prime=true;
for (int i = 2; i <= (int)Math.sqrt(j); i++) {
if(j%i==0 )
prime=false;
}
if(prime){
BigInteger add=new BigInteger(Integer.toString(j));
bg=bg.add(add);
}
}
System.out.println("ans="+bg);
}
}
java code for eular project problem5
PROBLEM
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
ANSWER
232792560
JAVA CODE
public class Problem5 {
public static void main(String[]args){
int ans=0;
for (int i = 100000000; i <1000000000; i++) {
boolean state=true;
for (int j = 3; j <21; j++) {
ans=i;
if(i%j!=0||i==9999999){
//ans=-1;
state=false;
break;
}
}
if(state){
break;
}
}
System.out.println(ans);
}
}
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
ANSWER
232792560
JAVA CODE
public class Problem5 {
public static void main(String[]args){
int ans=0;
for (int i = 100000000; i <1000000000; i++) {
boolean state=true;
for (int j = 3; j <21; j++) {
ans=i;
if(i%j!=0||i==9999999){
//ans=-1;
state=false;
break;
}
}
if(state){
break;
}
}
System.out.println(ans);
}
}
Monday, July 16, 2012
java answer for eular project problem 7
PROBLEM 7
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
ANSWER
104743
JAVA CODE
public class Problem7 {
public static void main(String[]args){
primeGenerator();
}
private static void primeGenerator() {
int max=775146;
int primeCount=0;
int ans=0;
for (int j = 2; j < max; j++) {
boolean prime=true;
for (int i = 2; i <= (int)Math.sqrt(j); i++) {
if(j%i==0 )
prime=false;
}
if(prime){
primeCount++;
ans=j;
}
if(primeCount>=10001)
break;
}
System.out.println("ans="+ans);
}
}
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
ANSWER
104743
JAVA CODE
public class Problem7 {
public static void main(String[]args){
primeGenerator();
}
private static void primeGenerator() {
int max=775146;
int primeCount=0;
int ans=0;
for (int j = 2; j < max; j++) {
boolean prime=true;
for (int i = 2; i <= (int)Math.sqrt(j); i++) {
if(j%i==0 )
prime=false;
}
if(prime){
primeCount++;
ans=j;
}
if(primeCount>=10001)
break;
}
System.out.println("ans="+ans);
}
}
eular project-problem6
PROBLEM 6
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
ANSWER
25164150
JAVA CODE
public class Problem6 {
public static void main(String[]args){
int sumOfTheSquares=0;
int squareOfTheSum=0;
for (int i = 0; i <101; i++) {
sumOfTheSquares+=(int)Math.pow(i, 2);
squareOfTheSum+=i;
}
System.out.println((int)Math.pow(squareOfTheSum,2)-sumOfTheSquares);
}
}
answer for eular project-problem4
PROBLEM
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.
Find the largest palindrome made from the product of two 3-digit numbers.
ANSWER
906609
JAVA CODE
public class Palindrome {
public static void main(String[]args){
int palindrome=0;
for (int i = 999; i >0; i--) {
for (int j = 999; j>0; j--) {
int prod=i*j;
String forward=Integer.toString(prod);
String reverse=new StringBuffer(forward).reverse().toString();
//System.out.println(forward+"back="+reverse);
if(forward.equalsIgnoreCase(reverse)&&prod>palindrome){
palindrome=i*j;
break;
}
}
}
System.out.println(palindrome);
}
}
answer for eula project- problem3
PROBLEM
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
ANSWER
6857
JAVA CODE
import java.math.BigInteger;
public class PrimeFactor {
public static void main(String[]args){
BigInteger req=new BigInteger("600851475143");
primeGenerator(req);
}
private static void primeGenerator(BigInteger req) {
int max=775146;//sqrt of 600851475143
int ans=0;
for (int j = 2; j < max; j++) {
boolean prime=true;
for (int i = 2; i <= (int)Math.sqrt(j); i++) {
if(j%i==0 )
prime=false;
}
if(prime){
BigInteger bi=new BigInteger(Integer.toString(j));
BigInteger mode=new BigInteger("0");
if(req.mod(bi).equals(mode) &&ans<j){
ans=j;
}
}
}
System.out.println("ans="+ans);
}
}
Subscribe to:
Comments (Atom)
Total Pageviews
Blog Archive
-
▼
2012
(93)
-
►
August
(18)
- open url in current window using javascript
- get substring using javascript
- get data of a cell in a table using javascript
- xpath creater from node using javascript
- remove directory using bat file
- how to make a zip file using windows default zippi...
- how set environment variable using bat file
- delete a file using java
- Writing a DOM Document to an XML File
- get an input from user using java popup
- open default web browser using java in widows
- java swing :Adding and Removing an Item in a JList...
- java swing : Getting the Selected Items in a JList...
- how to read xml file using java
- what is firebug
- sony new phones
- set java home using putty
- get time stamp using java
-
►
July
(13)
- Project Euler Problem 25 in Java
- Project Euler Problem 16 in Java
- Project Euler Problem 9 in Java
- java code for eular project problem 20
- answer java code for eular problem 10
- java code for eular project problem5
- java answer for eular project problem 7
- eular project-problem6
- answer for eular project-problem4
- answer for eula project- problem3
-
►
August
(18)







