Enlightensoft's Blog

Helping in your each step

  • Categories

  • Authors

Archive for the ‘Core Java’ Category

How to convert generic list to array: List to Long[] Array???

Posted by Pankil Patel on April 8, 2011

How to convert generic list to array: List<Long> to Long[] Array???

Main point in this question is to pass one argument (fixed length empty array of specific object type) to “toArray” method of  “Collection” interface.

public static void main(String[] args) {

A a = new A();

List<Long> longList = new ArrayList<Long>();
longList.add(23l);
longList.add(2l);
longList.add(3l);

a.setArrayLong((Long[])longList.toArray(new Long[longList.size()]));

}

public class A {

private Long[] arrayLong;

public Long[] getArrayLong() {
return arrayLong;
}

public void setArrayLong(Long[] arrayLong) {
this.arrayLong = arrayLong;
}

}

Posted in Core Java | Leave a Comment »

Audio – wav to mp3, flv to wave, flv to mp3, wav to pm file conversion

Posted by Pankil Patel on August 30, 2010

/**
*          AudioUtils.java File
*/
package co.cc.enlightensoft.util;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* This utils class would provide all Audio operations like convert Flv To Mp3
* etc.
*
* @author Pankil Patel
*
*/
public class AudioUtils {

private static Log LOG = LogFactory.getLog(FileUtils.class);

/**
*
* @param directory
* @return
* @throws IOException
*/
public static boolean convertFlvToMp3(String flvFile, String mp3Folder,
String mp3FileName) throws IOException {
String cmd = “ffmpeg -title \”" + mp3FileName + “\” -i \”" + flvFile
+ “\” -acodec mp3 -ac 2 -ab 128 -vn -y \”" + mp3Folder
+ mp3FileName + “.mp3\”";
LOG.info(“converFlvToMp3 cmd: ” + cmd);
Runtime.getRuntime().exec(cmd.split(” “));
System.out.println(“converFlvToMp3: Done………………”);
// Runtime.getRuntime().exec(cmd.split(” “));
return true;
}

/**
*
* @param directory
* @return
* @throws IOException
*/
public static boolean convertFlvToWav(String flvNameFileWithFullPath,
String wavFileNameWithFullPath) throws IOException {
String cmd = “ffmpeg -i ” + flvNameFileWithFullPath + ” -y “
+ wavFileNameWithFullPath;
LOG.info(“convertFlvToWav cmd: ” + cmd);
RuntimeUtils.executeCommand(cmd.split(” “));
System.out.println(“convertFlvToWav: Done………………”);
return true;
}

/**
*
* @param directory
* @return
* @throws IOException
*/
public static boolean convertWavToMP3(String wavNameFileWithFullPath,
String mp3FileNameWithFullPath) throws IOException {
String cmd = “lame -V2 ” + wavNameFileWithFullPath + ” “
+ mp3FileNameWithFullPath;
LOG.info(“convertWavToMP3 cmd: ” + cmd);
RuntimeUtils.executeCommand(cmd.split(” “));
System.out.println(“convertWavToMP3: Done………………”);
return true;
}

/**
* @param wavFileFolderPath
* @param genderCommand
* @return
* @throws IOException
*/
public static boolean convertWavToPM(String wavFileFullPath,
String genderCommand, String pmGeneratorPath) throws IOException {
String cmd = pmGeneratorPath + genderCommand + ” ” + wavFileFullPath;
LOG.info(“convertWavToPM cmd: ” + cmd);
RuntimeUtils.executeCommand(cmd.split(” “));
System.out.println(“convertWavToPM: Done………………”);
return true;
}
}

/**
*         RuntimeUtils.java File
*/
package co.cc.enlightensoft.util;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* @author Pankil Patel
*
*/
public class RuntimeUtils {
private static final Log LOG = LogFactory.getLog(RuntimeUtils.class);

/**
* Executes the given command and return the results as a list
*
* @param cmd
*            The command that is being executed.
* @return List The list of the out put
*/
public static List<String> executeCommand(String… cmd) {
Process process = null;
try {
process = Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
LOG.info(e.getMessage() + e);
e.printStackTrace();
}
BufferedReader localBufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String str;
ArrayList<String> localArrayList = null;
try {
str = localBufferedReader.readLine();

localArrayList = new ArrayList<String>();
while (str != null) {
localArrayList.add(str);
str = localBufferedReader.readLine();
}
} catch (IOException e) {
LOG.info(e.getMessage() + e);
e.printStackTrace();
}
return localArrayList;
}

/**
* Executes the given command and return the results as a list
*
* @param cmd
*            The command that is being executed.
* @return List The list of the out put
*/
public static List<String> executeCommand(String cmd) {
Process process = null;
try {
process = Runtime.getRuntime().exec(cmd);

try {// For Printing Error
process.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(
process.getErrorStream()));
String line = “”;
while ((line = buf.readLine()) != null) {
System.out.println(line);
}
} catch (InterruptedException e) {
LOG.info(e.getMessage() + e);
e.printStackTrace();
}

} catch (IOException e) {
LOG.info(e.getMessage() + e);
e.printStackTrace();
}
BufferedReader localBufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String str;
ArrayList<String> localArrayList = null;
try {
str = localBufferedReader.readLine();

localArrayList = new ArrayList<String>();
while (str != null) {
localArrayList.add(str);
str = localBufferedReader.readLine();
}
} catch (IOException e) {
LOG.info(e.getMessage() + e);
e.printStackTrace();
}
return localArrayList;
}
}

Posted in Core Java, Other | 1 Comment »

How to Execute command line command from java Application

Posted by Pankil Patel on August 22, 2010

Step 1: Write bellow two line in your code wherever you want to execute command from java application as it is executed from command prompt.

String cmd = “your command”;
Runtime.getRuntime().exec(cmd.split(” “));

Gooooooooooooooooooood Luck………………..

Posted in Core Java | Leave a Comment »

Thread Local

Posted by Pankil Patel on June 3, 2010

How to set & get value in thread specific local?

Step 1:

Create a class like bellow:

Step 2:

Set thread specific value in that.

Like: ABCThreadLocal.set(10);

Step 3:

Get that value in any time during that thread.

Like: ABCThreadLocal.get();

Hureeeeeeeeeeee Ready to use Your Thread Local which persist Object’s ( Integer in this case ) value during the thread execution.

Posted in Core Java | Leave a Comment »

Java Reflection

Posted by Pankil Patel on May 27, 2010

How to call method of specific class by Java Reflection?

Employee emp = new Employee();

String forMethodName = “Name”;
String forMethodCode = “Code”;
String forMethodRole = “Role”;

Method m1 = emp.getClass().getDeclaredMethod(“get” +forMethodName);
Method m2 = emp.getClass().getDeclaredMethod(“get” +forMethodCode );
Method m3 = emp.getClass().getDeclaredMethod(“get” +forMethodRole );

Object o1 = m1.invoke(emp);
Object o2 = m2.invoke(emp);
Object o3 = m3.invoke(emp);

Posted in Core Java | Leave a Comment »

Captcha in Struts 2

Posted by Pankil Patel on April 12, 2010

http://www.roseindia.net/struts/struts2/captcha/java-captcha-example.shtml

Posted in Core Java, Struts 2 | Leave a Comment »

Send EMAIL using Java Code

Posted by Pankil Patel on April 7, 2010

Required Jar:
javaMail1.2

Code:

package cc.co.enlightensof.sendmail.service.spring;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class TestJavaMailSenderImpl {
public static final String USERNAME = “proxibidinc@gmail.com”;
public static final String PASSWORD = “1qlchexaacuby”;
public static final String HOST = “smtp.gmail.com”;
// gmail-smtp.l.google.com or gmail-smtp-in.l.google.comans check if you are
// getting the same error?
// “gmail-smtp-in.l.google.com and “
public static final String PORT = “465″;
// public static final String PORT = “25″;
public Session mailSession;

public TestJavaMailSenderImpl() {
Properties props = new Properties();
props.put(“mail.smtp.user”, USERNAME);
props.put(“mail.smtp.host”, HOST);
props.put(“mail.smtp.port”, PORT);
props.put(“mail.transport.protocol”, “smtp”);
props.put(“mail.smtp.auth”, “true”);
props.put(“mail.smtp.socketFactory.class”,
“javax.net.ssl.SSLSocketFactory”);
props.put(“mail.smtp.socketFactory.fallback”, “false”);

Authenticator auth = new SMTPAuthenticator();
mailSession = Session.getInstance(props, auth);
}

public void postMail(String recipients[], String subject, String message,
String from) throws MessagingException {
Message msg = new MimeMessage(mailSession);

// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);

InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);

// Optional : You can also set your custom headers in the Email if you
// Want
msg.addHeader("MyHeaderName", "myHeaderValue");

// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
}

class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = TestJavaMailSenderImpl.USERNAME;
String password = TestJavaMailSenderImpl.PASSWORD;
return new PasswordAuthentication(username, password);
}
}

Main Class to run the code:

package cc.co.enlightensof.sendmail.service.spring;

import javax.mail.MessagingException;

public class Main {
public static void main(String[] args) {
TestJavaMailSenderImpl sendMail = new TestJavaMailSenderImpl();
String recipients[] = { “hello.pankilpatel@gmail.com” };
String subject = “Test”;
String message = “Simple mail”;
try {
sendMail.postMail(recipients, subject, message,
TestJavaMailSenderImpl.USERNAME);
System.out.println(“Sent……………………”);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}

Posted in Core Java, EMAIL | Leave a Comment »

Send SMS usign SMS Getway in JAVA

Posted by Pankil Patel on April 7, 2010

How to send SMS with java code using SMS getway?

Required Jars:
commons-codec-1.3
commons-httpclient-3.0.1
commons-logging-1.0.4

Code:

package com.es.sms.one;

//http://www.txtlocal.co.uk/api/
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* Class to help send SMS messages
*
* @author Pankil Patel
*/
public class SmsHelper {
private static final Log logger = LogFactory.getLog(SmsHelper.class);

private static final String PARAM_USER = “uname”;

private static final String PARAM_PASSWORD = “pword”;

private static final String PARAM_MESSAGE = “message”;

private static final String PARAM_SENDER = “from”;

private static final String PARAM_PHONE_NO = “selectednums”;

private static final String PARAM_INFO = “info”;

/**
* Send an SMS message via the gateway. Returns whether or not the message
* could be successfully sent.
*
* @param sender
* @param phoneNumber
* @param smsText
* @return
*/
public static boolean sendSMS_Live(final String sender,
final String phoneNumber, final String smsText) {
try {
final HttpClient client = new HttpClient();

final HttpMethod method = new GetMethod(
“https://www.txtlocal.com/sendsmspost.php”);

method.setQueryString(new NameValuePair[] {
new NameValuePair(PARAM_USER,
“email.id@gmail.com”),
new NameValuePair(PARAM_PASSWORD, “PASSWORD”),
new NameValuePair(PARAM_MESSAGE, smsText),
new NameValuePair(PARAM_SENDER, sender),
new NameValuePair(PARAM_PHONE_NO, phoneNumber),
new NameValuePair(PARAM_INFO, “1″), });

final int statusCode = client.executeMethod(method);
logger
.debug(“SmsHelper: QueryString>>> “
+ method.getQueryString());
logger.info(“SmsHelper: Status Text>>>”
+ HttpStatus.getStatusText(statusCode));
return true;
} catch (final Exception e) {
logger.error(“Exception sending SMS: ” + e.toString());
return false;
}
}
}
Main Class to run:
package com.es.sms.one;

//http://www.txtlocal.co.uk/api/

public class Test {
public static void main(String[] args) {
System.out.println(“Test”);
SmsHelper.sendSMS_Live(“Pankil Patel”, “+919725006017″, “Hi………….”);
System.out.println(“Done….”);
}
}

Posted in Core Java, SMS | 4 Comments »

File Download

Posted by Pankil Patel on March 16, 2010

http://www.daniweb.com/forums/thread154128.html#

Posted in Core Java | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.