Monday, May 12, 2008

Files sorter

/* if a file name is in the format -, this code can create respective directories and can move the files in the respective directories */

import java.io.File;

class SortingSongs {
public static void main(String[] args) {
// File dir = new File("D:\\Muvi");
// J:\Songs\B1- 1
// String dirToScan = "J:\\Songs\\B2 - 1";
String dirToScan = args[0];
File dir = new File(dirToScan);

String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i = 0; i < children.length; i++) {
String[] splittedName = children[i].split("-");
// System.out.println(splittedName[0]);
File newDirForSong = new File(dirToScan + "\\"
+ splittedName[0].trim());
if (newDirForSong.isDirectory()) {
// System.out.println(splittedName[0] + "is a directory");
} else {
newDirForSong.mkdir();
}

// System.out.println(i + " --- " +children[i]);
File fileToBeMoved = new File(dirToScan + "\\" + children[i]);

fileToBeMoved.renameTo(new File(dirToScan + "\\"
+ splittedName[0].trim() + "\\" + children[i]));
}
}

//System.out.println(args[0]);
}
}

Keeps checking the DB for a particular state

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class ReplicationErrorFixer extends TimerTask {
static String sql = "SELECT count(1)as COUNT "
+ "from dbo.product p,"
+ " dbo.product_price pp,v$instance vi "
+ "where p.project_number=pp.project_number and pp.country_code=pp.country_sold_in "
+ "and pp.country_code='US' and p.isbn in ('0077224183')";

static Connection conn;

static PreparedStatement ps;

static ResultSet rs;

static Timer timer = new Timer();

public static void main(String[] args) {
System.out.println("in main...");
preapareDBParams();
TimerTask tt = new ReplicationErrorFixer();
timer.schedule(tt, 0, 5 * 60 * 1000);
}

public void run() {
System.out.println("in run ... " + new Date());
try {
rs = ps.executeQuery();
while (rs.next()) {
int numberOfRecords = new Integer(rs.getString("COUNT"))
.intValue();
System.out.println("No of records = " + numberOfRecords);
if (numberOfRecords == 1) {
sendMail("1 records found. Trying to insert new record.");
boolean insSuc = insertRecord();
if (insSuc) {
timer.cancel();
closeObjects();
}
}

}
} catch (Exception e) {
e.printStackTrace();
}
}

public static void preapareDBParams() {

System.out.println("in preapareDBParams ...");
try {
Class.forName("oracle.jdbc.OracleDriver");
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@152.159.46.57:1521:prod", "scsingh",
"sh!v1234");
ps = conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

public void sendMail(String str) {
try {
System.out.println("will send a mail with content: " + str);
Properties props = new Properties();
props.put("mail.smtp.host", "205.246.29.36");
Session s = Session.getInstance(props, null);
InternetAddress from = new InternetAddress("mail@mail.com");
InternetAddress to = new InternetAddress("shivsi@rsgsystems.com");

MimeMessage message = new MimeMessage(s);
message.setFrom(from);
message.addRecipient(Message.RecipientType.TO, to);
message.setSubject(str);
message.setText(str + new Date());
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}

}

public boolean insertRecord() {
String insStr = "INSERT INTO dbo.product_price@product.world"
+ " VALUES ('US',1144057,'NET','USD','MHHE',3.5,Sysdate,'A','Manual_ALEKS_Price_Update',Sysdate,'US')";

try {
PreparedStatement insstmt = conn.prepareStatement(insStr);
insstmt.execute();
conn.commit();
sendMail("Insert was successful.");
return true;
} catch (SQLException e) {
sendMail("Insert was unsuccessful.");
e.printStackTrace();
return false;
}
}

public void closeObjects() {
try {
conn.close();
ps.close();
rs.close();
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
}
}

}

New File Notifier

/* This code scans a particular directory and sends an email if a new file is added / downloaded to that same directory */

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import javax.mail.internet.MimeMessage;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Properties;
import javax.mail.Message;
import java.util.Date;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import java.io.File;
import java.util.ArrayList;
public class FilesLister extends TimerTask
{
static String d_email = "email@gmail.com",
d_password = "",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "jawaharlal@gmail.com";

static Timer timer = new Timer();
ArrayList existingFiles = new ArrayList();
boolean firstTime = true;


public static void main(String[] args) {
//d_password=args[0];
TimerTask tt = new FilesLister();
timer.schedule(tt, 0, 5*60 * 1000);
}

public void sendMail(String str) {
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
//props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");

SecurityManager security = System.getSecurityManager();

try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
//session.setDebug(true);

MimeMessage msg = new MimeMessage(session);
msg.setText(str);
msg.setSubject(str);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
Transport.send(msg);
}
catch (Exception mex)
{
mex.printStackTrace();
}

}

public void run() {
System.out.println("in run ... " + new Date());
File dir = new File("D:\\Muvi");

String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i // Get filename of file or directory
String filename = children[i];
if (!(existingFiles.contains(filename)))
{
if (!firstTime)
{
sendMail("New file name : " + filename + " downloaded at : " + new Date());
}
existingFiles.add(filename);
}
//System.out.println(i + ". " + filename);
}
}
firstTime = false;
}

private class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(d_email, d_password);
}
}



}