filename
stringlengths 8
46
| code
stringlengths 184
6.34k
|
---|---|
BinarySearch.java |
public class BinarySearch {
//Heuristic: (([0-9,a-z,A-Z,_,$]+\s*\=\s*\(\s*[0-9,a-z,A-Z,_,$]+\s*\+\s*[0-9,a-z,A-Z,_,$]+\s*\)\s*/\s*2\s*;)|([0-9,a-z,A-Z,_,$]+\s*=\s*[0-9,a-z,A-Z,_,$]+\s*\+\s*\(\s*[0-9,a-z,A-Z,_,$]+\s*-\s*[0-9,a-z,A-Z,_,$]+\s*\)\s*/\s*2\s*;))
// imid = imin + (imax - imin)/2;
// imid = (imax + imin)/2;
public static int binarySearch1(int arr[], int key, int imin, int imax) {
//Implementation: Recursive, primitive type
if(imax < imin)
return -1;
int imid = (imin+imax)/2;
if(arr[imid] > key)
return binarySearch1(arr,key,imin,imid-1);
else if (arr[imid] < key)
return binarySearch1(arr,key,imid+1,imax);
else
return imid;
}
public static <T extends Comparable<T>> int binarySearch3(T[] arr, T key, int imin, int imax) {
//Implementation: Recursive, comparable type
if(imax < imin)
return -1;
int imid = (imin+imax)/2;
if(arr[imid].compareTo(key) > 0)
return binarySearch3(arr,key,imin,imid-1);
else if (arr[imid].compareTo(key) < 0)
return binarySearch3(arr,key,imid+1,imax);
else
return imid;
}
public static int binarySearch2(int arr[], int key) {
//Implementation: Iterative, primitive type.
int imin = 0;
int imax = arr.length - 1;
while(imin <= imax) {
int imid = imin + (imax - imin)/2;
if (key < arr[imid])
imax = imid-1;
else if (key > arr[imid])
imin = imid + 1;
else
return imid;
}
return -1;
}
public static <T extends Comparable<T>> int binarySearch4(T[] arr, T key) {
int imin = 0;
int imax = arr.length - 1;
while(imin <= imax) {
int imid = imin + (imax - imin)/2;
if (key.compareTo(arr[imid]) < 0)//(key < arr[imid])
imax = imid-1;
else if (key.compareTo(arr[imid]) > 0)//(key > arr[imid])
imin = imid + 1;
else
return imid;
}
return -1;
}
}
|
BubbleSort.java | public class BubbleSort {
public static void BubbleSortInt1(int[] num) {
boolean flag = true; // set flag to true to begin first pass
int temp; // holding variable
while (flag) {
flag = false; // set flag to false awaiting a possible swap
for (int j = 0; j < num.length - 1; j++) {
if (num[j] > num[j + 1]) // change to > for ascending sort
{
temp = num[j]; // swap elements
num[j] = num[j + 1];
num[j + 1] = temp;
flag = true; // shows a swap occurred
}
}
}
}
public static void BubbleSortInt2(int[] num) {
int last_exchange;
int right_border = num.length - 1;
do {
last_exchange = 0;
for (int j = 0; j < num.length - 1; j++) {
if (num[j] > num[j + 1])
{
int temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
last_exchange = j;
}
}
right_border = last_exchange;
} while (right_border > 0);
}
public static void BubbleSortFloat1(float[] num) {
boolean flag = true; // set flag to true to begin first pass
float temp; // holding variable
while (flag) {
flag = false; // set flag to false awaiting a possible swap
for (int j = 0; j < num.length - 1; j++) {
if (num[j] > num[j + 1]) // change to > for ascending sort
{
temp = num[j]; // swap elements
num[j] = num[j + 1];
num[j + 1] = temp;
flag = true; // shows a swap occurred
}
}
}
}
public static void BubbleSortFloat2(float[] num) {
int last_exchange;
int right_border = num.length - 1;
do {
last_exchange = 0;
for (int j = 0; j < num.length - 1; j++) {
if (num[j] > num[j + 1])
{
float temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
last_exchange = j;
}
}
right_border = last_exchange;
} while (right_border > 0);
}
public static void BubbleSortDouble1(double[] num) {
boolean flag = true; // set flag to true to begin first pass
double temp; // holding variable
while (flag) {
flag = false; // set flag to false awaiting a possible swap
for (int j = 0; j < num.length - 1; j++) {
if (num[j] > num[j + 1]) // change to > for ascending sort
{
temp = num[j]; // swap elements
num[j] = num[j + 1];
num[j + 1] = temp;
flag = true; // shows a swap occurred
}
}
}
}
public static void BubbleSortDouble2(double[] num) {
int last_exchange;
int right_border = num.length - 1;
do {
last_exchange = 0;
for (int j = 0; j < num.length - 1; j++) {
if (num[j] > num[j + 1])
{
double temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
last_exchange = j;
}
}
right_border = last_exchange;
} while (right_border > 0);
}
public static void BubbleSortLong1(long[] num) {
boolean flag = true; // set flag to true to begin first pass
long temp; // holding variable
while (flag) {
flag = false; // set flag to false awaiting a possible swap
for (int j = 0; j < num.length - 1; j++) {
if (num[j] > num[j + 1]) // change to > for ascending sort
{
temp = num[j]; // swap elements
num[j] = num[j + 1];
num[j + 1] = temp;
flag = true; // shows a swap occurred
}
}
}
}
public static void BubbleSortLong2(long[] num) {
int last_exchange;
int right_border = num.length - 1;
do {
last_exchange = 0;
for (int j = 0; j < num.length - 1; j++) {
if (num[j] > num[j + 1])
{
long temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
last_exchange = j;
}
}
right_border = last_exchange;
} while (right_border > 0);
}
public static void BubbleSortShort1(short[] num) {
boolean flag = true; // set flag to true to begin first pass
short temp; // holding variable
while (flag) {
flag = false; // set flag to false awaiting a possible swap
for (int j = 0; j < num.length - 1; j++) {
if (num[j] > num[j + 1]) // change to > for ascending sort
{
temp = num[j]; // swap elements
num[j] = num[j + 1];
num[j + 1] = temp;
flag = true; // shows a swap occurred
}
}
}
}
public static void BubbleSortShort2(short[] num) {
int last_exchange;
int right_border = num.length - 1;
do {
last_exchange = 0;
for (int j = 0; j < num.length - 1; j++) {
if (num[j] > num[j + 1])
{
short temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
last_exchange = j;
}
}
right_border = last_exchange;
} while (right_border > 0);
}
public static void BubbleSortByte1(byte[] num) {
boolean flag = true; // set flag to true to begin first pass
byte temp; // holding variable
while (flag) {
flag = false; // set flag to false awaiting a possible swap
for (int j = 0; j < num.length - 1; j++) {
if (num[j] > num[j + 1]) // change to > for ascending sort
{
temp = num[j]; // swap elements
num[j] = num[j + 1];
num[j + 1] = temp;
flag = true; // shows a swap occurred
}
}
}
}
public static void BubbleSortByte2(byte[] num) {
int last_exchange;
int right_border = num.length - 1;
do {
last_exchange = 0;
for (int j = 0; j < num.length - 1; j++) {
if (num[j] > num[j + 1])
{
byte temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
last_exchange = j;
}
}
right_border = last_exchange;
} while (right_border > 0);
}
public static <T extends Comparable<T>> void BubbleSortComparable1(T[] num) {
int j;
boolean flag = true; // set flag to true to begin first pass
T temp; // holding variable
while (flag) {
flag = false; // set flag to false awaiting a possible swap
for (j = 0; j < num.length - 1; j++) {
if (num[j].compareTo(num[j + 1]) > 0) // change to > for ascending sort
{
temp = num[j]; // swap elements
num[j] = num[j + 1];
num[j + 1] = temp;
flag = true; // shows a swap occurred
}
}
}
}
public static <T extends Comparable<T>> void BubbleSortComparable2(T[] num) {
int last_exchange;
int right_border = num.length - 1;
do {
last_exchange = 0;
for (int j = 0; j < num.length - 1; j++) {
if (num[j].compareTo(num[j + 1]) > 0)
{
T temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
last_exchange = j;
}
}
right_border = last_exchange;
} while (right_border > 0);
}
} |
CreateJavaProject.java | import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
public class CreateJavaProject {
public static IProject CreateJavaProject(String name, IPath classpath) throws CoreException {
// Create and Open New Project in Workspace
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IProject project = root.getProject(name);
project.create(null);
project.open(null);
// Add Java Nature to new Project
IProjectDescription desc = project.getDescription();
desc.setNatureIds(new String[] { JavaCore.NATURE_ID});
project.setDescription(desc, null);
// Get Java Project Object
IJavaProject javaProj = JavaCore.create(project);
// Set Output Folder
IFolder binDir = project.getFolder("bin");
IPath binPath = binDir.getFullPath();
javaProj.setOutputLocation(binPath, null);
// Set Project's Classpath
IClasspathEntry cpe = JavaCore.newLibraryEntry(classpath, null, null);
javaProj.setRawClasspath(new IClasspathEntry[] {cpe}, null);
return project;
}
}
|
CopyFileSamples.java | import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;
import java.util.Scanner;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class CopyFileSamples {
public static void copyFile1(File srcFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
FileChannel source = fis.getChannel();
FileChannel destination = fos.getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
fis.close();
fos.close();
}
public static void copyFile2(File srcFile, File destFile) throws IOException {
FileUtils.copyFile(srcFile, destFile);
}
public static void copyFile3(File srcFile, File destFile) throws IOException {
InputStream in = new FileInputStream(srcFile);
OutputStream out = new FileOutputStream(destFile);
byte[] buf = new byte[1024];
int len;
while((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
public static void copyFile4(File srcFile, File destFile) throws IOException {
InputStream in = new FileInputStream(srcFile);
OutputStream out = new FileOutputStream(destFile);
IOUtils.copy(in, out);
in.close();
out.close();
}
public static void copyFile5(File srcFile, File destFile) throws IOException {
InputStream in = new FileInputStream(srcFile);
OutputStream out = new FileOutputStream(destFile);
IOUtils.copyLarge(in, out);
in.close();
out.close();
}
public static void copyFile6(File srcFile, File destFile) throws FileNotFoundException {
Scanner s = new Scanner(srcFile);
PrintWriter pw = new PrintWriter(destFile);
while(s.hasNextLine()) {
pw.println(s.nextLine());
}
pw.close();
s.close();
}
}
|
CRC32FileChecksum.java | import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;
public class CRC32FileChecksum {
public static long checksum1(File file) throws IOException {
CRC32 crc = new CRC32();
FileReader fr = new FileReader(file);
int data;
while((data = fr.read()) != -1) {
crc.update(data);
}
fr.close();
return crc.getValue();
}
}
|
ConvertDateFormat.java | import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ConvertDateFormat {
public static String convertDateFormat(String date, String srcFormat, String destFormat) throws ParseException {
// Parse date string into a Date object using the source format
DateFormat sFormat = new SimpleDateFormat(srcFormat);
Date srcDate = sFormat.parse(date);
// Format the data object to produce a string using the destination format
DateFormat dFormat = new SimpleDateFormat(destFormat);
String retval = dFormat.format(srcDate);
// Return
return retval;
}
}
|
Fibonacci.java |
public class Fibonacci {
public static int getFibonacci(int n) {
if(n == 0)
return 0;
else if (n == 1)
return 1;
else
return getFibonacci(n-1) + getFibonacci(n-2);
}
}
|
DBUpdateAndRollback.java | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUpdateAndRollback {
public static void Sample1(String myField, String condition1, String condition2) throws SQLException {
Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost/test", "user", "password");
connection.setAutoCommit(false);
PreparedStatement ps = connection.prepareStatement("UPDATE myTable SET myField = ? WHERE myOtherField1 = ? AND myOtherField2 = ?");
ps.setString(1, myField);
ps.setString(2, condition1);
ps.setString(3, condition2);
// If more than 10 entries change, panic and rollback
int numChanged = ps.executeUpdate();
if(numChanged > 10) {
connection.rollback();
} else {
connection.commit();
}
ps.close();
connection.close();
}
public static void Sample2(String myField, String condition1, String condition2) throws SQLException {
Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost/test", "user", "password");
connection.setAutoCommit(false);
Statement st = connection.createStatement();
String sql = "UPDATE myTable SET myField = '" + myField + "' WHERE myOtherField1 = '" + condition1 + "' AND myOtherField2 = '" + condition2 + "'";
int numChanged = st.executeUpdate(sql);
// If more than 10 entries change, panic and rollback
if(numChanged > 10) {
connection.rollback();
} else {
connection.commit();
}
st.close();
connection.close();
}
}
|
CopyDirectoryTree.java | package database;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.*;
public class CopyDirectoryTree {
// copy AND isDirectory AND list
public static void copyDirectory1(Path src, Path dest) throws IOException {
Files.copy(src, dest);
if(Files.isDirectory(src)) {
for(String filename : src.toFile().list()) {
Path srcFile = src.resolve(filename);
Path destFile = dest.resolve(filename);
copyDirectory1(srcFile, destFile);
}
}
}
// preVisitDirectory AND visitFile AND walkFileTree AND copy
public static void copyDirectory2(final Path src, final Path dest) throws IOException {
Files.walkFileTree(src, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Files.copy(dir, dest.resolve(src.relativize(dir)));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.copy(file, dest.resolve(src.relativize(file)));
return FileVisitResult.CONTINUE;
}
});
}
}
|
GCD.java |
//Heuristic:
//((while\s*\(\s*[a-z,A-Z,0-9,_,$]+\s*!=\s*0\s*\).*[a-z,A-Z,0-9,_,$]+\s*=\s*[a-z,A-Z,0-9,_,$]+\s*%\s*[a-z,A-Z,0-9,_,$]+)|(while\s*\(\s*[a-z,A-Z,0-9,_,$]+\s*!=\s*[a-z,A-Z,0-9,_,$]+\s*\).*[a-z,A-Z,0-9,_,$]+\s*=\s*[a-z,A-Z,0-9,_,$]+\s*-\s*[a-z,A-Z,0-9,_,$]+)|(return\s+[a-z,A-Z,0-9,_,$]+\s*\(\s*[a-z,A-Z,0-9,_,$]+\s*,\s*[a-z,A-Z,0-9,_,$]+\s*%\s*[a-z,A-Z,0-9,_,$]+\)))
public class GCD {
// while(b != 0) AND b = a % b
// while\s*\(\s*[a-z,A-Z,0-9,_,$]+\s*!=\s*0\s*\)
// [a-z,A-Z,0-9,_,$]+\s*=\s*[a-z,A-Z,0-9,_,$]+\s*%\s*[a-z,A-Z,0-9,_,$]+
// while\s*\(\s*[a-z,A-Z,0-9,_,$]+\s*!=\s*0\s*\).*[a-z,A-Z,0-9,_,$]+\s*=\s*[a-z,A-Z,0-9,_,$]+\s*%\s*[a-z,A-Z,0-9,_,$]+
public static int gcd1(int a, int b) {
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}
// while(a != b) AND a = a - b
//while\s*\(\s*[a-z,A-Z,0-9,_,$]+\s*!=\s*[a-z,A-Z,0-9,_,$]+\s*\)
//[a-z,A-Z,0-9,_,$]+\s*=\s*[a-z,A-Z,0-9,_,$]+\s*-\s*[a-z,A-Z,0-9,_,$]+
//while\s*\(\s*[a-z,A-Z,0-9,_,$]+\s*!=\s*[a-z,A-Z,0-9,_,$]+\s*\).*[a-z,A-Z,0-9,_,$]+\s*=\s*[a-z,A-Z,0-9,_,$]+\s*-\s*[a-z,A-Z,0-9,_,$]+
public static int gcd2(int a, int b) {
while (a != b) {
if (a > b)
a = a - b;
else
b = b - a;
}
return a;
}
// return gcd3(b, a % b)
//return\s+[a-z,A-Z,0-9,_,$]+\s*\(\s*[a-z,A-Z,0-9,_,$]+\s*,\s*[a-z,A-Z,0-9,_,$]+\s*%\s*[a-z,A-Z,0-9,_,$]+\)
public static int gcd3(int a, int b) {
if (b == 0) {
return 1;
} else {
return gcd3(b, a % b);
}
}
} |
CreateRSAKeys.java | import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class CreateRSAKeys {
public static void main(String args[]) throws NoSuchAlgorithmException, IOException {
System.out.println(generateKeys1());
}
public static KeyPair generateKeys1() throws NoSuchAlgorithmException, IOException {
//Minimum Example
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = keyGen.generateKeyPair();
return keyPair;
}
public static void generateKeys2(int keySize, Path publicKey, Path privateKey) throws NoSuchAlgorithmException, IOException {
//Fuller Example
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(keySize);
KeyPair keyPair = keyGen.generateKeyPair();
PublicKey pubkey = keyPair.getPublic();
PrivateKey privkey = keyPair.getPrivate();
Files.createDirectories(publicKey.getParent());
Files.createFile(publicKey);
Files.createDirectories(privateKey.getParent());
Files.createFile(privateKey);
ObjectOutputStream oout = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(publicKey.toFile())));
oout.writeObject(pubkey);
oout.close();
oout = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(privateKey.toFile())));
oout.writeObject(privkey);
oout.close();
}
}
|
DeleteFolderRecursively.java | import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
public class DeleteFolderRecursively {
//isDirectory AND listFiles AND delete
public static void deleteRecursively1(File file) {
if (file.isDirectory()) {
for (File f : file.listFiles())
deleteRecursively1(f);
}
file.delete();
}
//walkFileTree AND delete AND postVisitDirectory AND visitFile
public static void deleteRecursively1(Path dir) throws IOException {
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
// try to delete the file anyway, even if its attributes
// could not be read, since delete-only access is
// theoretically possible
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
if (exc == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
} else {
// directory iteration failed; propagate exception
throw exc;
}
}
});
}
}
|
FileChooser.java | import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class FileChooser {
public static File chooseFileOpen(JFrame frame) {
File retval;
//Create and configure file chooser
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Select input file.");
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setMultiSelectionEnabled(false);
//Show dialog and wait for user input
int status = fc.showOpenDialog(frame);
//React to input
if(status == JFileChooser.APPROVE_OPTION) {
retval = fc.getSelectedFile();
} else if (status == JFileChooser.CANCEL_OPTION) {
retval = null;
} else {
retval = null;
}
//Cleanup
fc.setEnabled(false);
fc.setVisible(false);
//Return
return retval;
}
public static File chooseFileSave(JFrame frame) {
File retval;
//Create and configure file chooser
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Select input file.");
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setMultiSelectionEnabled(false);
//Show dialog and wait for user input
int status = fc.showSaveDialog(frame);
//React to input
if(status == JFileChooser.APPROVE_OPTION) {
retval = fc.getSelectedFile();
} else if (status == JFileChooser.CANCEL_OPTION) {
retval = null;
} else {
retval = null;
}
//Cleanup
fc.setEnabled(false);
fc.setVisible(false);
//Return
return retval;
}
public static File[] chooseFileOpenMultiple(JFrame frame) {
File retval[];
//Create and configure file chooser
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Select input file.");
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setMultiSelectionEnabled(true);
//Show dialog and wait for user input
int status = fc.showSaveDialog(frame);
//React to input
if(status == JFileChooser.APPROVE_OPTION) {
retval = fc.getSelectedFiles();
} else if (status == JFileChooser.CANCEL_OPTION) {
retval = null;
} else {
retval = null;
}
//Cleanup
fc.setEnabled(false);
fc.setVisible(false);
//Return
return retval;
}
public static File[] chooseFileDirectory(JFrame frame) {
File retval[];
//Create and configure file chooser
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Select input file.");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setMultiSelectionEnabled(false);
//Show dialog and wait for user input
int status = fc.showSaveDialog(frame);
//React to input
if(status == JFileChooser.APPROVE_OPTION) {
retval = fc.getSelectedFiles();
} else if (status == JFileChooser.CANCEL_OPTION) {
retval = null;
} else {
retval = null;
}
//Cleanup
fc.setEnabled(false);
fc.setVisible(false);
//Return
return retval;
}
//public static void main(String args[]) {
// JFrame frame = new JFrame();
// frame.setVisible(true);
// System.out.println(FileChooser.chooseFileOpen(frame));
// System.out.println(FileChooser.chooseFileSave(frame));
// System.out.println(FileChooser.chooseFileOpenMultiple(frame));
// frame.setVisible(false);
// frame.disable();
//}
}
|
EncryptFile.java | import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class EncryptFile {
public static void encryptFile(File in, File out, SecretKey key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {
// Create Cipher for Algorithm using Encryption Key
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE, key);
// Create File Read/Writers
FileInputStream fin = new FileInputStream(in);
FileOutputStream fout = new FileOutputStream(out);
// Create Cipher Output Stream
CipherOutputStream cout = new CipherOutputStream(fout, c);
// Read input writer and write encrypted version using cipher stream
int i;
byte[] data = new byte[1024];
while((i = fin.read(data)) != -1)
cout.write(data, 0, i);
// Clean-up
fin.close();
cout.close();
}
}
|
CallMethodUsingReflection.java | import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.NoSuchElementException;
//((getMethod)|(getDeclaredMethod))
//invoke
public class CallMethodUsingReflection {
public static Object callMethod1(Object object, String methodName, Object args[]) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//Caveat: this solution doesn't support some method signatures (e.g., those with primitive types)
Class<?> myClass = object.getClass();
Class<?>[] ptypes = new Class[args.length];
for(int i = 0; i < args.length; i++) {
ptypes[i] = args[i].getClass();
}
Method method = myClass.getMethod(methodName, ptypes);
Object returnVal = method.invoke(object, args);
return returnVal;
}
public static Object callMethod2(Object object, String methodName, Object params[], Class[] types) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// Uses getMethod
Class<?> myClass = object.getClass();
Method method = myClass.getMethod(methodName, types);
Object returnVal = method.invoke(object, params);
return returnVal;
}
public static Object callMethod3(Object object, String methodName, Object params[], Class[] types) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// Uses getDeclaredMethod and climbs up the superclasses
Method method = null;
Class<?> myClass = object.getClass();
NoSuchMethodException ex = null;
while(method == null && myClass != null) {
try {
method = myClass.getDeclaredMethod(methodName, types);
} catch (NoSuchMethodException e) {
ex = e;
myClass = myClass.getSuperclass();
}
}
if(method == null)
throw ex;
Object returnVal = method.invoke(object, params);
return returnVal;
}
public static void main(String args[]) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Integer[] params = {};
Class[] types = {};
Object retval = CallMethodUsingReflection.callMethod3(new GCD(), "getClass", (Object []) params, types);
System.out.println(retval);
}
}
|
ConnectToDatabaseJDBC.java | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class ConnectToDatabaseJDBC {
public static Connection getConnection1(String serverName, int port, String database, String driver, String username, String password) throws SQLException {
Connection conn = null;
Properties props = new Properties();
props.put("user", username);
props.put("password", password);
String url = "jdbc:" + driver + "://" + serverName + ":" + port + "/" + database;
conn = DriverManager.getConnection(url, props);
return conn;
}
public static Connection getConnection2(String serverName, int port, String database, String driver, String username, String password) throws SQLException {
Connection conn = null;
String url = "jdbc:" + driver + "://" + serverName + ":" + port + "/" + database;
conn = DriverManager.getConnection(url, username, password);
return conn;
}
}
|
DownloadWebpage.java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
public class DownloadWebpageSamples {
public static String downloadWebpage1(String address) throws MalformedURLException, IOException {
URL url = new URL(address);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
String page = "";
while((line = br.readLine()) != null) {
page += line + "\n";
}
br.close();
return page;
}
public static String downloadWebpage2(String address) throws MalformedURLException, IOException {
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(true);
String encoding = conn.getContentEncoding();
InputStream is = null;
if(encoding != null && encoding.equalsIgnoreCase("gzip")) {
is = new GZIPInputStream(conn.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
is = new InflaterInputStream(conn.getInputStream());
} else {
is = conn.getInputStream();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
String page = "";
while((line = br.readLine()) != null) {
page += line + "\n";
}
br.close();
return page;
}
public static String downloadWebpage3(String address) throws ClientProtocolException, IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(address);
HttpResponse response = client.execute(request);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
String page = "";
while((line = br.readLine()) != null) {
page += line + "\n";
}
br.close();
return page;
}
}
|
ExecuteExternalProcessAndReadInput.java | import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ProcessBuilder.Redirect;
import java.util.Map;
public class ExecuteExternalProcessAndReadInput {
// start AND ProcessBuilder AND (redirect)|(getInputStream|getOutputStream)
public static void execute1() throws IOException, InterruptedException {
//Create Process Builder with Command and Arguments
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
//Setup Execution Environment
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
//Setup execution directory
pb.directory(new File("myDir"));
//Handle Output Streams
File log = new File("log");
pb.redirectErrorStream(true);
pb.redirectOutput(Redirect.appendTo(log));
// Start Process
Process p = pb.start();
//Wait for process to complete
p.waitFor();
//Cleanup
p.destroy();
}
// exec AND (getInputStream)|(getErrorStream)
public static void execute2() throws IOException, InterruptedException {
// Get Runtime
Runtime rt = Runtime.getRuntime();
//Execute Process
Process p = rt.exec("myCommand");
//Redirect external process stdout to this program's stdout
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while((line = in.readLine()) != null)
System.out.println(line);
//Wait for process to complete and cleanup
p.waitFor();
p.destroy();
}
}
|
FTP_ApacheCommonsNet_Samples.java | import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPHTTPClient;
import org.apache.commons.net.ftp.FTPSClient;
public class FTP_ApacheCommonsNet_Samples {
public FTPClient sample1a(String server, int port, String username, String password) throws SocketException, IOException {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(server, port);
ftpClient.login(username, password);
return ftpClient;
}
public FTPClient sample1b(String server, String username, String password) throws SocketException, IOException {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(server);
ftpClient.login(username, password);
return ftpClient;
}
public FTPClient sample1c(String server, int port, String username, String password) throws SocketException, IOException {
FTPClient ftpClient = new FTPClient();
ftpClient.setDefaultPort(port);
ftpClient.connect(server);
ftpClient.login(username, password);
return ftpClient;
}
public FTPClient sample2a(String server, int port, String username, String password) throws SocketException, IOException {
FTPSClient ftpClient = new FTPSClient();
ftpClient.connect(server, port);
ftpClient.login(username, password);
return ftpClient;
}
public FTPClient sample2b(String server, String username, String password) throws SocketException, IOException {
FTPSClient ftpClient = new FTPSClient();
ftpClient.connect(server);
ftpClient.login(username, password);
return ftpClient;
}
public FTPClient sample2c(String server, int port, String username, String password) throws SocketException, IOException {
FTPSClient ftpClient = new FTPSClient();
ftpClient.setDefaultPort(port);
ftpClient.connect(server);
ftpClient.login(username, password);
return ftpClient;
}
public FTPClient sample3a(String ftpserver, int ftpport, String proxyserver, int proxyport, String username, String password) throws SocketException, IOException {
FTPHTTPClient ftpClient = new FTPHTTPClient(proxyserver, proxyport);
ftpClient.connect(ftpserver, ftpport);
ftpClient.login(username, password);
return ftpClient;
}
public FTPClient sample3b(String ftpserver, String proxyserver, int proxyport, String username, String password) throws SocketException, IOException {
FTPHTTPClient ftpClient = new FTPHTTPClient(proxyserver, proxyport);
ftpClient.connect(ftpserver);
ftpClient.login(username, password);
return ftpClient;
}
public FTPClient sample3c(String ftpserver, int ftpport, String proxyserver, int proxyport, String username, String password) throws SocketException, IOException {
FTPHTTPClient ftpClient = new FTPHTTPClient(proxyserver, proxyport);
ftpClient.setDefaultPort(ftpport);
ftpClient.connect(ftpserver);
ftpClient.login(username, password);
return ftpClient;
}
}
|
ExtactUsingRegex.java | import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtactUsingRegex {
// find AND start AND end AND compile AND matcher
public static List<String> extractMatches(String text, String pattern) {
List<String> matches = new LinkedList<String>();
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
while(m.find()) {
matches.add(text.subSequence(m.start(), m.end()).toString());
}
return matches;
}
//while\s*\(\s*[a-z,A-Z,0-9,_,$]+\s*\.\s*find\s*\(
//[a-z,A-Z,0-9,_,$]+\s*\.\s*start\s*\(
//[a-z,A-Z,0-9,_,$]+\s*\.\s*end\s*\(
//[a-z,A-Z,0-9,_,$]+\s*\.\s*compile\s*\(
//[a-z,A-Z,0-9,_,$]+\s*\.\s*matcher\s*\(
}
|
FTP_FTP4J_Samples.java | import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPFile;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
import it.sauronsoftware.ftp4j.FTPListParseException;
import java.io.IOException;
public class FTP_FTP4J_Samples {
public FTPClient sample1(String server, int port, String username, String password) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(server, port);
ftpClient.login(username, password);
return ftpClient;
}
public FTPClient sample2(String server, String username, String password) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(server);
ftpClient.login(username, password);
return ftpClient;
}
}
|
ParseXML2Dom.java | import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ParseXML2Dom {
//Heuristic: newDocumentBuilder AND parse
public static Document parse(File xmlFile) throws ParserConfigurationException, SAXException, IOException {
// Create DocumentBuilderFactory
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
// Configure Factory (this step will vary largely)
docFactory.setValidating(false);
docFactory.setNamespaceAware(true);
docFactory.setExpandEntityReferences(false);
// Use Factory to Build Document Builder (i.e., configured XML parser)
DocumentBuilder parser = docFactory.newDocumentBuilder();
//Parse the Document
Document document = parser.parse(xmlFile);
//Return the Document
return document;
}
public static void main(String args[]) throws ParserConfigurationException, SAXException, IOException {
Document document = ParseXML2Dom.parse(new File("/home/jeff/test.xml"));
NodeList nodeList = document.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
// do something with the current element
System.out.println(node.getNodeName());
System.out.println(node.getTextContent());
}
}
}
}
|
LoadFileIntoByteArray.java | import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
public class LoadFileIntoByteArray {
public static byte[] loadFile(File file) throws Exception {
if (!file.exists() || !file.canRead()) {
String message = "Cannot read file: " + file.getCanonicalPath();
throw new Exception(message);
}
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream data = new ByteArrayOutputStream();
int len = 0;
byte[] buf = new byte[1024];
while ((len = fis.read(buf)) >= 0) {
data.write(buf, 0, len);
}
fis.close();
byte[] retval = data.toByteArray();
data.close();
return retval;
}
}
|
ShuffleArrayInPlace.java | import java.util.Random;
public class ShuffleArrayInPlace {
// Heuristic
// Need to swap:
// a[i] = a[j] AND a[j] = tmp
// Need a random index:
// random.nextInt(
// #1:
// j = i + random.nextInt(length-i);
// #2:
// j = random.nextInt(i+1);
public static void shuffle1(int[] a) {
//Standard Fisher-Yates/Knuth Shuffle
int length = a.length;
Random random = new Random();
random.nextInt();
for(int i = 0; i < length; i++) {
//Chose index to swap with from i <= j < length
int j = i + random.nextInt(length-i);
//Swap
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
public static void shuffle2(int[] a) {
//Alternate Fisher-Yates/Knuth Shuffle
Random random = new Random();
random.nextInt();
for(int i = a.length-1; i >= 1; i--) {
//Choose index to swap from 0 <= j <= i
int j = random.nextInt(i+1);
//Swap
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
public static <T> void shuffle3(T[] a) {
//Standard Fisher-Yates/Knuth Shuffle for Object array
int length = a.length;
Random random = new Random();
random.nextInt();
for(int i = 0; i < length; i++) {
//Chose index to swap with from i <= j < length
int j = i + random.nextInt(length-i);
//Swap
T tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
//public static void main(String args[]) {
// int arr[] = {1,2,3,4,5,6,7,8,9,10};
// shuffle1(arr);
// for(int i : arr) {
// System.out.print(i + " " );
// }
// System.out.println();
// shuffle2(arr);
// for(int i : arr) {
// System.out.print(i + " " );
// }
// System.out.println();
// Integer arro[] = {1,2,3,4,5,6,7,8,9,10};
// shuffle3(arro);
// for(int i : arro) {
// System.out.print(i + " " );
// }
//}
}
|
OpenURLInSystemBrowser.java | import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class OpenURLInSystemBrowser {
public static void openURL(URI uri) throws IOException, URISyntaxException {
if(Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
desktop.browse(uri);
} else {
throw new UnsupportedOperationException("Desktop is not supported on this platform.");
}
}
}
|
PrimeFactors.java | import java.util.ArrayList;
import java.util.List;
public class PrimeFactors {
public static List<Integer> primeFactors1(int number) {
int n = number;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
return factors;
}
public static List<Integer> primeFactors2(int number) {
int n = number;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
return factors;
}
//public static void main(String args[]) {
// int i = 998;
// System.out.println(primeFactors1(i));
// System.out.println(primeFactors2(i));
//}
}
|
SendEMail.java | //FROM :http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
//Copyright © 2008-2014 Mkyong.com, all rights reserved.
import java.util.Properties;
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 SendMailTLS {
public static void main(String[] args) {
final String username = "username@gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
} |
LoadFont.java | import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
//HEURISTIC: createFont AND registerFont
// 1 - Create the font. 2 - Register the font with the graphics environemnt.
public class LoadFont {
public static void loadFont1(URL url) throws FontFormatException, IOException {
InputStream stream = url.openStream();
Font font = Font.createFont(Font.TRUETYPE_FONT, stream);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
}
public static void loadFont2(File file) throws FontFormatException, IOException {
FileInputStream stream = new FileInputStream(file);
Font font = Font.createFont(Font.TYPE1_FONT, stream);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
}
public static void loadFont3(File file) throws FontFormatException, IOException {
Font font = Font.createFont(Font.TRUETYPE_FONT, file);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
}
}
|
SetUpGraphicalViewerSelectionEventHandler.java | public class SetUpGraphicalViewerSelectionEventHandler {
public void setup() {
final GraphicalViewer viewer = new ScrollingGraphicalViewer();
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
}
});
}
}
|
ScreenShot.java | import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ScreenShot {
//createScreenCapture
public static void screenshot(File file) throws AWTException, IOException {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", file);
}
}
|
TestPalindrome.java | public class Plaindrome {
public static boolean isPalindrome(String original) {
//A not very efficient example
String reverse = "";
int length = original.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
return true;
else
return false;
}
}
|
InstantiateNamedClassUsingReflection.java | import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class InstantiateNamedClassUsingReflection {
public static Object instantiate(String clazz, Object[] pvalues, Class[] ptypes) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> c = Class.forName(clazz);
Constructor<?> constructor = c.getConstructor(ptypes);
Object obj = constructor.newInstance(pvalues);
return obj;
}
}
|
ResizeObjectArray.java | public class ResizeObjectArray {
public static Object[] resizeArray(Object[] oldArray, int newSize) {
//implementation for any object type
int oldSize = oldArray.length;
Class<?> elementType = oldArray.getClass().getComponentType();
Object newArray = java.lang.reflect.Array.newInstance(elementType, newSize);
int preserveLength = Math.min(oldSize, newSize);
if (preserveLength > 0) {
System.arraycopy(oldArray, 0, newArray, 0, preserveLength);
}
return (Object[]) newArray;
}
}
|
OpenFileInDesktopApp.java | import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class OpenFileInDesktopApp {
public static void openFileInDesktopApp(File file) throws IOException {
Desktop desktop = Desktop.getDesktop();
if(Desktop.isDesktopSupported()) {
desktop.open(file);
} else {
throw new UnsupportedOperationException("Not supported on this platform.");
}
}
}
|
ParseCSVFile.java | package database;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class ParseCSVFile {
// c AND ,
public static void parseCSV(File file) throws IOException {
StringTokenizer toks;
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
int lnum = 0;
while((line = in.readLine()) != null) {
lnum++;
toks = new StringTokenizer(line, ",");
int tnum = 0;
while(toks.hasMoreTokens()) {
tnum++;
System.out.println("Line# " + lnum + " Token# " + tnum + ": " + toks.nextToken());
}
}
in.close();
}
}
|
getMACAddresInStandardForm.java | import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class getMACAddresInStandardForm {
public static String getMyMacAddress1() throws SocketException, UnknownHostException {
InetAddress ip = InetAddress.getByName("192.168.0.12");
System.out.println(ip.getHostAddress());
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
String macStr = "";
for(int i = 0; i < mac.length; i++) {
int a = mac [i] & 0xFF;
if (a > 15) macStr += Integer.toHexString (a);
else macStr += "0" + Integer.toHexString (a);
if (i < (mac.length - 1)) {
macStr += "-";
}
}
return macStr;
}
public static String getMyMacAddress2() throws SocketException, UnknownHostException {
InetAddress ip = InetAddress.getByName("192.168.0.12");
System.out.println(ip.getHostAddress());
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
String macStr = sb.toString();
return macStr;
}
//public static void main(String args[]) throws SocketException, UnknownHostException {
// System.out.println(getMACAddresInStandardForm.getMyMacAddress2());
//}
}
|
SetUpScrollingGraphicalViewer.java | public class SetUpScrollingGraphicalViewer {
public void createPartControl(Model model) {
GraphicalViewer viewer = new ScrollingGraphicalViewer();
viewer.setContents(model);
}
}
|
MD5.java | public class MD5_Target {
public String getMD5(String password) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
byte byteData[] = md.digest();
StringBuffer sb = new StringBuffer();
for(int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
|
PlaySound.java | import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class PlaySound {
//Heuristic: getClip, open, start
public static void playSound1(File file) throws LineUnavailableException, UnsupportedAudioFileException, IOException {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);
clip.open(inputStream);
clip.start();
}
//getLine, read, write, getAudioInputStream
public static void playSound2(File file) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);
AudioFormat audioFormat = inputStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
SourceDataLine sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(audioFormat);
sourceLine.start();
int nbytes = 0;
byte[] data = new byte[1024];
while(nbytes != -1) {
nbytes = inputStream.read(data, 0, data.length);
sourceLine.write(data, 0, data.length);
}
sourceLine.drain();
sourceLine.close();
}
public static void main(String args[]) throws MalformedURLException, LineUnavailableException, UnsupportedAudioFileException, IOException {
//PlaySound.playSound1(new File("/Users/jeff/Downloads/11k16bitpcm.wav"));
PlaySound.playSound2(new File("/Users/jeff/Downloads/11k16bitpcm.wav"));
//while(true);
}
}
|
XMPPSendMessage.java | import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
public class XMPPSendMessage {
public static boolean sendMessage(String message, String receipient) {
//Create Message
JID jid = new JID(receipient);
Message msg = new MessageBuilder()
.withRecipientJids(jid)
.withBody(message)
.build();
//Send Message
XMPPService xmpp = XMPPServiceFactory.getXMPPService();
SendResponse status = xmpp.sendMessage(msg);
//Get and return if successful
boolean messageSent = false;
messageSent = (status.getStatusMap().get(jid) == SendResponse.Status.SUCCESS);
return messaageSent;
}
}
|
TransposeMatrix.java | package database;
public class TransposeMatrix {
public static int[][] transpose(int[][] m) {
int[][] retval = new int[m[0].length][m.length];
for(int i = 0; i < m.length; i++) {
for(int j = 0; j < m[0].length; j++) {
retval[j][i] = m[i][j];
}
}
return retval;
}
// public static void print(int[][] m) {
// for(int i = 0; i < m.length; i++) {
// for(int j = 0; j < m[0].length; j++) {
// System.out.println("m[" + (i+1) + "][" + (j+1) + "]=" + m[i][j]);
// }
// }
// }
// public static void main(String args[]) {
// int[][] om = new int[2][3];
// om[0][0] = 11;
// om[0][1] = 12;
// om[0][2] = 13;
// om[1][0] = 21;
// om[1][1] = 22;
// om[1][2] = 23;
// System.out.println(om.length);
// System.out.println(om[0].length);
// System.out.println("---");
// TransposeMatrix.print(om);
// System.out.println("---");
// TransposeMatrix.print(TransposeMatrix.transpose(om));
// }
}
|
UnZip.java |
public class UnZip {
public static void unzip1(File zipfile, File outputdir) throws IOException {
//Buffer for copying the files out of the zip input stream
byte[] buffer = new byte[1024];
//Create parent output directory if it doesn't exist
if(!outputdir.exists()) {
outputdir.mkdirs();
}
//Create the zip input stream
//OR ArchiveInputStream zis = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, new FileInputStream(zipfile));
ArchiveInputStream zis = new ZipArchiveInputStream(new FileInputStream(zipfile));
//Iterate through the entries of the zip file, and extract them to the output directory
ArchiveEntry ae = zis.getNextEntry(); // OR zis.getNextZipEntry()
while(ae != null) {
//Resolve new file
File newFile = new File(outputdir + File.separator + ae.getName());
//Create parent directories if not exists
if(!newFile.getParentFile().exists())
newFile.getParentFile().mkdirs();
if(ae.isDirectory()) { //If directory, create if not exists
if(!newFile.exists())
newFile.mkdir();
} else { //If file, write file
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
//Proceed to the next entry in the zip file
ae = zis.getNextEntry();
}
//Cleanup
zis.close();
}
public static void unzip2(File zipfile, File outputdir) throws IOException {
//Buffer for extracting files
byte[] buffer = new byte[1024];
//Zip file
ZipFile zip = new ZipFile(zipfile);
//Get entries
Enumeration<ZipArchiveEntry> files = zip.getEntries();
//Iterate through the entries
while(files.hasMoreElements()) {
//Get entry
ZipArchiveEntry ze = files.nextElement();
//Resolve entry file
File newFile = new File(outputdir + File.separator + ze.getName());
//Make parent directories
newFile.getParentFile().mkdirs();
if(ze.isDirectory()) { //If directory, create it
newFile.mkdir();
} else { //If file, extract it
InputStream is = zip.getInputStream(ze);
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while((len = is.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
}
}
//Cleanup
zip.close();
}
}
|
ZipFiles.java | import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFiles {
public static void ZipFiles(File zipfile, File[] files) throws IOException {
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(zipfile);
ZipOutputStream zos = new ZipOutputStream(fos);
// For Each File
for(int i = 0; i < files.length; i++) {
// Open File
File src = files[i];
FileInputStream fis = new FileInputStream(src);
//Create new zip entry
ZipEntry entry = new ZipEntry(src.getName());
zos.putNextEntry(entry);
//Write the file to the entry in the zip file (compressed)
int length;
while((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
//Close Original File
fis.close();
}
// Close Zip File
zos.close();
}
// public static void main(String args[]) throws IOException {
// File[] files = {new File("/media/jeff/ssd/test1"), new File("/media/jeff/ssd/test2")};
// ZipFiles.ZipFiles(new File("/media/jeff/ssd/zip.zip"), files);
// }
}
|
WritePDF.java | import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
/**
http://tutorials.jenkov.com/java-itext/getting-started.html
*/
public class WritePDF {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
document.open();
document.add(new Paragraph("A Hello World PDF document."));
document.close(); // no need to close PDFwriter?
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} |
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 35