There are two ways to create a backup snapshot of compute engine persistent disks. You can either take a snapshot from the Google cloud console or run gcloud snapshot command from the command line. The following command creates a snapshot (backup) of the disk named "mydisk1" created in "asia-east1-a" availability zone,
gcloud compute disks snapshot mydisk1 --zone=asia-east1-a
If you want to enable automatic daily or weekly backups, you need to add the above command in a cron job. The cron job for automatic backups can be run in a VM in the compute engine or in a Docker container in Google Container Engine. Configuring the above command in cron requires the following steps,
- Install Google Cloud SDK (required for the gcloud command). If you are configuring cron in a Linux VM, follow these instructions to install Google Cloud SDK. If you are using Google Container Engine, you can create a custom container with Google Cloud SDK from this base image. Such a container can be used for all maintenance activities of your production environment.
- Create a file named cronfile with the following content,
PATH=/google-cloud-sdk/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/sbin
0 23 * * * /myfolder/backup.sh
The above cronfile will run the backup.sh every day at 11pm. Note the use of PATH variable. Please change the first path element to point to the folder where gcloud command is located.
- Create the backup.sh script with the following content (don't forget to change zone for your disk),
gcloud compute disks snapshot mydisk1 --zone=asia-east1-a
Ensure that the backup.sh is executable by running the following command,
chmod +x backup.sh
-
Finally enable the cronfile by configuring it as a cron job for a user account.
crontab -u root cronfile
cron reload
Posted in Google Cloud | Comments Off on Automatic Backup of Compute Engine Persistent Disks in Google Cloud Platform
The following Java program copies files with .java extension from one folder to another folder. You can easily change the extension .java to anything you want. For example, you might want to copy just .txt files from one directory to another.
This program takes two input parameters. The first one is the source directory and the second one is the target directory. Please ensure that you enter full path of the directories. This program also displays errors encountered if any during the file copying.
Note that this program doesn't delete the source file. This program only uses the File and File stream classes.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Copy all the files in a folder with specific extension to another folder.
* Both the folders are specified on the command line.
* The program currently uses .java extension as filter.
**/
public class CopyFilesWithExtension {
public static void main(String[] args) {
if(args.length!=2) {
System.out.println("Command usage: java CopyFilesWithExtension sourcedirectory targetdirectory");
}
String sourceFolder = args[0];
String targetFolder = args[1];
File sFile = new File(sourceFolder);
// Find files with specified extension
File[] sourceFiles = sFile.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if(name.endsWith(".java")) {// change this to your extension
return true;
}else {
return false;
}
}
});
// let us copy each file to the target folder
for(File fSource:sourceFiles) {
File fTarget = new File(new File(targetFolder), fSource.getName());
copyFileUsingStream(fSource,fTarget);
// fSource.delete(); // Uncomment this line if you want source file deleted
}
}
/**
* Copies a file using the File streams
* @param source
* @param dest
*/
private static void copyFileUsingStream(File source, File dest) {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
}catch(Exception ex) {
System.out.println("Unable to copy file:"+ex.getMessage());
}
finally {
try {
is.close();
os.close();
}catch(Exception ex) {}
}
}
}
Posted in Java | Comments Off on How to Copy Files from One Folder to Another in Java
Converting an array of strings to a map of strings with the same string as key and value is required in many use cases. Conversion to map enables quick and easy evaluation as to whether a string exists in the list of strings. Conversion to map also enables removal of duplicate strings. The following Java program demonstrates conversion of an array of strings to its corresponding map.
import java.util.HashMap;
import java.util.Map;
/**
* Converts an array of strings to a map. Each string becomes the key and the corresponding value.
* Useful for removal of duplicates and quick check on existence of a string in the list.
* @author jj
*/
public class ArrayToMap {
public static void main(String[] args) {
String[] colors = new String[]{"blue","green","red"};
Map<String,String> colorMap = new HashMap<String,String>();
for(String color:colors) {
colorMap.put(color, color);
}
}
}
Posted in Java | Comments Off on Array to Map Conversion in Java
The following Java program prints a sequential number pyramid in Java. The output of the program is given below.
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
/**
* Prints number pyramid Java
* @author jj
*/
public class NumberPyramid {
public static void main(String[] args) {
int rows = 5; // number of rows for pyramid
for(int i=1;i<=rows;i++) {
for(int k=rows-i;k>=1;k--) {
System.out.print(" ");
}
for(int j=1;j<=i;j++) {
System.out.print(i*(i-1)/2+j+" ");
}
System.out.println();
}
}
}
Posted in Java | Comments Off on How to Print a Number Pyramid in Java
The following Java program prints repeated/duplicated words in a String. The program uses case insensitive comparison (For example, program assumes words CAT, cat and Cat etc. are all same). This algorithm is useful in text processing programs where word frequency calculations are needed.
The program first asks for the input string from the command line. Using the split function, this string is broken into individual words. We then add each word into a map checking whether the word already exists. Whenever we find a word that is repeated, we print the word.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
// How to find repeated/duplicated words in a string using Java
public class DuplicateWords {
public static void main(String[] args) {
System.out.print("Enter string to analyse:");
Scanner sn = new Scanner(System.in);
String input = sn.nextLine();
// first let us split string into words
String[] words = input.split(" ");
// adds all words into a map
// we also check whether the word is already in map!
Map<String,String> wordMap = new HashMap<String,String>();
for(int i=0;i<words.length;i++) {
String word = words[i].toUpperCase(); // for case insensitive comparison
if(wordMap.get(word)!=null) {
// we found a duplicated word!
System.out.println("Duplicated/Repeated word:"+word);
}else {
wordMap.put(word, word);
}
}
}
}
If a word is repeated more than once, it is printed multiple times. The following program fixes this by keeping track of printed words using another map.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
// How to find repeated/duplicated words in a string using Java
public class DuplicateWords2 {
public static void main(String[] args) {
System.out.print("Enter string to analyse:");
Scanner sn = new Scanner(System.in);
String input = sn.nextLine();
// first let us split string into words
String[] words = input.split(" ");
// adds all words into a map
// we also check whether the word is already in map!
Map<String,String> wordMap = new HashMap<String,String>();
Map<String,String> printedMap = new HashMap<String,String>();
for(int i=0;i<words.length;i++) {
String word = words[i].toUpperCase(); // for case insensitive comparison
if(wordMap.get(word)!=null) {
// we found a duplicated word!
if(printedMap.get(word)==null) { // first check if it is printed already!
System.out.println("Duplicated/Repeated word:"+word);
printedMap.put(word, word);
}
}else {
wordMap.put(word, word);
}
}
}
}
Posted in Java | Comments Off on Java Program to Find Repeated Words in a String