Share

Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets - 775 code snippet(s) found

 Sample 1. Switch Case with Enum
Admin
info@buggybread.com
public enum State {
NEVADA, CALIFORNIA, WASHINGTON;
}

public static void method(States stateName) {
switch (stateName) {
case NEVADA:
System.out.println("You are in Nevada");
break;

case CALIFORNIA:
System.out.println("You are in California");
break;

case WASHINGTON:
System.out.println("You are in Washington");
break;
}
}

   Like      Feedback     switch case  switch  case  enum   switch with enums   switch and enums


 Sample 2. Combine two Summaries and Generate a new Summary using Lambda Expression

// Populate a List using Set elements.

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();
Set<Integer> intSet2 = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);
intSet2.add(1);
intSet2.add(2);
intSet2.add(3);
intSet2.add(4);

// Use the stream and collectors to Summarize all Integer elements

IntSummaryStatistics summary = intSet.stream().collect(Collectors.summarizingInt(p->((Integer)p)));

summary.combine(intSet2.stream().collect(Collectors.summarizingInt(p->((Integer)p))));

System.out.println(summary); // Prints IntSummaryStatistics{count=8, sum=20, min=1, average=2.500000, max=4}

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.summarizingInt   summary.combine  java.util.hashset  java.util.stream.Collectors  java.util.IntSummaryStatistics


 Sample 3. Get all elements greater than 2, sort them and then push them to a new set, using Lambda Expression

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Set the predicate or the condition for filtering the elements.

Predicate<Integer> moreThan2Pred = (p) -> (p > 1);

// Use Filter to refine the element set, sort to Sort and Collectors.toSet to get a set out of Stream.

intSet = intSet.stream().filter(moreThan2Pred).sorted().collect(Collectors.toSet());

System.out.println(intSet); // Prints [2, 3, 4]

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   predicate   filter   sort  java.util.hashset  java.util.stream.Collectors


 Sample 4. Write a Program to reverse a string iteratively and recursively

Using String method -

new StringBuffer(str).reverse().toString();

Iterative -

public static String getReverseString(String str){
StringBuffer strBuffer = new StringBuffer(str.length);
for(int counter=str.length -1 ; counter>=0;counter--){
strBuffer.append(str.charAt(counter));
}
return strBuffer;
}

Recursive -

public static String getReverseString(String str){
if(str.length <= 1){
return str;
}
return (getReverseString(str.subString(1)) + str.charAt(0);
}

   Like      Feedback     string  StringBuffer  recursion  for loop  stringbuffer.append  java.lang.String  java.lang.StringBuffer


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 5. Method to get all files from a directory recursively

List<File> fileList = new ArrayList();

List<File> read(String dir) throws IOException{
File directory = new File(dir);
File[] fList = directory.listFiles();
for(File file:fList){
if(file.isDirectory()){
read(file.getPath());
} else {
fileList.add(file);
}
}
return fileList;
}

   Like      Feedback     file handling   file   isDirectory()  .getPath()   recursion   java.io.File


 Sample 6. Google Spreadsheet ( Google Docs ) JSON feed api

List getSpreadSheetData() throws IOException, ServiceException{
   List<SpreadsheetEntry> spreadsheetData = Service.getSpreadSheetData("<Spreadsheet Url>");
            
   SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
   URL SPREADSHEET_FEED_URL = new URL(url);

   SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
   List<SpreadsheetEntry> spreadsheet = feed.getEntries();
   return spreadsheet;
}

   Like      Feedback     google docs api  google spreadsheet api


 Sample 7. Interface Default Methods ( Base Class Definition has precedence over Interface Default Method if both are being extended and implemented and have common method definition )

HelloJava8Base 

public class HelloJava8Base {
public void defaultMethod() {
System.out.println("Default Method Base Class Implementation");
}
}

DefaultMethodInterface

public interface DefaultMethodInterface {
default public void defaultMethod() {
System.out.println("Default Method Interface Implementation");
}
}

HelloJava8

public class HelloJava8 extends HelloJava8Base implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface dmi = new HelloJava8();
dmi.defaultMethod(); // Prints "Default Method Base Class Implementation"
}
}

   Like      Feedback     interface default methods  java 8  interfaces


 Sample 8. Class bean with getter , setter and constructor

public class Employee {
public String name;
public int age;
public int salary;

Employee(String name, int age, int salary) {
this.name = name;
this.age = age;
this.salary = salary;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public int getSalary() {
return salary;
}

public void setSalary(int salary) {
this.salary = salary;
}
}

   Like      Feedback     bean   pojo   plain java objects   getters   setters   getters nd setters   classes   class   constructor   parameterized constructor  this keyword


 Sample 9. Check if the string is empty using Spring StringUtils

String str = "";
if(StringUtils.isEmpty(str)){
System.out.println("Yes, string is empty");
}

   Like      Feedback     StringUtils  StringUtils.isEmpty


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 10. Scheduling task using java.util.timer

static {
timer.schedule(new ScheduledTask(), 60000, 60000);
}

private static class Schedule extends TimerTask {
@Override public void run() {
//doSomething();
}
}

   Like      Feedback     java.util.timer  java.util.TimerTask  scheduling task  java.lang  Override


 Sample 11. Declaring Abstract Class

public abstract class TestClass {
public static void main(String[] args){
}
}

   Like      Feedback     abstract classes  main method declaration  main method


 Sample 12. Declaring static block

public abstract class TestClass {
static{
init();
}

public static void main(String[] args){
}

private init(){
}
}

   Like      Feedback     static block  abstract class declaration


 Sample 13. Declaring static final ( constant ) variables.

public abstract class TestClass {

   protected static final String TEST_STRING = "test";

   public static void main(String[] args){
   }
}

   Like      Feedback     static final variables   constant variables


 Sample 14. Web Crawler using crawler4j - Crawler Controller

String crawlStorageFolder = "/data/crawl/t2";

// Set No of Crawler Threads
int numberOfCrawlers = 5;

// Set Config

CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);

config.setMaxDepthOfCrawling(1);
config.setMaxPagesToFetch(-1);
config.setUserAgentString("JavaIndex");

// Instantiate the controller for this crawl.

PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);

controller.addSeed("http://www.buggybread.com");

// Initiate Crawler threads
controller.start(MyCrawler.class, numberOfCrawlers);

// Exit
System.exit(0);

   Like      Feedback     crawler4j


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 15. Find, if all elements of a collection matches the specified condition ( Using Lambda expressions )
Admin
info@buggybread.com
// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Specify the Predicate or the Condition using Lambda expressions

Predicate<Integer> moreThan2Pred = (p) -> (p > 2); 

// Use the stream method allMatch to see if all elements fulfils the Predicate.

   Like      Feedback     lambda expression   collections   set  hashset  generics  predicate


 Sample 16. Find, if any element of the collection matches the specified condition ( Using Lambda Expressions )
Admin
info@buggybread.com
// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Specify the Predicate or the Condition using Lambda expressions

Predicate<Integer> moreThan2Pred = (p) -> (p > 2); 

// Use the stream method anyMatch to see if all elements fulfils the Predicate.

System.out.println(intSet.stream().anyMatch(moreThan2Pred)); // Prints True.

   Like      Feedback     lambda expression   collections   set  hashset  generics  predicate


 Sample 17. Find, if no element of the collection matches the specified condition ( Inverse of anyMatch )

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Specify the Predicate or the Condition using Lambda expressions

Predicate<Integer> moreThan2Pred = (p) -> (p > 2); 

// Use the stream method noneMatch to see if all elements fulfils the Predicate.

System.out.println(intSet.stream().noneMatch(moreThan2Pred)); // Prints False.

   Like      Feedback     lambda expression   collections   set  hashset  generics  predicate


 Sample 18. Count number of collection elements using Lambda Expressions

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream method count to see if all elements fulfils the Predicate.

System.out.println(intSet.stream().count); // Prints 4.

   Like      Feedback     lambda expression   collections   set  hashset  generics  predicate


 Sample 19. Find the Average of all collection elements using Lambda Expressions

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and Collector to find the average of all elements.

System.out.println(intSet.stream().collect(Collectors.averagingInt(p->((Integer)p))));  Prints 2.5

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collector


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 20. Group Elements by even or Odd using Lambda Expressions

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and Collector to Group by Even and Odd

System.out.println(intSet.stream().collect(Collectors.groupingBy(p->((Integer)p)%2)));  Prints {0=[2, 4], 1=[1, 3]}

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.groupingBy


 Sample 21. Sum all collection elements using Lambda Expressions

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and collectors to sum all elements.

System.out.println(intSet.stream().collect(Collectors.summingInt(p->(Integer)p)));

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.groupingBy


 Sample 22. Populate a List using Set elements and Lambda Expression

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and collectors to get List out of Set

List li = intSet.stream().collect(Collectors.toList());
System.out.println(li); // Prints [1, 2, 3, 4]

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.toList


 Sample 23. Get the complete Summary of Collection Elements using Lambda Expressions

// Populate a List using Set elements.

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and collectors to Summarize all Integer elements 

System.out.println(intSet.stream().collect(Collectors.summarizingInt(p->((Integer)p)))); // Prints IntSummaryStatistics{count=4, sum=10, min=1, average=2.500000, max=4}

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.summarizingInt


 Sample 24. Create a Map using Set elements using Lambda Expression

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and collectors to get a Map out of Set 

System.out.println(intSet.stream().collect((Collectors.toMap(p->(Integer)p,q->((Integer)q)*500)))); // Prints {1=500, 2=1000, 3=1500, 4=2000} 

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 25. Get count of elements greater than 1 using Lambda Expression

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use Stream, Predicate and Filter to get the count of elements more than 1

System.out.println(intSet.stream().filter(moreThan2Pred).count()); // Prints 3

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   predicate   filter


 Sample 26. Get the Maximum number out of the Integer List, using Lambda Expression

// Declare and Initialize the Collection

List<Integer> intList = new ArrayList<Integer>();

// Add Elements

intList.add(1);
intList.add(2);
intList.add(3);
intList.add(4);


System.out.println(intList.stream().reduce(Math::max).get()); // Prints 1

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream  reducer   Math::max


 Sample 27. Concatenate Strings

String str = new String().concat("Explain").concat("This").concat("Code");

   Like      Feedback     string  string concatenation  concat


 Sample 28. Java Code to get all images url from html code.

regex = Pattern.compile("[http]");
regexMatcher = regex.matcher(htmlParseData.getHtml());
List tr=htmlParseData.getOutgoingUrls();
imgUrlCounter=0;
for(i=0;i<tr.size();i++){
if(tr.get(i).toString().contains(".jpg") || tr.get(i).toString().contains(".jpeg") || tr.get(i).toString().contains(".gif") || tr.get(i).toString().contains(".bmp")){
url = new URL(tr.get(i).toString());
Image image = new ImageIcon(url).getImage();
}
}

   Like      Feedback     regex  pattern  regex.matcher  html  java.util.regex.pattern  regular expressions


 Sample 29. Code to find email ids in a string using Pattern.

String text="vivek boy goy vivek@tech.com viv@ek.com sdjs@adjk";
Pattern regex = Pattern.compile("[@]");
Matcher regexMatcher = regex.matcher(text);
int i =0;
int width = 0;
while (regexMatcher.find()) {
if((regexMatcher.start()-10 > 0) && (regexMatcher.end()+10 < text.length())){
width=10;
String[] substr=text.substring(regexMatcher.start()-width,regexMatcher.end()+width).split(" ");
for(int j=0;j<substr.length;j++){
if(substr[j].contains("@") && (substr[j].contains(".com") || substr[j].contains(".net"))){
System.out.println(substr[j]);
}
}
} else {
width=0;
}
}

   Like      Feedback     regex  pattern  string  regexMatcher.find  java.util.regex.Matcher  java.util.regex.Pattern


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 30. SWT / JFace - Context Menu for Table / Tree

           Menu menu1 = new Menu(treeViewer.getTree());
           MenuItem item = new MenuItem(menu1, SWT.PUSH);
           item.setText("Test 1");
           item.addSelectionListener(new Test1Listener());
           MenuItem item = new MenuItem(menu1, SWT.PUSH);
           item1.setText("Test2");
           item1.addSelectionListener(new Test2Listener());
         
           tableViewer.getTable().setMenu(menu1);

   Like      Feedback     swt  jface  jface tree   jface table


 Sample 31. SWT / JFace - TreeViewer - Different Menus for Parent and Child

treeViewer.getTree().addMenuDetectListener(new MenuDetectListener() {

   @Override
   public void menuDetected(MenuDetectEvent e) {
    
    // get the selected items
                                ISelection selection = (IStructuredSelection) treeViewer.getSelection();
   
            // define menus - menu 1 if right click on parent tree item
           Menu menu1 = new Menu(treeViewer.getTree());
           MenuItem item = new MenuItem(menu1, SWT.PUSH);
           item.setText("Test 1");
           item.addSelectionListener(new Test1Listener());
         
           // menu 2 if right click on child tree item
           Menu menu2 = new Menu(procedureTreeViewerICD9.getTree());
           MenuItem item1 = new MenuItem(menu2, SWT.PUSH);
           item1.setText("Test2");
           item1.addSelectionListener(new Test2Listener());

           // menu 3 if right click on neither the parent tree item or child tree item. ex - menu for headers.
           Menu menu3 = new Menu(procedureTreeViewerICD9.getTree());
           MenuItem item1 = new MenuItem(menu3, SWT.PUSH);
           item1.setText("Test3");
           item1.addSelectionListener(new Test3Listener());
         
                              
                               // check if the tree item selected is parent or child and set the menu accordingly
          if (selection.getFirstElement() instanceof <ParentClass> ) {
              treeViewer.getControl().setMenu(menu1);
           } else if (selection.getFirstElement() instanceof <ChildClass> )
              treeViewer.getControl().setMenu(menu2);
           } else {
               treeViewer.getControl().setMenu(menu3);
           }
           // clear the selection
           treeViewer.setSelection(null);
   }
});

   Like      Feedback     swt  jface  jface tree   jface table  jface menu   MenuDetectEvent


 Sample 32. Method to check if input String is Palindrome

private static boolean isPalindrome(String str) {
if (str == null)
return false;
StringBuilder strBuilder = new StringBuilder(str);
strBuilder.reverse();
return strBuilder.toString().equals(str);
}

   Like      Feedback     Palindrome   strBuilder.reverse   string  stringbuilder.reverse  java.lang.StringBuilder


 Sample 33. Method that will remove given character from the String

private static String removeChar(String str, char c) {
if (str == null)
return null;
return str.replaceAll(Character.toString(c), "");
}

   Like      Feedback     string  string.replaceall  Character.toString


 Sample 34. Method to convert binary to a number

convert(int binaryInt) {
int sumValue=0;
int multiple = 1;
while(binaryInt > 0){
binaryDigit = binaryInt%10;
binaryInt = binaryInt /10;
sumValue = sumValue + (binaryDigit * multiple);
multiple = multiple * 2;
}
return sumValue;
}

   Like      Feedback     binary  binary to int  binary to number   while loop  modulus operator


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 35. Find whether a given integer is odd or even without use of modules operator in java

public static void main(String ar[])
{
   int n=5;
   if((n/2)*2==n)
   {
      System.out.println("Even Number ");
   }
   else
   {
      System.out.println("Odd Number ");
   }
}

   Like      Feedback     integer


 Sample 36. Rest Web Service ( Post ) using Jersey, XML

@Path("/employeeInfo")
public class RestWebServiceJersey {
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public String submitEmployeeInfo(Employee employee) {
StatusDto status = insertIntoDb(employee);
return status;
}
}

   Like      Feedback     rest  @post  @consumes  @produces  xml  rest web service  jersey  javax.ws.rs.Path  javax.ws.rs.Post  javax.ws.rs.Produces  javax.ws.rs.Consumes  javax.ws.rs.core.MediaType


 Sample 37. JQuery - Create a Dialog ( Alert )

Dialog with a fixed height and width

$('<div></div>').appendTo('body').html(
            'Validation Failed .')
            .dialog({
              resizable : false,
              modal : true,
              title : "Alert",
              height : 150,
              width : 400,
              buttons : {
                "Ok" : function() {
                  $(this).dialog('close');
              }
         }
 });

Dialog with expanding height and width  

$('<div></div>').appendTo('body').html(
            'Validation Failed .')
            .dialog({
              resizable : false,
              modal : true,
              title : "Alert",
              buttons : {
                "Ok" : function() {
                  $(this).dialog('close');
              }
         }
 }); 

   Like      Feedback     jquery  ajax  dialog ui  alert ui


 Sample 38. ajax / Jquery call to get the list of check boxes to be disabled.

function disableCheckBox(){
    sendAjaxGetCall(“/resourceUrl?input=”+input) .done(function(data) {
          data = data + '';
          var checkboxToDisable = data.split(",");
          for(int i=0;i < checkboxToDisable.length;i++){
                $(“#”+i).attr("disabled", true);
           }
     }).fail(function(xhr, error) {
           console.log('error: ' + xhr.statusText);
     });
}

   Like      Feedback     jquery  ajax  checkbox   disable checkbox


 Sample 39. Ajax / Jquery call to decide on showing html page section

function hideXYZSection(){

    sendAjaxGetCall(“/resourceUrl?input=”+input) .done(function(data) {
         if(data == 'true'){
             $("#sectionDivId").show(); // show or hide
         }

     }).fail(function(xhr, error) {

           console.log('error: ' + xhr.statusText);

     });

}

   Like      Feedback     jquery  ajax  showing html section  .show()  sendAjaxGetCall


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 40. Usage of HashMap

Map<Integer,String> indexedInfo = new HashMap();
indexedInfo.put(1,"Spain");
indexedInfo.put(2,"Denmark");
indexedInfo.put(3,"China");

   Like      Feedback     hashmap  map  collections  java.util.hashmap


 Sample 41. Method to check if the WebUrl matches a Pattern.

public boolean shouldVisit(WebURL url) {
Pattern filters = Pattern.compile(".*(.(htm|html))$");

String href = url.getURL().toLowerCase();
if(filters.matcher(href).matches()){
return true;
}
return false;
}

   Like      Feedback     weburl  patternmatching  .getURL()  pattern  pattern.matcher  pattern.matcher.matches   regex  regular expression


 Sample 42. Write a program to print fibonacci series.

int count = 15;
int[] fibonacci = new int[count];
fibonacci[0] = 0;
fibonacci[1] = 1;
for(int x=2; x < count; x++){
   fibonacci[x] = fibonacci[x-1] + fibonacci[x-2];
}

for(int x=0; x< count; x++){
   System.out.print(fibonacci[x] + " ");
}

   Like      Feedback     fibonacci


 Sample 43. Method to get Text / html info from edu.uci.ics.crawler4j.crawler.Page

private void crawlPageInfo(Page page){
try {
String url = page.getWebURL().getURL();

if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
TextParser parser = new TextParser(htmlParseData.getText());
}
} catch(Exception ex){
System.out.println(ex.getMessage());
}

   Like      Feedback     html info   getting text/html from edu.uci.ics.crawler4j.crawler.Page   HtmlParseData   TextParser


 Sample 44. Get the content of a file in a string

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileToString {

public static void main(String[] args) throws IOException {

String line = null;

String wholePage = "";

FileReader fileReader =
new FileReader("/home/vivekvermani/test.txt");

BufferedReader bufferedReader =
new BufferedReader(fileReader);

while((line = bufferedReader.readLine()) != null) {
wholePage = wholePage + line + "
";
}

bufferedReader.close();

System.out.println(wholePage);
}
}

   Like      Feedback     reading file to string  import


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 45. Replace all occurrences of a character or substring in a string

String myString = new String("Nevada,Kansas,Georgia");

myString = myString.replaceAll(",", " ");

System.out.println(myString); // prints Nevada Kansas Georgia

   Like      Feedback     string   substring  replaceAll


 Sample 46. Check if a string contains a substring.

String text = "I don't think we're in Kansas anymore";

if(text.indexOf("Kansas") != -1){
System.out.println("Yes, the dialog contains Kansas");
}

   Like      Feedback     string  substring  indexOf()


 Sample 47. Get the subString from a String using the begin and end index

String text = "I don't think we're in Kansas anymore";

// Usage string.substring(startIndex,endIndex)

String subStringText = text.substring(0,2);

System.out.println(subStringText); // prints I d

   Like      Feedback     string  substring  substring using indices


 Sample 48. Trim New line and spaces in a string

String trimNewLineAndSpace(String str){
str = str.trim();
if(str.startsWith("\n")){
str = str.substring(1);
}

if(str.endsWith("\n")){
str = str.substring(0, str.length()-1);
}
return str;
}

   Like      Feedback     string  trim new lines  string.substring  string.startswith  string.endswith


 Sample 49. Trim a String till first capital character.

String trimTillFirstCapitalCharacter(String str){
   for(int i=0;i<str.length();i++){
      if(str.charAt(i) != str.toLowerCase().charAt(i)){
         return str.substring(i);
      }
   }
   return str;
}

   Like      Feedback     trim characters   trim


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 50. Overriding equals method

public class ClassInfoBean {
public String url;

@Override
public boolean equals(Object o) {
if (this.url.equals(((ClassInfoBean)o).url)){
return true;
}
return false;
}
}

   Like      Feedback     equals  overriding equals method   @override


 Sample 51. Enum with a method to get the constant having specific member element.

public enum JavaFramework {
SPRING("Spring","Web"),
STRUTS("Struts","Web"),
JSF("JSF","View"),
CRUNCH("Apache Crunch","BigData");


public String name;
public String type;

JavaFramework(String name, String type){
this.name = name;
this.type = type;
}

static public List<JavaFramework> getByType(String type) {
List<JavaFramework> frameworks = new ArrayList();
for(JavaFramework framework: JavaFramework.values()){
if(framework.type.equalsIgnoreCase(type)){
frameworks.add(framework);
}
}

return frameworks;
}
}

   Like      Feedback     enum  java.util.list


 Sample 52. Trim square braces and spaces from a String

String trimSquareBracesAndSpaces(String str){
   str = str.trim();
   if(str.startsWith("[")){
      str = str.substring(1);
   }
      
   if(str.endsWith("]")){
      str = str.substring(0, str.length()-1);
   }
   return str;
}

   Like      Feedback     string  string trim   trim


 Sample 53. Remove templatized arguments from a String

String removeTemplatizedArgument(String str){
   String cleanStr = "";
   boolean withinTemplatized=false;   
   int countBlock = 0;
   for(char x: str.toCharArray()){
      if(x == '<'){
         withinTemplatized = true;
         countBlock++;
         continue;
      } else if(x == '>'){
         withinTemplatized = false;
         countBlock--;
         continue;
      } else if(!withinTemplatized && countBlock == 0){
         cleanStr = cleanStr + x;
      }
         
   }
      
   return cleanStr;
}

   Like      Feedback     string  string trim  trim  char  .toCharArray()


 Sample 54. Remove Alien characters i.e removing everything except characters , numbers and special characters.

String removeAlienCharacters(String str){
   String newString = new String();
   String returnString = "";
   if(str.contains("<")){
      String[] str2 = str.split("<");
      str = str2[0];
   }
      
   for(char x: str.toCharArray()){
      if((x >= 48 && x <= 57) || (x>=65 && x <= 90) || (x >= 97 && x<= 122) || x=='.'){
         returnString += x;
      }
   }
   return returnString.trim();
}

   Like      Feedback     string  .contains()  .split()  string split  string contains  remove characters from string  remove alien characters


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 55. Rest Web Service ( Get ) using Jersey

@Path("/employeeInfo")
public class RestWebServiceJersey {
@GET
@Path("/detail/{employeeId}")
@Produces(MediaType.APPLICATION_JSON)
public String getEmployeeInfo(@PathParam("employeeId") String employeeId) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("EmployeeName", "Sam");
jsonObj.put("EmployeeDept", "Marketing");
return jsonObj.toString();
}
}

   Like      Feedback     rest  rest web service  jersey  @path  @get  @produces  MediaType.APPLICATION_JSON  @PathParam  JSONObject  javax.json.JSONObject


 Sample 56. Blogger API for creating Posts ( Change xxxxxx to your blog specific info )

package Reader;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;

public class BlogPostCreater {

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String title, String content,String label,String authorization_key) throws IOException {

content = content.replace(""",""");


String url = "https://www.googleapis.com/blogger/v3/blogs/xxxxxxxxxx/posts?clientId=xxxxxxxx&clientSecret=xxxxxxxx";

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

// add header
post.setHeader("Authorization", authorization_key);
post.setHeader("Content-type","application/json");

post.setEntity(new StringEntity(buildJson(title,content,label)));

HttpResponse response = client.execute(post);

System.out.println(response);

return "true";
}



String buildJson(String title, String content,String label) {

System.out.println(label);
return "{"status": "LIVE", "content": ""+content+"", "kind": "blogger#post"" +
", "title": ""+title+"", "url": "xxxxxx", " +
""readerComments": "DONT_ALLOW_HIDE_EXISTING", "author": {" +
""url": "https://www.blogger.com/profile/04326686331881561093", " +
""image": {" +
""url": "//lh4.googleusercontent.com/-64Ucx9lX9Q4/AAAAAAAAAAI/AAAAAAAAAx0/-rUjBgS3djE/s35-c/photo.jpg"" +
"}, " +
""displayName": "Vivek Vermani", " +
""id": "g108356395081185480077"" +
"}, "updated": "2015-09-28T09:46:12+05:30", "replies": {"totalItems": "0", " +
""selfLink": "https://www.googleapis.com/blogger/v3/blogs/xxxxxxxxxx/posts/2495464003469367152/comments"" +
"}, "blog": {"id": "4275342475651800664"}, " +
""etag": "'GtyIIQmNmmUjEA0nwhSqMElCJ1g/dGltZXN0YW1wOiAxNDQzNDEzNzcyMDc1Cm9mZnNldDogMTk4MDAwMDAK'", " +
""published": "2015-09-28T09:46:00+05:30", " +
""id": "2495464003469367152", " +
""selfLink": "https://www.googleapis.com/blogger/v3/blogs/xxxxxx/posts/2495464003469367152"}";
}

public String post(String url, Map<String,String> formParameters) throws ClientProtocolException, IOException {
HttpPost request = new HttpPost(url);

List <NameValuePair> nvps = new ArrayList <NameValuePair>();

for (String key : formParameters.keySet()) {
nvps.add(new BasicNameValuePair(key, formParameters.get(key)));
}

request.setEntity(new UrlEncodedFormEntity(nvps));

return execute(request);
}

// makes request and checks response code for 200
private String execute(HttpRequestBase request) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);

HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);

if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Expected 200 but got " + response.getStatusLine().getStatusCode() + ", with body " + body);
}

return body;
}


}

   Like      Feedback     blogger api   blogger api for post creation  java.lang.RuntimeException


 Sample 57. Hibernate Entity

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.hibernate.annotations.Type;

import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import org.hibernate.annotations.DiscriminatorOptions;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;


@Entity
@Table(name="Employee", schema = "test")
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
name="ACTIVE",
discriminatorType= DiscriminatorType.STRING
)
@DiscriminatorOptions(insert=true)
@DiscriminatorValue("Yes")
public class Employee {

@javax.persistence.Id
@SequenceGenerator(name = "", sequenceName = "")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "")
@Column(name="EMPLOYEE_ID")
private int employeeId;

@Column(name="EMPLOYEE_NAME")
@NotNull
private String employeeName;

@Column(name="DEPT")
@NotNull
private String department;

@Column(name="FULL_TIME")
@Type(type="yes_no")
@NotNull
private Boolean isFullTime;

@Column(name = "ACTIVE")
@Type(type = "yes_no")
public boolean getActive() {
return active;
}

public String getName() {
return employeeName;
}

public String getDept() {
return department;
}
}

   Like      Feedback     Hibernate entity   Hibernate Bean


 Sample 58. Method to convert all elements of a collection ( Set ) to lower case.

Set<String> convertLowerCase(Set<String> set){
   Set<String> newSet = new HashSet();
   for(String s: set){
      newSet.add(s.toLowerCase());
   }
      
   return newSet;
}

   Like      Feedback     string  collections  set  .tolowercase()


 Sample 59. Interface Default Methods

public interface DefaultMethodInterface {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface");
}
}

public interface DefaultMethodInterface2 {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface2");
}
}

public class HelloJava8 implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface defMethIn = new HelloJava8();
defMethIn.defaultMethod();
}

public void defaultMethod(){
System.out.println("HelloJava8");
}
}

   Like      Feedback     interface default methods   interfaces  java 8


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 60. Usage of StringBuffer

StringBuffer strBuffer = new StringBuffer();
strBuffer.append("I don't think");
strBuffer.sppend("we're in Kansas anymore");
String string = strBuffer.toString();

   Like      Feedback     stringbuffer


 Sample 61. Get all words from a String and display them

String string = "I don't think we are in Kansas anymore";
String splittedString = str1.split(" ");
int count = 1;
for(String str: splittedString){
   System.out.println("Word number:" + count + ":" + str);
   count++;
}

   Like      Feedback     string  string split  Get all words from a String   word count


 Sample 62. Method to remove duplicates from a Map ( string and List of objects ) by matching the member field of the object.

Map<String,List<ClassInfoBean>> removeDuplicates(Map<String, List<ClassInfoBean>> interfaceMap){
   Map<String, List<ClassInfoBean>> interfaceMapWithoutDuplicate = new HashMap();
      
   for(Map.Entry<String, List<ClassInfoBean>> entry: interfaceMap.entrySet()){
      List<ClassInfoBean> classListWithoutDuplicate = new ArrayList();
      boolean alreadyContain = false;
      for(ClassInfoBean classes: entry.getValue()){
         for(ClassInfoBean classes1: classListWithoutDuplicate){
            if(classes1.name.equalsIgnoreCase(classes.name)){
               alreadyContain = true;
               break;
            }
         }
         if(alreadyContain == false){
            classListWithoutDuplicate.add(classes);
         }
      }
      interfaceMapWithoutDuplicate.put(entry.getKey(), classListWithoutDuplicate);
   }
      
   return interfaceMapWithoutDuplicate;
}

   Like      Feedback     map  map of list of objects  remove duplicates from map  Map.Entry


 Sample 63. Method to remove duplicates from a List of objects by matching the member elements of objects.

List<ClassInfoBean> removeDuplicates(List<ClassInfoBean> listClassInfo){
   Set<ClassInfoBean> set = new HashSet();
   Set<String> url = new HashSet();
   boolean flag = false;
   for(ClassInfoBean cl: listClassInfo){
      if(!url.contains(cl.url)){
         set.add(cl);
         url.add(cl.url);
      }
   }
      
   return new ArrayList(set);
}

   Like      Feedback     list  list of objects  remove duplicates from list


 Sample 64. Sort a List using Collections.sort and comparator

Collections.sort(listClassInfo,new Comparator<ClassInfoBean>(){
public int compare(ClassInfoBean s1,ClassInfoBean s2){
if(s1.name.compareTo(s2.name) < 0){
return -1;
} else {
return 1;
}

}});

   Like      Feedback     sorting   sort   Collections.sort   sort a list   comparator   compare method  java.util.Collections


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 65. ArrayList of Optional Integers

List<Optional<Integer>> intList = new ArrayList<Optional<Integer>>();

// Add Elements

intList.add(Optional.empty());
intList.add(Optional.of(2));
intList.add(Optional.of(3));
intList.add(Optional.of(4));

   Like      Feedback     optional  java 8   list   arraylist   list of optional integers   arraylist of optional  java.util.Optional


 Sample 66. Get Date using ZonedDateTime and LocalDateTime

ZonedDateTime zonedDatetime = ZonedDateTime.of(201, 1, 31, 14, 35, 12, 123, ZoneId.of("UTC-11"));
System.out.println(zonedDatetime.get(ChronoField.HOUR_OF_DAY));

LocalDateTime localDateTime = LocalDateTime.of(2015, 03, 10, 13, 36);
System.out.println(localDateTime);

ZonedDateTime zonedDatetime2 = ZonedDateTime.now(ZoneId.of("merica/Chicago"));
System.out.println(zonedDatetime2);

ZonedDateTime zonedDatetime3 = ZonedDateTime.of(localDateTime, ZoneId.of("America/Chicago"));
System.out.println(zonedDatetime3);

   Like      Feedback     ZonedDateTime   LocalDateTime   ZonedDateTime.of  LocalDateTime.of  ZonedDateTime.now  ZoneId  ZoneId.of  java.time.ZonedDateTime  java.time   java 8


 Sample 67. Method to get a map of words and their count by passing in the string

Map<String,Integer> wordCountMap = new TreeMap();
String[] words = text.split(" ");
Set<Integer> countSet;
for(String word: words) {
if(wordCountMap.containsKey(word.toLowerCase())){
wordCountMap.put(word.toLowerCase(), wordCountMap.get(word.toLowerCase()).intValue() + 1);
} else {
wordCountMap.put(word.toLowerCase(), 1);
}
}

countSet = new TreeSet(Collections.reverseOrder());
countSet.addAll(wordCountMap.values());

for(Integer inte: countSet) {
for(Entry<String,Integer> entry: wordCountMap.entrySet()){
if(entry.getValue() == inte) {
System.out.println(entry);
}
}
}

   Like      Feedback     map  word count  map of string and integer  containsKey  string split  treeset  Collections.reverseOrder  set addAll   entry


 Sample 68. Enum implementing TemporalField

public enum MyChronoField implements TemporalField {

NANO_OF_SECOND("NanoOfSecond", NANOS, SECONDS, ValueRange.of(12l,45l));


private final String name;
private final TemporalUnit baseUnit;
private final TemporalUnit rangeUnit;
private final ValueRange range;
private final String displayNameKey;

private MyChronoField(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit, ValueRange range) {
this.name = name;
this.baseUnit = baseUnit;
this.rangeUnit = rangeUnit;
this.range = range;
this.displayNameKey = null;
}

private MyChronoField(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit,
ValueRange range, String displayNameKey) {
this.name = name;
this.baseUnit = baseUnit;
this.rangeUnit = rangeUnit;
this.range = range;
this.displayNameKey = displayNameKey;
}
}

   Like      Feedback     enum   TemporalField  java.time.temporal   java.timejava.time.temporal.TemporalField


 Sample 69. Controller in Spring MVC

@Controller
@RequestMapping("/employee")
public class EmployeeInfoController {
@RequestMapping(value = "", method = RequestMethod.GET)
public Model searchEmployeeInfo(Model model, @RequestParam("id") String employeeId) {
   // body
}
}

   Like      Feedback     controller  @Controller  @RequestMapping  RequestMethod.GET  @RequestParam  Spring mvc  spring framework


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 70. Retry in case of exception

public static final int NUMBER_OF_RETRIES = 5;

try {
   // do something
} catch (Exception e) {
   int count;
   for (count = 1; count <= NUMBER_OF_RETRIES; count++) {
      Thread.sleep(5000);
   } catch (InterruptedException e1) {
      try {
         // do something again
         break;
      } catch (Exception ex) {
   }
}

   Like      Feedback     exception handling   exception   Retry in case of exception   for loop   for   Thread.sleep   InterruptedException


 Sample 71. Initialize Date using SimpleDateFormat and parsing string

Date endDate = new SimpleDateFormat("yyyyMMdd").parse("20160426");

   Like      Feedback     SimpleDateFormat   Date   SimpleDateFormat.parse  java.text.SimpleDateFormat


 Sample 72. Get current time using GregorianCalendar

Calendar calendar = new GregorianCalendar();
float currentTime = calendar.get( Calendar.HOUR_OF_DAY ) + ((float)calendar.get( Calendar.MINUTE )/100);

   Like      Feedback     GregorianCalendar  Calendar.HOUR_OF_DAY  Calendar.MINUTE  Calendar.java.util.Calendar


 Sample 73. Null or Empty String check using string length

String str= "";

if (str != null || str.length() != 0) {
   // Do something
}

   Like      Feedback     string  null check   String.length  check empty string


 Sample 74. Check if an object is an instanceOf class or derived class or implementing interface

DerivedClass dc = new DerivedClass();

if (dc instanceof BaseClass) {
}

   Like      Feedback     instanceof


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 75. Initialize Joda DateTime

DateTime dt = new DateTime("2016-12-18T22:34:41.311-07:00");

   Like      Feedback     DateTime   Joda


 Sample 76. Singleton Class ( using private constructor , object initialization using static method, doubly checked , thread safe, synchronized , volatile reference )

class Singleton {
   private static volatile Singleton instance = null;
   private Singleton(){}
   public static Singleton getInstance() {
      if (instance == null) {
         synchronized(Singleton.class) {
            if (instance== null)
               instance = new Singleton();
            }
         }
      return instance;
   }
}

   Like      Feedback     singleton   singleton class   volatile   private constructor    object initialization using static method   doubly checked    thread safe   synchronized block using class level lock   synchronized   synchronized block   class level lock


 Sample 77. Tricky code for String Comparison and String Pool

class BuggyBread { 
public static void main(String[] args)
{
String s2 = "I am unique!";
String s5 = "I am unique!";

System.out.println(s2 == s5); // prints true
}
}

   Like      Feedback     tricky code example  string  string comparison  object comparison   object equality   string equality   string pool


 Sample 78. Tricky Code for Overloading and Overriding

class BuggyBread1 {
public String method() {
return "Base Class - BuggyBread1";
}
}

class BuggyBread2 extends BuggyBread1{

private static int counter = 0;

public String method(int x) {
return "Derived Class - BuggyBread2";
}

public static void main(String[] args) {
BuggyBread1 bg = new BuggyBread2();
System.out.println(bg.method()); // prints Base Class - BuggyBread1
}
}

   Like      Feedback     overloading   overriding   tricky code examples  inheritance


 Sample 79. Exception handling and logging using Log4j

private static final Logger LOGGER = Logger.getLogger(BuggyBread.class);

public static void main(String[] args) {
   try {
      // Do Something   
   } catch (Throwable t) {
      LOGGER.error("Shit Happens");
   } finally {
      // release the connections
   }
}



   Like      Feedback     exception handling  exceptions  log4j  logging  logger  finally


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 80. Write a method to input 10 numbers and then print the sum.

public void calculateSum() {
   Scanner scanner=new Scanner(System.in);
   int sum=0;
   for(int counter=1;counter<=10;counter++)
      sum=sum+(scanner.nextInt());

   System.out.println("The sum is: "+sum);
}

   Like      Feedback     scanner  for loop  scanner.nextInt   input numbers and print sum


 Sample 81. Internal Implementation of ChronoField

public enum ChronoField implements TemporalField {
NANO_OF_SECOND("NanoOfSecond", NANOS, SECONDS, ValueRange.of(0, 999_999_999)),
NANO_OF_DAY("NanoOfDay", NANOS, DAYS, ValueRange.of(0, 86400L * 1000_000_000L - 1)),
MICRO_OF_SECOND("MicroOfSecond", MICROS, SECONDS, ValueRange.of(0, 999_999)),
MICRO_OF_DAY("MicroOfDay", MICROS, DAYS, ValueRange.of(0, 86400L * 1000_000L - 1)),
MILLI_OF_SECOND("MilliOfSecond", MILLIS, SECONDS, ValueRange.of(0, 999)),
MILLI_OF_DAY("MilliOfDay", MILLIS, DAYS, ValueRange.of(0, 86400L * 1000L - 1)),
SECOND_OF_MINUTE("SecondOfMinute", SECONDS, MINUTES, ValueRange.of(0, 59), "second"),
SECOND_OF_DAY("SecondOfDay", SECONDS, DAYS, ValueRange.of(0, 86400L - 1)),
MINUTE_OF_HOUR("MinuteOfHour", MINUTES, HOURS, ValueRange.of(0, 59), "minute"),
MINUTE_OF_DAY("MinuteOfDay", MINUTES, DAYS, ValueRange.of(0, (24 * 60) - 1)),
HOUR_OF_AMPM("HourOfAmPm", HOURS, HALF_DAYS, ValueRange.of(0, 11)),
CLOCK_HOUR_OF_AMPM("ClockHourOfAmPm", HOURS, HALF_DAYS, ValueRange.of(1, 12)),
HOUR_OF_DAY("HourOfDay", HOURS, DAYS, ValueRange.of(0, 23), "hour"),
CLOCK_HOUR_OF_DAY("ClockHourOfDay", HOURS, DAYS, ValueRange.of(1, 24)),
AMPM_OF_DAY("AmPmOfDay", HALF_DAYS, DAYS, ValueRange.of(0, 1), "dayperiod"),
DAY_OF_WEEK("DayOfWeek", DAYS, WEEKS, ValueRange.of(1, 7), "weekday"),
ALIGNED_DAY_OF_WEEK_IN_MONTH("AlignedDayOfWeekInMonth", DAYS, WEEKS, ValueRange.of(1, 7)),
ALIGNED_DAY_OF_WEEK_IN_YEAR("AlignedDayOfWeekInYear", DAYS, WEEKS, ValueRange.of(1, 7)),
DAY_OF_MONTH("DayOfMonth", DAYS, MONTHS, ValueRange.of(1, 28, 31), "day"),
DAY_OF_YEAR("DayOfYear", DAYS, YEARS, ValueRange.of(1, 365, 366)),
EPOCH_DAY("EpochDay", DAYS, FOREVER, ValueRange.of((long) (Year.MIN_VALUE * 365.25), (long) (Year.MAX_VALUE * 365.25))),
ALIGNED_WEEK_OF_MONTH("AlignedWeekOfMonth", WEEKS, MONTHS, ValueRange.of(1, 4, 5)),
ALIGNED_WEEK_OF_YEAR("AlignedWeekOfYear", WEEKS, YEARS, ValueRange.of(1, 53)),
MONTH_OF_YEAR("MonthOfYear", MONTHS, YEARS, ValueRange.of(1, 12), "month"),
PROLEPTIC_MONTH("ProlepticMonth", MONTHS, FOREVER, ValueRange.of(Year.MIN_VALUE * 12L, Year.MAX_VALUE * 12L + 11)),
YEAR_OF_ERA("YearOfEra", YEARS, FOREVER, ValueRange.of(1, Year.MAX_VALUE, Year.MAX_VALUE + 1)),
YEAR("Year", YEARS, FOREVER, ValueRange.of(Year.MIN_VALUE, Year.MAX_VALUE), "year"),
ERA("Era", ERAS, FOREVER, ValueRange.of(0, 1), "era"),
INSTANT_SECONDS("InstantSeconds", SECONDS, FOREVER, ValueRange.of(Long.MIN_VALUE, Long.MAX_VALUE)),
OFFSET_SECONDS("OffsetSeconds", SECONDS, FOREVER, ValueRange.of(-18 * 3600, 18 * 3600));

private final String name;
private final TemporalUnit baseUnit;
private final TemporalUnit rangeUnit;
private final ValueRange range;
private final String displayNameKey;

private ChronoField(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit, ValueRange range) {
this.name = name;
this.baseUnit = baseUnit;
this.rangeUnit = rangeUnit;
this.range = range;
this.displayNameKey = null;
}

private ChronoField(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit,
ValueRange range, String displayNameKey) {
this.name = name;
this.baseUnit = baseUnit;
this.rangeUnit = rangeUnit;
this.range = range;
this.displayNameKey = displayNameKey;
}

@Override
public String getDisplayName(Locale locale) {
Objects.requireNonNull(locale, "locale");
if (displayNameKey == null) {
return name;
}

LocaleResources lr = LocaleProviderAdapter.getResourceBundleBased()
.getLocaleResources(locale);
ResourceBundle rb = lr.getJavaTimeFormatData();
String key = "field." + displayNameKey;
return rb.containsKey(key) ? rb.getString(key) : name;
}

@Override
public TemporalUnit getBaseUnit() {
return baseUnit;
}

@Override
public TemporalUnit getRangeUnit() {
return rangeUnit;
}

@Override
public ValueRange range() {
return range;
}

@Override
public boolean isDateBased() {
return ordinal() >= DAY_OF_WEEK.ordinal() && ordinal() <= ERA.ordinal();
}

@Override
public boolean isTimeBased() {
return ordinal() < DAY_OF_WEEK.ordinal();
}

public long checkValidValue(long value) {
return range().checkValidValue(value, this);
}

public int checkValidIntValue(long value) {
return range().checkValidIntValue(value, this);
}

@Override
public boolean isSupportedBy(TemporalAccessor temporal) {
return temporal.isSupported(this);
}

@Override
public ValueRange rangeRefinedBy(TemporalAccessor temporal) {
return temporal.range(this);
}

@Override
public long getFrom(TemporalAccessor temporal) {
return temporal.getLong(this);
}

@SuppressWarnings("unchecked")
@Override
public <R extends Temporal> R adjustInto(R temporal, long newValue) {
return (R) temporal.with(this, newValue);
}

@Override
public String toString() {
return name;
}

}

   Like      Feedback     chronofield  temporalfield  java 8  java.time.temporal.TemporalField


 Sample 82. Selenium - Get the element using WebDriver

WebElement element = driver.findElement(By.id("elementId"));

// or use annotation @FindBy as following

@FindBy(id = "elementId")
WebElement element;

   Like      Feedback     selenium  webdriver  automation testing


 Sample 83. Select an option using the select element name and the expected option value

void select(String name, String value) {
WebElement element = By.name(name);
List<WebElement> options = element.findElements(By.tagName("option"));
for (WebElement option : options) {
if (option.getText().equals(value)) {
option.click();
return;
}
}
}

   Like      Feedback     selenium  webdriver  webelement


 Sample 84. Selenium - WebDriver - Method to check if an option has already been selected

boolean isSelected(String selectName, String optionValue) {
WebElement element = By.name(name);
List<WebElement> options = element.findElements(By.tagName("option"));
for (WebElement option : options) {
if (option.getText().equals(value)) {
return option.isSelected();
}
}
return false;
}

   Like      Feedback     selenium  webdriver  WebElement


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 85. Sorting elements of a set using TreeSet

Set<String> mySet = new HashSet<String>();
mySet.add("D");
mySet.add("A");
mySet.add("B");
mySet.add("C");
mySet.add("E");

System.out.println(mySet); // May be Sorted but sorting is not guaranteed

mySet = new TreeSet<String>(mySet);

System.out.println(mySet); // Sorted

   Like      Feedback     sorting  collections  treeset  set  hashset


 Sample 86. Sorting an arraylist using Collections.sort

List<String> myList = new ArrayList<String>();
myList.add("D");
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("E");

System.out.println(myList); // Unsorted

Collections.sort(myList);

System.out.println(myList); // Sorted

   Like      Feedback     list  arraylist  collections.sort  collections


 Sample 87. Internal Implementation of MinguoEra

public enum MinguoEra implements Era {
BEFORE_ROC,
ROC;

public static MinguoEra of(int minguoEra) {
switch (minguoEra) {
case 0:
return BEFORE_ROC;
case 1:
return ROC;
default:
throw new DateTimeException("Invalid era: " + minguoEra);
}
}

@Override
public int getValue() {
return ordinal();
}

}

   Like      Feedback     MinguoEra  java.time  java.time.chrono  internal implementation  enum  switch  throw  exception throw


 Sample 88. Internal Implementation of java.time.chrono.era

public interface Era extends TemporalAccessor, TemporalAdjuster {
int getValue();

@Override
default boolean isSupported(TemporalField field) {
if (field instanceof ChronoField) {
return field == ERA;
}
return field != null && field.isSupportedBy(this);
}

@Override // override for Javadoc
default ValueRange range(TemporalField field) {
return TemporalAccessor.super.range(field);
}

@Override // override for Javadoc and performance
default int get(TemporalField field) {
if (field == ERA) {
return getValue();
}
return TemporalAccessor.super.get(field);
}

@Override
default long getLong(TemporalField field) {
if (field == ERA) {
return getValue();
} else if (field instanceof ChronoField) {
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.getFrom(this);
}

@SuppressWarnings("unchecked")
@Override
default <R> R query(TemporalQuery<R> query) {
if (query == TemporalQueries.precision()) {
return (R) ERAS;
}
return TemporalAccessor.super.query(query);
}

@Override
default Temporal adjustInto(Temporal temporal) {
return temporal.with(ERA, getValue());
}

default String getDisplayName(TextStyle style, Locale locale) {
return new DateTimeFormatterBuilder().appendText(ERA, style).toFormatter(locale).format(this);
}
}

   Like      Feedback     era  java.time.TemporalAccessor  java.time.TemporalAdjuster  java.time.chrono  default methods


 Sample 89. Initialize java.util.date using java.util.Calendar

Date currentDate = Calendar.getInstance().getTime();

   Like      Feedback     calendar  java.util.calendar  java.util  date  java.util.date  Calendar.getTime


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 90. Initialize list using google guava Lists

import java.util.List;
import com.google.common.collect.Lists;

class GoogleListsTest{
public static void main(String[] args){
List list = Lists.newArrayList();
}
}

   Like      Feedback     list  google guava  Lists  Lists.newArrayList  com.google.common.collect.Lists


 Sample 91. Check if an integer is odd or even using ternary operator

public class BuggyBreadTest {
    public static void main(String[] args) {
       int x = 5;
       boolean isEven = x%2 == 0 ? true:false;
       if(isEven)
          System.out.println("Even");
       else
          System.out.println("Odd"); // prints Odd
    }
}

   Like      Feedback     odd even  ternary operator


 Sample 92. Initialize object using Builder Pattern

public class Employee {
public String name;
public int age;
public int salary;

Employee withName(String name){
    this.name = name;
    return this;
}

Employee withAge(int age){
    this.age = age;
    return this;
}

Employee withSalary(int salary){
    this.salary = salary;
    return this;
}
}


public class BuilderPatternTest {
    public static void main(String[] args) {
       Employee employee = new Employee().withName("John").withAge(25).withSalary(10000);
    }
}

   Like      Feedback     builder design pattern  builder pattern


 Sample 93. Constructor Overloading

public class Employee {
public String name;
public int age;
public int salary;

// No Argument Constructor
Employee(){
    this.name = "";
    this.age = 0;
    this.salary = 0;
}

// Single Argument Constructor
Employee(String name){
    this.name = name;
    this.age = 0;
    this.salary = 0;
}

// Argument Constructor
Employee(String name,int age){
    this.name = name;
    this.age = age;
    this.salary = 0;
}

// Argument Constructor
Employee(String name,int age,int salary){
    this.name = name;
    this.age = age;
    this.salary = salary;
}
}

   Like      Feedback     constructor  constructor overloading


 Sample 94. getting file path, absolute path and canonical path

public static void main(String[] args){
String parent = null;
File file = new File("/file.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
}

   Like      Feedback     file  absolute path  canonical path  canonical  file handling  java.io.IOException


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 95. Write to a file using File, FileOutputStream and ObjectOutputStream

class BuggyBread1{
   public static void main(String[] args){
      try {
         BuggyBread1 buggybread1 = new BuggyBread1();
         ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
         objectOutputStream.writeObject(buggybread1);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

   Like      Feedback     File   FileOutputStream   ObjectOutputStream   file handling


 Sample 96. Method to get specific format files from a directory

private Collection<File> getDocAndTextFiles() {
File directory = new File("C:DocDir");
if (directory.exists() && directory.isDirectory()) {
Collection<File> files = FileUtils.listFiles(directory, new String[] { "doc","txt" }, false);
}
return files;
}

   Like      Feedback     file handling  file  directory  FileUtils.listFiles  fileutils


 Sample 97. Load XLS file and print first column using poi XSSFWorkbook

public XSSFWorkbook loadXLSAndPrintFirstColumn(File xlsFile) {
   InputStream inputStream = null;
   try {
      inputStream = new FileInputStream(xlsFile);
   XSSFWorkbook xssFWorkbook = new XSSFWorkbook(inputStream);
      Sheet sheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
      for (int index = 0; index < sheet.getPhysicalNumberOfRows(); index++) {
      try {
         Row row = sheet.getRow(index);
            System.out.println(row.getCell(0,Row.CREATE_NULL_AS_BLANK).getStringCellValue()));   
      } catch (Exception e) {
      System.out.println("Exception");
   }
}

}

   Like      Feedback     readinf xls  reading excel  apache poi  XSSFWorkbook  InputStream


 Sample 98. Write a Program for coin changer application. The program should set the cash box with available currency and then should render the exact change. If enough cash is not available , it should present the appropriate message.

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;


public class CoinChanger {

enum Currency {
DOLLAR(1),QUARTER(.25),DIME(.10),NICKEL(.05),PENNY(.01);

private double currencyValue;

Currency(double value){
currencyValue = value;
}

double getCurrencyValue(){
return this.currencyValue;
}
}

private static Map<Currency, Integer> cashBox;
private static Map<Currency, Integer> change;

static {
cashBox = new TreeMap<Currency, Integer>();
change = new TreeMap<Currency, Integer>();
initializeCashBox();
}



public static void main(String[] args) {
double amountToReturn = 18.79f; // Set the amount to be changed here

for(Entry<Currency, Integer> entry:cashBox.entrySet()){
Currency currency = (Currency)entry.getKey();
int coinCount = (int)(amountToReturn/(entry.getKey().getCurrencyValue()));
int availableCurrency = (int)(entry.getValue());

if(coinCount > availableCurrency){
coinCount = availableCurrency;
}

change.put(currency, coinCount);
if(coinCount > 0){
amountToReturn = amountToReturn - (coinCount * entry.getKey().getCurrencyValue());
}
}

System.out.println(change);

if(amountToReturn > .1){
System.out.println("Not enough cash");
}
}

private static void initializeCashBox(){
//set the cash box
cashBox.put(Currency.DOLLAR, 50);
cashBox.put(Currency.QUARTER, 0);
cashBox.put(Currency.DIME, 50);
cashBox.put(Currency.NICKEL, 50);
cashBox.put(Currency.PENNY, 50);

}
}

   Like      Feedback     coin changer application  coin changer app


 Sample 99. Find shortest and longest word in a string

public static void main(String[] args) {
String str = "We are not in Kansas anymore";
String shortestWord = "";
String longestWord = "";
int shortestWordLength = 1000;
int longestWordLength = 0;
String[] splitStr = str.split(" ");
for(String string: splitStr){
if(string.length() > longestWordLength){
longestWord = string;
longestWordLength = string.length();
} else if(string.length() < shortestWordLength){
shortestWord = string;
shortestWordLength = string.length();
}
}

System.out.println("Shortest Word :" + shortestWord);
System.out.println("Longest Word :" + longestWord);
}

   Like      Feedback     string  string.split


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 100. Write a Program to print ascii value of each character of a string

public static void main(String[] args) {
String str = "We are not in Kansas anymore";
for(char character: str.toCharArray()){
System.out.println((int)character);
}
}

   Like      Feedback     ascii  character


 Sample 101. Method to get Date after n days using Calendar

Date getDateAfterDays(int numberOfDays){
   Calendar futureDate = Calendar.getInstance();
   futureDate.setTime(new Date()); // Set Current Date
   futureDate.add(Calendar.DATE, numberOfDays); // Add n days to current Date

   return new Date(futureDate.getTimeInMillis());
}

   Like      Feedback     date   calendar   java.util  calendar.add  calendar.date  calendar.settime  calendar.gettimeinmillis


 Sample 102. Get Date and Time after few Hours

Date getDateTimeAfterNHours(int numberOfHours){
   Calendar futureTime = Calendar.getInstance();
   futureTime.setTime(new Date()); // Set Current Date
   futureTime.add(Calendar.HOUR, numberOfDays); // Add n hours to current Date and Time

   return new Date(futureTime.getTimeInMillis());
}

   Like      Feedback     date   calendar   java.util  calendar.add  calendar.hour  calendar.settime  calendar.gettimeinmillis


 Sample 103. Junit Test

import org.junit.Test;
import org.junit.Ignore;

public class JunitTest {

   @Test
   void test1(){
   }

   @Test
   @Ignore
   void test1(){
   }
}

   Like      Feedback     junit  unit testing  @test  @ignore


 Sample 104. Mocking a method call within Junit Test

@Test
public void test(){
   Employee employee = new Employee();
   employee.setId(123l);   
   DBAccess dbAccess = Mockito.mock(DBAccess.class);
   Mockito.when(dbAccess.getEmployeeInfo(Mockito.anyLong()).thenReturn(null);
}

   Like      Feedback     unit testing  junit  mockito  mocking frameworks  mockito.mock  mockito.when  mockito.anylong  mockito.thenreturn


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 105. Calling an Api using HttpClient and HttpPost

String url = "https://www.googleapis.com/blogger/v3/blogs/xxxxxxxxxx/posts?clientId=xxxxxxxx&clientSecret=xxxxxxxx";

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

// add header
post.setHeader("Authorization", authorization_key);
post.setHeader("Content-type","application/json");
post.setEntity(new StringEntity(buildJson(title,content,label)));

HttpResponse response = client.execute(post);

   Like      Feedback     HttpClient  HttpPost  Calling api


 Sample 106. Initialize maps through static block

public class CoinChanger {
   private static Map<Currency, Integer> cashBox;
   private static Map<Currency, Integer> change;

enum Currency {
      DOLLAR,QUARTER,DIME,NICKEL,PENNY;
   }

   static {
      cashBox = new TreeMap<Currency, Integer>();
      change = new TreeMap<Currency, Integer>();
      initializeCashBox();
   }

   private static void initializeCashBox(){
      //set the cash box
      cashBox.put(Currency.DOLLAR, 50);
      cashBox.put(Currency.QUARTER, 0);
      cashBox.put(Currency.DIME, 50);
      cashBox.put(Currency.NICKEL, 50);
      cashBox.put(Currency.PENNY, 50);
   }
}
}

   Like      Feedback     static block   enum   initializing maps   initializing treemap


 Sample 107. Initialize member elements ( maps ) using constructor

public class CoinChanger {
   private static Map<Currency, Integer> cashBox;
   private static Map<Currency, Integer> change;

   enum Currency {
      DOLLAR,QUARTER,DIME,NICKEL,PENNY;
   }

   CoinChanger() {
      cashBox = new TreeMap<Currency, Integer>();
      change = new TreeMap<Currency, Integer>();
      initializeCashBox();
   }

   private static void initializeCashBox(){
      //set the cash box
      cashBox.put(Currency.DOLLAR, 50);
      cashBox.put(Currency.QUARTER, 0);
      cashBox.put(Currency.DIME, 50);
      cashBox.put(Currency.NICKEL, 50);
      cashBox.put(Currency.PENNY, 50);
   }
}
}

   Like      Feedback     constructor   initializing maps   initializing treemap   enum


 Sample 108. Loading Cache Map using Google Guava LoadingCache and CacheBuilder

LoadingCache<String,String> loadingCache = CacheBuilder.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).build(new CacheLoader<String,String>(){
   @Override
   public String load(String arg0) throws Exception {
      return "";
   }
});

   Like      Feedback     google guava  loadingcache  CacheBuilder  CacheLoader


 Sample 109. Create a new File

File file = new File("xyz.txt");
boolean status = file.createNewFile();

   Like      Feedback     file   file handling  file.createnewfile


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 110. Create a new Directory

File dir = new File("c:xyz");
boolean status = file.mkdir();

   Like      Feedback     file handling  creating new directory  file.mkdir


 Sample 111. Today's Date as per Hijrah Chronology

AbstractChronology abstractChrono = HijrahChronology.INSTANCE;
System.out.println(abstractChrono.dateNow());

   Like      Feedback     Hijrah Date  Hijrah Calendar  Hijrah Chronology  HijrahChronology  java 8  HijrahChronology.INSTANCE  AbstractChronology  AbstractChronology.datenow


 Sample 112. Today's Date as per Japanese Chronology

AbstractChronology abstractChrono = JapaneseChronology.INSTANCE;
System.out.println(abstractChrono.dateNow());

   Like      Feedback     Japanese Chronology  JapaneseChronology  java 8  JapaneseChronology.INSTANCE  AbstractChronology  AbstractChronology.datenow


 Sample 113. Todays Date as per Minguo Chronology

AbstractChronology abstractChrono = MinguoChronology.INSTANCE;
System.out.println(abstractChrono.dateNow());

   Like      Feedback     Minguo Chronology  MinguoChronology  java 8  MinguoChronology.INSTANCE  AbstractChronology  AbstractChronology.datenow


 Sample 114. Todays Date as per ThaiBuddhistChronology

AbstractChronology abstractChrono = ThaiBuddhistChronology.INSTANCE;

System.out.println(abstractChrono.dateNow());

   Like      Feedback     ThaiBuddhist Chronology  ThaiBuddhistChronology  java 8  ThaiBuddhistChronology.INSTANCE  AbstractChronology  AbstractChronology.datenow


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 115. Get the Calendar Type from the abstract chronology

AbstractChronology abstractChrono = ThaiBuddhistChronology.INSTANCE;
System.out.println(abstractChrono.getCalendarType()); // Will print buddhist

   Like      Feedback     AbstractChronology  java 8  AbstractChronology.getCalendarType


 Sample 116. Print the length of year as per IsoChronology

AbstractChronology abstractChrono = IsoChronology.INSTANCE;
System.out.println(abstractChrono.dateNow().lengthOfYear());

   Like      Feedback     AbstractChronology  IsoChronology


 Sample 117. Prints Length of year as per HijrahChronology

AbstractChronology abstractChrono = HijrahChronology.INSTANCE;
System.out.println(abstractChrono.dateNow().lengthOfYear());

   Like      Feedback     AbstractChronology  HijrahChronology


 Sample 118. Get 6 days before today as per HijrahChronology

AbstractChronology abstractChrono = HijrahChronology.INSTANCE;
System.out.println(abstractChrono.dateNow().minus(6, ChronoUnit.DAYS));

   Like      Feedback     AbstractChronology  HijrahChronology  ChronoUnit.DAYS  ChronoUnit


 Sample 119. Get 6 months before today as per JapaneseChronology

AbstractChronology abstractChrono = JapaneseChronology.INSTANCE;
System.out.println(abstractChrono.dateNow().minus(6, ChronoUnit.MONTHS));

   Like      Feedback     AbstractChronology  JapaneseChronology  ChronoUnit  java 8


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 120. Get a unmodifiable / read only Set

Set<String> modifiableSet = Sets.newHashSet();

modifiableSet.add("New York");
modifiableSet.add("Washington");
modifiableSet.add("Georgia");

Set<String> unmodifiableSet = Collections.unmodifiableSet(modifiableSet);

   Like      Feedback     collections  set  unmodifiable set   unmodifiableset   Collections.unmodifiableSet


 Sample 121. Using Pojomatic for overriding equals,hashcode and toString methods

import org.pojomatic.Pojomatic;
import org.pojomatic.annotations.AutoProperty;

@AutoProperty
public class Employee {
   public String name;
   public int age;
   public int salary;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public int getAge() {
      return age;
   }

   public void setAge(int age) {
      this.age = age;
   }

   public int getSalary() {
      return salary;
   }

   public void setSalary(int salary) {
      this.salary = salary;
   }

   @Override
   public int hashCode() {
      return Pojomatic.hashCode(this);
   }

   @Override
   public boolean equals(Object other) {
      return Pojomatic.equals(this, other);
   }

   @Override
   public String toString() {
      return Pojomatic.toString(this);
   }
}

   Like      Feedback     pojomatic  toString method  toString  hashcode method  equals method   overrding equals method  overriding hashcode method  overrding tostring method  @autoproperty  pojomatic autoproperty


 Sample 122. Filtering objects using google.common.base.Predicate

static Collection<Employee> employeesGreaterThan30(Collection<Employee> employees) {
return filter(employees, new Predicate<Employee>() {
@Override
public boolean apply(Employee employee) {
return employee.getAge() > 30;
}
});
}

   Like      Feedback     predicate  google.common.base.Predicate  filter objects   alternate for predicate before java 8  collections  google guava


 Sample 123. Order Collection using google.common.collect.Ordering

Collection<Employee> sortedEmployeess = Ordering.from(new Comparator<Employee>() {
@Override
public int compare(Employee employee1, Employee employee2) {
return employee1.getAge() - employee2.getAge();
}
};).sortedCopy(employees);

   Like      Feedback     collections  sorting collections   sorting collections using google library  comparator  compare method  google.common.collect.Ordering  google guava


 Sample 124. Constant Class

public class Constants {
public static final long ZERO = 0L;
public static final long HUNDRED = 100L;
public static final long THOUSAND = 1000L;
}

   Like      Feedback     constant class  static final variable


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 125. Round a Big Decimal Number with 5 precision and to upper value using MathContext

MathContext mathContext = new MathContext(5,RoundingMode.HALF_UP);
       System.out.println(new BigDecimal(100.4767,mathContext));

   Like      Feedback     rounding a number  BigDecimal  rounding Bigdecimal  RoundingMode  MathContext  RoundingMode.HALF_UP


 Sample 126. Round a Big Decimal Number with 5 precision and to half lower value using MathContext

MathContext mathContext = new MathContext(5,RoundingMode.HALF_DOWN);
System.out.println(new BigDecimal(100.4767,mathContext));

   Like      Feedback     rounding a number  BigDecimal  rounding Bigdecimal  RoundingMode  MathContext  RoundingMode.HALF_DOWN


 Sample 127. Initializing Executor Service within Kafka

int numberOfThreads = 10;

ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);

   Like      Feedback     kafka  kafka executor


 Sample 128. Class Nested within Interface / Static Inner class within Interface

public interface SampleInterface {
   public int sampleMethod(List sampleList);

   static class Impl implements SampleInterface {

      @Override
      public int sampleMethod(List sampleList) {
         return 0;
      }
   }
}

   Like      Feedback     nested classes  nested class  inner class  inner classes  static inner class  static inner class within interface  @override


 Sample 129. Generate a Random float number from 0 to 1

double randomNo = Math.random();
System.out.println(randomNo);

   Like      Feedback     random number   random number generation  Math.random()


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 130. Generate a Random Integer from 0 to 100

double randomNo = Math.random();
System.out.println((int)(randomNo*100));

   Like      Feedback     random number   random number generation  Math.random()


 Sample 131. Get the Maximum of two numbers

int maxNumber = Math.max(100, 500);
System.out.println(maxNumber);

   Like      Feedback     maximum of two numbers  Math.max


 Sample 132. Get the minimum of two numbers

int minNumber = Math.min(100, 500);
System.out.println(minNumber);

   Like      Feedback     maximum of two numbers  Math.min


 Sample 133. Get the Square Root of a Number

double sqrt = Math.sqrt(81);
System.out.println(sqrt);

   Like      Feedback     square root  sqrt  Math.sqrt


 Sample 134. Example of Factory Class

public final class EmployeeFactory {

private Employee svEmp;

public EmployeeFactory(String type){
if( type.equals("Manager")){
svEmp = new Manager();
} else if(type.equals("Developer")){
svEmp = new Developer();
} else if(type.equals("QA")){
svEmp = new QA();
}
}

public Employee getFactoryProduct() {
return svEmp;
}

}

   Like      Feedback     factory design pattern  factory class  final class  composition


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 135. Load Properties using Property Class

private static Properties props = null;
   
private static void loadProperties(){
   try {
      if(props == null || props1 == null || props2 == null){
         props = new Properties();
         props.load(new FileInputStream(Constants.PROP_BASE_DIR + Constants.EMPLOYEE_REPORTING_PROP));
      } catch (FileNotFoundException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }

   }
}

   Like      Feedback     property class  properties  FileInputStream  file handling


 Sample 136. Usage of Iterator

Iterator iterator = ReportingEmp.iterator();
while (iterator.hasNext()) {
   EmployeeBean eb1 = (EmployeeBean)iterator.next();
   EmployeeFactory empFactory = new EmployeeFactory(eb1.getType());
   svEmp = empFactory.getFactoryProduct();
   allocation += svEmp.getAllocation();
}

   Like      Feedback     collections  Iterator


 Sample 137. Database Api using java.sql classes

package BuggyBread;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseAPI {

   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "";

   // Database credentials
   static final String USER = "";
   static final String PASS = "";

   Connection conn = null;
   
   public void initializeConnection(){
      try {
         // STEP 2: Register JDBC driver
         Class.forName("com.mysql.jdbc.Driver");

         // STEP 3: Open a connection
         System.out.println("Connecting to database...");
         conn = DriverManager.getConnection(DB_URL, USER, PASS);

         conn.close();
      } catch (SQLException se) {
         // Handle errors for JDBC
         se.printStackTrace();
      } catch (Exception e) {
         // Handle errors for Class.forName
         e.printStackTrace();
      } finally {
         
         try {
            if (conn != null)
               conn.close();
         } catch (SQLException se) {
            se.printStackTrace();
         }// end finally try
      }// end try
   
   }
}

   Like      Feedback     database api  java.sql


 Sample 138. Get Number of instances a pattern exist in the text

public int getNoOfQuestions(){    
   Pattern p = Pattern.compile("Ans.");
Matcher m = p.matcher(text);
int count = 0;
while (m.find()){
   count = count + 1;
}
return count-3;
}

   Like      Feedback     pattern matching  Pattern  Matcher  Matcher.find


 Sample 139. Load Library

System.loadLibrary("jawt");

   Like      Feedback     System Class  system  System.loadLibrary


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 140. Loading Class using Class.forName ( Reflection )

Class clazz = null;
try {
   clazz = Class.forName("sun.awt.windows.WEmbeddedFrame");
} catch (Throwable e) {
}

Constructor constructor = null;
try {
   constructor = clazz.getConstructor(new Class[] { Integer.TYPE });
} catch (Throwable localThrowable1) {
}

   Like      Feedback     Class.forName  Reflection


 Sample 141. Copy Array using System.arraycopy

String[] stringArray = new String[50];
String[] newStringArray = new String[50];
System.arraycopy(stringArray, 0, newStringArray, 0, 50); //arrayCopy(src,srcPosition,destination,destinationPos,length)

   Like      Feedback     System.arraycopy  Copy array  arrays  array of string


 Sample 142. Method to check if the the file exists and not a directory

public static boolean isOleFile(File file)
{
   if ((file == null) || (!file.exists()) || (file.isDirectory())) {
      return false;
   }

   return true;
}

   Like      Feedback     file handling  check if file exists  File class  check if file is a directory  file.isDirectory  file.exists


 Sample 143. Method to invert / reverse Bit Data

byte[] bitInvertData(byte[] data, int startIndex, int endIndex){
   for (int i = startIndex; i < endIndex; i++) {
      data[i] = ((byte)(255 - data[(i - startIndex)]));
   }
   return data;
}

   Like      Feedback     bit data  reverse bit data  byte[]  byte array


 Sample 144. Java 8 Map Merge Example ( Map.merge )

Map<String,String> intMap = new HashMap<String,String>();
strMap.put("Key1","Value1");
strMap.put("Key2", "Value2");
String str = strMap.merge("Key1","Value56",(v1,v2)->v1.substring(3).concat(v2));
System.out.println(str); // prints ue1Value56
System.out.println(strMap); // prints {Key2=Value2, Key1=ue1Value56}

   Like      Feedback     java 8  map.merge  map merge  hashmap  collections


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 145. Java 8 MapMerge

Map<String,String> strMap = new HashMap<String,String>();
strMap.put("Key1","Value1");
strMap.put("Key2", "Value2");
String str = strMap.merge("Key4","Value56",(v1,v2)->v1.substring(3).concat(v2));
System.out.println(str); // prints Value56
System.out.println(strMap); // prints {Key2=Value2, Key1=Value1, Key4=Value56}

   Like      Feedback     java 8  map.merge  map merge  hashmap  collections


 Sample 146. Repeat a string using Google Guava Strings Class

System.out.println(Strings.repeat("Hello", 5));

   Like      Feedback     google guava  google guava string  strings.repeat  repeat characters   repeat string


 Sample 147. Parse JSON using JSONParser

JSONParser jsonParser = new JSONParser();
String jsonMessage = JSONMessageAsString;

JSONObject jsonObject = null;
try {
jsonObject = (JSONObject) jsonParser.parse(jsonMessage);
} catch (ParseException e) {
System.out.println("Error in Parsing JSON");
}


Long id = (Long) jsonObject.get("Id");
String name = (String) jsonObject.get("Name");

   Like      Feedback     JSON Parsing  JSON Parser


 Sample 148. Convert from Long object to Integer object

Long longValue = 20l;
Integer int = (int)(long)longValue;

   Like      Feedback     long to int  Long to Integer  casting  casting long to integer


 Sample 149. Convert Time in milliseconds to Days

TimeUnit.DAYS.convert(timeinMs, TimeUnit.MILLISECONDS)

   Like      Feedback     convert time in ms to days  TimeUnit  java.util.concurrent.TimeUnit


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 150. Time Taken to call a method or service

Date date1 = new Date();

// Call Service or Method

Date date2 = new Date();
System.out.println(TimeUnit.SECONDS.convert(date2.getTime()-date1.getTime(), TimeUnit.MILLISECONDS));// Time Taken in Seconds
System.out.println(TimeUnit.MINUTES.convert(date2.getTime()-date1.getTime(), TimeUnit.MILLISECONDS));// Time Taken in Minutes
System.out.println(TimeUnit.HOURS.convert(date2.getTime()-date1.getTime(), TimeUnit.MILLISECONDS));// Time Taken in Hours

   Like      Feedback     Difference between 2 dates  Time to call a method  TimeUnit  Date.java.util.Date


 Sample 151. Convert int to String

int x = 5;
String.valueOf(x);

   Like      Feedback     String  String.valueOf  int to String


 Sample 152. RabbitMQ message receiver

import java.util.concurrent.CountDownLatch;

public class Receiver {

   private CountDownLatch latch = new CountDownLatch(1);

   public void receiveMessage(String message) {
      latch.countDown();
   }

   public CountDownLatch getLatch() {
      return latch;
   }

}

   Like      Feedback     Spring AMQP  Rabbit MQ  RabbitMQ


 Sample 153. Implementation of NamespaceContext

import java.util.Iterator;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;

// Map prefixes to Namespace URIs
public class APINameSpaceContext implements NamespaceContext
{
   static final String WEB_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/web";
   static final String API_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element";
   static final String SPELL_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/spell";
   static final String RS_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/relatedsearch";
   static final String PB_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/phonebook";
   static final String MM_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/multimedia";
   static final String AD_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/ads";
   static final String IA_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/instantanswer";
   static final String NEWS_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/news";
   static final String ENCARTA_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/encarta";

   public String getNamespaceURI(String prefix)
   {
      if (prefix == null) throw new NullPointerException("Null prefix");
      else if ("api".equals(prefix)) return API_NAMESPACE;
      else if ("web".equals(prefix)) return WEB_NAMESPACE;
      return XMLConstants.NULL_NS_URI;
   }
   
   // This method isn't necessary for XPath processing.
   public String getPrefix(String uri)
   {
      throw new UnsupportedOperationException();
   }
   
   public Iterator getPrefixes(String arg0)
   {
      throw new UnsupportedOperationException();
   }
}

   Like      Feedback     NamespaceContext


 Sample 154. Usage of java.io.FileInputStream

FileInputStream fis = new FileInputStream("mypodcast.mp3");
InputStreamRequestEntity re = new InputStreamRequestEntity(fis, "audio/mp3");

   Like      Feedback     ileInputStrea


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 155. Internal Implementation of ArrayList#removeIf

@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);

int removeCount = 0;
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
if (filter.test(element)) {
removeSet.set(i);
removeCount++;
}
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}

// shift surviving elements left over the spaces left by removed elements
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
final int newSize = size - removeCount;
for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
i = removeSet.nextClearBit(i);
elementData[j] = elementData[i];
}
for (int k=newSize; k < size; k++) {
elementData[k] = null; // Let gc do its work
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}

return anyToRemove;
}

   Like      Feedback     Internal Implementation of ArrayList#removeIf  java.util.function.Predicate  java.util.Objects  java.util.Objects  java.util.ConcurrentModificationException.ConcurrentModificationException


 Sample 156. Internal Implementation of BufferedReader#lines

public Stream<String> lines() {
Iterator<String> iter = new Iterator<String>() {
String nextLine = null;

@Override
public boolean hasNext() {
if (nextLine != null) {
return true;
} else {
try {
nextLine = readLine();
return (nextLine != null);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}

@Override
public String next() {
if (nextLine != null || hasNext()) {
String line = nextLine;
nextLine = null;
return line;
} else {
throw new NoSuchElementException();
}
}
};
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
iter, Spliterator.ORDERED | Spliterator.NONNULL), false);
}

   Like      Feedback     Internal Implementation of BufferedReader#lines


 Sample 157. Usage of org.joda.time.DateMidnight

DateMidnight currentDate = new DateMidnight();
DateMidnight dateafterAMonth = currentDate.plusMonths(1);
Date javaSedateAfterAMonth = dateafterAMonth.toDate();

   Like      Feedback     org.joda.time.DateMidnight  java.util.Date  Date  Add month to Date


 Sample 158. Use java.time.format.DateTimeFormatter to Parse date in the format YYYYMMDD+HHmmss

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendValue(YEAR, 4)
.appendValue(MONTH_OF_YEAR, 2)
.appendValue(DAY_OF_MONTH, 2)
.appendOffset("+HHMMss", "Z")
.toFormatter();

TemporalAccessor temporal = null;

try {
temporal = dateTimeFormatter.parse("2016101+235700");
System.out.println(temporal.toString()); // prints {OffsetSeconds=86220},ISO resolved to 2016-01-01
} catch (DateTimeParseException ex){
System.out.println("Error parsing date");
}

   Like      Feedback     DateTimeFormatter   Parse Date in Java 8   Parse date using DateTimeFormatter and DateTimeFormatterBuilder


 Sample 159. Check whether a reference of AbstractCollection holds a List,Queue or Set

public static void main(String[] args)  {
      
       AbstractCollection collection = new ArrayList();
      
       if(collection instanceof AbstractList){
          System.out.println("This is a list");
       }
      
       if(collection instanceof AbstractQueue){
          System.out.println("This is a Queue");
       }
      
       if(collection instanceof AbstractSet){
          System.out.println("This is a Set");
       }
      
}

   Like      Feedback     instaceOf  AbstractCollection


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 160. Clear Map entries after expiration time using Apache commons PassiveExpiringMap

PassiveExpiringMap<String,String> cache = new PassiveExpiringMap<String,String>(1000); // Expiration time of 1 sec
cache.put("Key1", "Value1");
System.out.println(cache.containsKey("Key1"));
Thread.sleep(500);
System.out.println(cache.containsKey("Key1"));
Thread.sleep(500);
System.out.println(cache.containsKey("Key1"));

   Like      Feedback     expiring cache using map   Clear Map entries after expiration time   PassiveExpiringMap


 Sample 161. Clear Map entries after expiration time using Apache commons PassiveExpiringMap

PassiveExpiringMap<String,String> cache = new PassiveExpiringMap<String,String>(1,TimeUnit.SECONDS); // Expiration time of 1 sec
cache.put("Key1", "Value1");
System.out.println(cache.containsKey("Key1")); // prints true
Thread.sleep(1000);
System.out.println(cache.containsKey("Key1")); // prints false

   Like      Feedback     Clear Map entries after expiration  PassiveExpiringMap  map  apache commons  TimeUnit.SECONDS  Thread.sleep


 Sample 162. Make a map readonly using Apache Commons UnmodifiableMap

Map<String,String> map = new HashMap();
map.put("Key1", "Value1");

Map<String,String> unmodifiableMap = UnmodifiableMap.unmodifiableMap(map);
      
unmodifiableMap.put("Key2", "Value2"); // throws java.lang.UnsupportedOperationException

   Like      Feedback     readonly map  apache commons


 Sample 163. Make a Map entry read only using Apache Commons UnmodifiableMapEntry

Entry entry = new UnmodifiableMapEntry("Key2", "Value2");
entry.setValue("Value3"); // throws java.lang.UnsupportedOperationException

   Like      Feedback     read only map entry  UnmodifiableMapEntry  Apache commons collections


 Sample 164. Cache Hibernate Entities using EHCache

// net.sf.ehcache.Cache.Cache(String name, int maxElementsInMemory, MemoryStoreEvictionPolicy 
memoryStoreEvictionPolicy, boolean overflowToDisk, String diskStorePath, boolean eternal, long
timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long
diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners)

Ehcache employeeCache = new Cache("Employee", 1000, MemoryStoreEvictionPolicy.FIFO, false, "c:/EmployeeDiskCacheStorage", false, 300,
300, false, 30, null);

employeeCache = new SelfPopulatingCache(employeeCache, new CacheEntryFactory() {
   @Override
   public Object createEntry(Object day) throws Exception {
      Employee employee = getEmployee(1234);
   return employee;
   }
});

CacheManager.getInstance().addCache(employeeCache);

   Like      Feedback     EHCache  cache hibernate entities  CacheManager  CacheEntryFactory  SelfPopulatingCache  MemoryStoreEvictionPolicy  net.sf.ehcache.Cache


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 165. Usage of TreeMap

Map<String,String> treemap = new TreeMap();
treemap.put("United States", "Washington");
treemap.put("Canada", "Ottawa");
treemap.put("Canada", "Ottawa");
treemap.put("South Africa", "Pretoria");
treemap.put("South Africa", "Cape Town");
treemap.put("South Africa", "Bloemfontein");

System.out.println(treemap); // Duplicate Not allowed as it's a Map, Ordered by Keys as it's a TreeMap

   Like      Feedback     TreeMap  Map  java.util


 Sample 166. Usage of LinkedHashMap


Map<String,String> linkedhashmap = new LinkedHashMap();
linkedhashmap.put("United States", "Washington");
linkedhashmap.put("Canada", "Ottawa");
linkedhashmap.put("Canada", "Ottawa");
linkedhashmap.put("South Africa", "Pretoria");
linkedhashmap.put("South Africa", "Cape Town");
linkedhashmap.put("South Africa", "Bloemfontein");

System.out.println(linkedhashmap); // Duplicates not allowed as it's a Map, Insertion Order as its linked Map

   Like      Feedback     LinkedHashMap  Map  HashMap  java.util  collections framework


 Sample 167. Usage of Apache Commons - ArrayListValuedHashMap

ListValuedMap<String,String> listValuedMap = new ArrayListValuedHashMap();
listValuedMap.put("United States", "Washington");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("South Africa", "Pretoria");
listValuedMap.put("South Africa", "Cape Town");
listValuedMap.put("South Africa", "Bloemfontein");

System.out.println(listValuedMap); // Values being added to the List and allow even duplicates

   Like      Feedback     apache commons  apache commons collections  ArrayListValuedHashMap  ListValuedMap


 Sample 168. Usage of Apache Commons - HashSetValuedHashMap

SetValuedMap<String,String> setValuedMap = new HashSetValuedHashMap();
setValuedMap.put("United States", "Washington");
setValuedMap.put("Canada", "Ottawa");
setValuedMap.put("Canada", "Ottawa");
setValuedMap.put("South Africa", "Pretoria");
setValuedMap.put("South Africa", "Cape Town");
setValuedMap.put("South Africa", "Bloemfontein");
      
System.out.println(setValuedMap); // Values being added to the Set and hence doesn't allow duplicates

   Like      Feedback     apache commons   apache commons collections  apache commons map   HashSetValuedHashMap  SetValuedMap


 Sample 169. Print all elements of a ListValuedMap ( Apache Commons ) using forEach and System.out::println

ListValuedMap<String,String> listValuedMap = new ArrayListValuedHashMap();
listValuedMap.put("United States", "Washington");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("South Africa", "Pretoria");
listValuedMap.put("South Africa", "Cape Town");
listValuedMap.put("South Africa", "Bloemfontein");

listValuedMap.entries().forEach(System.out::println);

   Like      Feedback     ListValuedMap  apache commons  System.out::println  collections framework   map


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 170. Get all Permutations of List Elements using Apache Commons PermutationIterator

List<String> list = new ArrayList();
list.add("Washington");
list.add("Nevada");
list.add("California");

PermutationIterator permIterator = new PermutationIterator((Collection) list);
      
permIterator.forEachRemaining(System.out::print); // prints [Washington, Nevada, California][Washington, California, Nevada][California, Washington, Nevada][California, Nevada, Washington][Nevada, California, Washington][Nevada, Washington, California]

   Like      Feedback     Permutations of collection elements  Permutations of List elements  Apache Commons  PermutationIterator  Iterator  Collections  .forEachRemaining  System.out::print  List  ArrayList


 Sample 171. Count elements of a collection matching a Predicate using Apache Commons IterableUtils

List<String> list = new ArrayList();
list.add("Washington");
list.add("Nevada");
list.add("California");
list.add("New York");
list.add("New Jersey");

// <String> long org.apache.commons.collections4.IterableUtils.countMatches(Iterable<String> input, Predicate<? super String> predicate)
      
System.out.println(IterableUtils.countMatches(list, p->((String)p).startsWith("N")));

   Like      Feedback     Apache Commons IterableUtils  Apache Commons  Predicate  Java 8  Count elements of a collection  java8


 Sample 172. Find the Frequency of a Particular element in a Collection using apache Commons IterableUtils

List<String> list = new ArrayList();
list.add("Washington");
list.add("Washington");
list.add("Nevada");
      
System.out.println(IterableUtils.frequency(list, "Washington")); // prints 2

   Like      Feedback     Frequency of a Particular element in a Collection  Apache Commons  IterableUtils  IterableUtils.frequency


 Sample 173. Usage of ConcurrentSkipListMap

Map<String,String> map = new ConcurrentSkipListMap();
map.put("United States", "Washington");
map.put("Canada", "Ottawa");
map.put("Canada", "Ottawa");
map.put("South Africa", "Pretoria");
map.put("South Africa", "Cape Town");
map.put("South Africa", "Bloemfontein");

System.out.println(map); // Prints {Canada=Ottawa, South Africa=Bloemfontein, United States=Washington}
      
// Duplicates not allowed as it's a Map, Sorted as par natural order of keys for faster and concurrent operations.

   Like      Feedback     map  ConcurrentSkipListMap  concurrent access map


 Sample 174. Usage of EnumMap

Map<Country,String> map = new HashMap();
map.put(Country.US, "Washington");
map.put(Country.CANADA, "Ottawa");
map.put(Country.CANADA, "Ottawa");
map.put(Country.SOUTH_AFRICA, "Pretoria");
map.put(Country.SOUTH_AFRICA, "Cape Town");
map.put(Country.SOUTH_AFRICA, "Bloemfontein");

Map<String,String> enumMap = new EnumMap(map); // Prints {CANADA=Ottawa, US=Washington, SOUTH_AFRICA=Bloemfontein}

System.out.println(enumMap); // Duplicates not allowed as it's a Map, Sorted as per order of Enum Declarations

   Like      Feedback     EnumMap  Collections framework  Map  Map with enum keys


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 175. Usage of Apache Commons CaseInsensitiveMap

Map<String, String> map = new CaseInsensitiveMap<String, String>();
map.put("US", "Washington");
map.put("us", "Washington DC");
      
System.out.println(map); // Prints {us=Washington DC} as Keys are case insensitive

   Like      Feedback     CaseInsensitiveMap  Map with Case insensitive keys  apache commons  apache commons collections


 Sample 176. Get Yesterdays Date using Apache Commons DateUtils

Date yesterdayDate = DateUtils.addDays(new Date(), -1);

   Like      Feedback     DateUtils  Apache Commons


 Sample 177. Reading / Parsing Command Line options using apache.commons.cli

public static void main(String[] args) {
   Option option1 = OptionBuilder.withArgName("option").hasArg().create("option");

   Options options = new Options();
   CommandLineParser parser = new GnuParser();
   options.addOption(option1);

   final CommandLine commandLine = parser.parse(options, args);
   final String[] commandLineArgs = commandLine.getArgs();

   if (commandLine.hasOption("option")) {
   }
}

   Like      Feedback     Parsing Command Line options  apache.commons.cli  CommandLineParser  GnuParser  OptionBuilder  Options


 Sample 178. Usage of Arrays using Apache Commons ArrayUtils

int array[] = new int[4];
array[0] = 0;
array[1] = 1;
array[2] = 2;
array[3] = 2;
      
System.out.println(array.length); // Prints 4
System.out.println(ArrayUtils.contains(array, 3)); // Prints false
array = ArrayUtils.add(array, 3); // Add element 3 to the array
System.out.println(array.length); // Prints 5
System.out.println(ArrayUtils.contains(array, 3)); // Prints true
ArrayUtils.lastIndexOf(array, 2); // prints 3
array = ArrayUtils.removeElement(array, 1); // Remove element 1 to the array
System.out.println(array.length); // Prints 4
System.out.println(ArrayUtils.contains(array, 1)); // Prints false

   Like      Feedback     arrays  ArrayUtils  Apache Commons  ArrayUtils Example  ArrayUtils Sample


 Sample 179. Usage of Apache Commons CharSet

String str = new String("Hello World");
CharSet charSet = CharSet.getInstance(str);
System.out.println(charSet.contains('W')); // prints true
System.out.println(charSet.contains('w')); // prints false

   Like      Feedback     CharSet  Apache Commons  CharSet Example  CharSet Sample  String  characters


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 180. Remove characters from the String using CharSetUtils

String str = new String("Hello World"); 
String newStr = CharSetUtils.delete(str, "abcde");
System.out.println(newStr); // prints Hllo Worl

   Like      Feedback     Remove characters from the String  String  CharSetUtils  Apache Commons


 Sample 181. Get the properties of class (i.e package name , interfaces , subclasses etc ) using ClassUtils( Apache Commons )

Class class1 = ClassUtils.getClass("BuggyBreadTest"); 
System.out.println(ClassUtils.getPackageName(class1));
System.out.println(ClassUtils.getAllInterfaces(class1));

   Like      Feedback     ClassUtils  Apache Commons  Get Class Properties  java.lang.Class


 Sample 182. Remove Numbers from a String using CharSetUtils (Apache Commons)

String str = new String("1H4ello1 World2"); 

String newStr = CharSetUtils.delete(str, "1234567890");

System.out.println(newStr); // prints Hello World

   Like      Feedback     Apache Commons  CharSetUtils   Remove Numbers from String


 Sample 183. Remove special characters from a String using CharSetUtils ( Apache Commons )

String str = new String("What's Up ?"); 

String newStr = CharSetUtils.delete(str, "'?");

System.out.println(newStr); // prints Whats Up

   Like      Feedback     Apache Commons  CharSetUtils  Remove characters from String


 Sample 184. Check if the String contains specified characters using CharSetUtils (Apache Commons)

System.out.println(CharSetUtils.containsAny("Whats Up ?", "W")); // Prints true as the String contains character W  System.out.println(CharSetUtils.containsAny("Whats Up ?", "YZ")); // Prints false as the String doesn't contain character Y or Z

   Like      Feedback     CharSetUtils (Apache Commons)  Check if String contains characters


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 185. Print the characters that exist in the specified String using CharSetUtils ( Apache Commons )

System.out.println(CharSetUtils.keep("Whats Up ?", "Watch")); // Prints Wat as only those characters matches in the String 

   Like      Feedback     Characters that exist in String  CharSetUtils ( Apache Commons )


 Sample 186. Apache Commons MultiSet Example

MultiSet<String> multiSet = new HashMultiSet(); 
multiSet.add("Albama");
multiSet.add("Albama");
multiSet.add("Albama");
      
System.out.println(multiSet); // Prints [Albama:3]

   Like      Feedback     Set with duplicate values  MultiSet  Apache Commons Collections


 Sample 187. Create an UnmodifiableMultiSet ( Read only set allowing multiple values ) using Apache Commons

MultiSet<String> multiSet = new HashMultiSet(); 
multiSet.add("Albama");
multiSet.add("Albama");
multiSet.add("Albama");

System.out.println(multiSet); // Prints [Albama:3]
      
UnmodifiableMultiSet<String> unmodifiablemultiSet = (UnmodifiableMultiSet<String>) MultiSetUtils.unmodifiableMultiSet(multiSet);

unmodifiablemultiSet.add("Albama"); // throws java.lang.UnsupportedOperationException

   Like      Feedback     UnmodifiableMultiSet  Apache Commons Collections  Set  MultiSet


 Sample 188. Assign value to BigInteger upon validating the value using BigIntegerValidator ( Apache Commons )

BigIntegerValidator bigIntegerValidator = BigIntegerValidator.getInstance();
BigInteger bigInteger = bigIntegerValidator.validate("1AD2345");
System.out.println(bigInteger); // prints null as the validation fails because of non numeric characters

   Like      Feedback     Validate a Number  Apache Commons  Assign if the Number is valid  BigInteger


 Sample 189. Check if the numerical value is within a specified range using BigIntegerValidator ( Apache Commons )

System.out.println(bigIntegerValidator.isInRange(12, 0, 100)); // prints true because the value 12 falls in range 0-100

   Like      Feedback     Check if the numerical value is within a specified range  Apache Commons  BigIntegerValidator


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 190. Usage of Bit Flags ( Apache Commons )

int male = 1 << 0;
int female = 1 << 1;
      
Flags flag = new Flags(1); // Select the Option
System.out.println(flag); //Prints 0000000000000000000000000000000000000000000000000000000000000001
if(flag.isOn(male)){
   System.out.println("Male"); // Prints Male
}

if(flag.isOn(female)){
   System.out.println("female");
}
   
flag = new Flags(2); // Select the Option
System.out.println(flag); //Prints 0000000000000000000000000000000000000000000000000000000000000010
if(flag.isOn(male)){
   System.out.println("Male");
}
   
if(flag.isOn(female)){
   System.out.println("female"); // prints female
}

   Like      Feedback     Bit Flags   Apache Commons


 Sample 191. Validate an IP Address using InetAddressValidator ( Apache Commons )

InetAddressValidator inetAddressValidator =
InetAddressValidator.getInstance();
if (inetAddressValidator.isValid("123.123.123.123")) {
System.out.println("true"); // prints true
}

if (inetAddressValidator.isValid("www.buggybread.com")) {
System.out.println("true"); // doesn't print true here
}

   Like      Feedback     Validate IP Address   Apache Commons Validator


 Sample 192. Usage of java.net.HttpURLConnection

HttpURLConnection hc = (HttpURLConnection) new URL(tldurl).openConnection();
if (modTime > 0) {
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");//Sun, 06 Nov 1994 08:49:37 GMT
String since = sdf.format(new Date(modTime));
hc.addRequestProperty("If-Modified-Since", since);
}

   Like      Feedback     java.net.HttpURLConnection   HttpURLConnection


 Sample 193. Usage of java.net.IDN

final String input = ".";
final boolean ok = input.equals(IDN.toASCII(input));
System.out.println("IDN.toASCII is " + (ok? "OK" : "BROKEN"));

   Like      Feedback     java.net.IDN  IDN  IDN.toASCII


 Sample 194. Usage of java.lang.reflect.Field;

Form form1 = resources.getForm("fr", "", "", "testForm1_fr");
Field field1 = form1.getField("testProperty1");

   Like      Feedback     Reflection   java.lang.reflect.Field


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 195. Usage of java.lang.reflect.Modifier

Field f = DomainValidator.class.getDeclaredField(arrayName);
final boolean isPrivate = Modifier.isPrivate(f.getModifiers());
if (isPrivate) {
f.setAccessible(true);
}

   Like      Feedback     Reflection  java.lang.reflect.Modifier


 Sample 196. Get the Date object using the TimeZone

TimeZone zone = (TimeZone.getDefault().getRawOffset() == EET.getRawOffset() ? EST : EET);
Date expectedZone = createCalendar(zone, 20051231, 0).getTime();

   Like      Feedback     TimeZone  java.util.TimeZone  Date  Calendar


 Sample 197. Usage of java.text.DecimalFormat

DecimalFormat fmt = new DecimalFormat(pattern);
Float smallestPositive = new Float(Float.MIN_VALUE);
String decimalStr = fmt.format(smallestPositive);

   Like      Feedback     java.text.DecimalFormat


 Sample 198. Usage of java.io.ByteArrayInputStream

ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
result = ois.readObject();

   Like      Feedback     ByteArrayInputStream  java.io  input stream  ObjectInputStream


 Sample 199. Usage of ByteArrayOutputStream

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(validator);
oos.flush();
oos.close();
} catch (Exception e) {
}

   Like      Feedback     java.io.ByteArrayOutputStream  java.io  ObjectOutputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 200. Card Number Validation using CodeValidator and RegexValidator

String CARD_REGEX = "^(5[1-5]d{2})(?:[- ])?(d{4})(?:[- ])?(d{4})(?:[- ])?(d{4})$";
CodeValidator validator = new CodeValidator(CARD_REGEX, LuhnCheckDigit.LUHN_CHECK_DIGIT);
RegexValidator regex = validator.getRegexValidator();

   Like      Feedback     Card Number Validation  Apache Commons  CodeValidator  LuhnCheckDigit.LUHN_CHECK_DIGIT  RegexValidator


 Sample 201. Generate Random Number till 100

Random rand = new Random();
int randomNumber = rand.nextInt(100);

   Like      Feedback     Random Number Generation  Random


 Sample 202. Usage of java.text.NumberFormat

NumberFormat formatter = null;
if (locale != null) {
formatter = NumberFormat.getNumberInstance(locale);
} else {
formatter = NumberFormat.getNumberInstance(Locale.getDefault());
}

   Like      Feedback     NumberFormat  Locale


 Sample 203. Email Validation using org.apache.commons.validator.routines.EmailValidator

EmailValidator validator = new EmailValidator();
validator.isValid("xyz@buggybread.com");

   Like      Feedback     email validation


 Sample 204. Usage of org.apache.commons.validator.ValidatorAction

ValidatorAction va = new ValidatorAction();
va.setName(action);
va.setClassname("org.apache.commons.validator.ValidatorTest");
va.setMethod("formatDate");
va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field");

FormSet fs = new FormSet();
Form form = new Form();
form.setName("testForm");
Field field = new Field();
field.setProperty(property);
field.setDepends(action);
form.addField(field);
fs.addForm(form);

resources.addValidatorAction(va);
resources.addFormSet(fs);

   Like      Feedback     Apache Commons  ValidatorAction  FormSet


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 205. Usage of org.apache.avro.reflect.Union

Union union = c.getAnnotation(Union.class);
if (union != null) {
return getAnnotatedUnion(union, names);
}

   Like      Feedback     Apache Avro


 Sample 206. Usage of java.lang.reflect.ParameterizedType

ParameterizedType ptype = (ParameterizedType)type;
Class raw = (Class)ptype.getRawType();

   Like      Feedback     Reflection  ParameterizedType


 Sample 207. Usage of org.apache.hadoop.conf.Configuration

Configuration conf = new Configuration(
(Configuration)context.getAttribute("name.conf"));
UnixUserGroupInformation.saveToConf(conf,
UnixUserGroupInformation.UGI_PROPERTY_NAME, ugi);
return DFSClient.createNamenode(nn.getNameNodeAddress(), conf);

   Like      Feedback     Apache Hadoop  apache Hadoop Configuration


 Sample 208. Usage of Java Collections Stack

Stack<INodeDirectory> directories = new Stack<INodeDirectory>();
for(directories.push((INodeDirectory)inode); !directories.isEmpty(); ) {
   INodeDirectory d = directories.pop();
}

   Like      Feedback     stack  collections  java.util


 Sample 209. Usage of org.apache.hadoop.hdfs.server.namenode.FSEditLog.EditLogFileInputStream

EditLogFileInputStream edits =
new EditLogFileInputStream(getImageFile(sd, NameNodeFile.EDITS));
numEdits = FSEditLog.loadFSEdits(edits);
edits.close();
File editsNew = getImageFile(sd, NameNodeFile.EDITS_NEW);
if (editsNew.exists() && editsNew.length() > 0) {
edits = new EditLogFileInputStream(editsNew);
numEdits += FSEditLog.loadFSEdits(edits);
edits.close();

   Like      Feedback     EditLogFileInputStream  Apache Hadoop


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 210. Usage of org.apache.hadoop.fs.permission.FsPermission

FsPermission mode = inode.getFsPermission();

if (user.equals(inode.getUserName())) { //user class
if (mode.getUserAction().implies(access)) { return; }
}
else if (groups.contains(inode.getGroupName())) { //group class
if (mode.getGroupAction().implies(access)) { return; }
}
else { //other class
if (mode.getOtherAction().implies(access)) { return; }
}

   Like      Feedback     Apache Hadoop  FsPermission


 Sample 211. Usage of org.apache.hadoop.fs.permission.PermissionStatus

PermissionStatus permissions = fsNamesys.getUpgradePermission();
if (imgVersion <= -11) {
permissions = PermissionStatus.read(in);
}
if (path.length() == 0) { // it is the root
if (nsQuota != -1 || dsQuota != -1) {
fsDir.rootDir.setQuota(nsQuota, dsQuota);
}
fsDir.rootDir.setModificationTime(modificationTime);
fsDir.rootDir.setPermissionStatus(permissions);
continue;

   Like      Feedback     Apache Hadoop  PermissionStatus


 Sample 212. Usage of org.apache.hadoop.hdfs.server.namenode.NameNode

NameNode nn = (NameNode)context.getAttribute("name.node");
Configuration conf = new Configuration(
(Configuration)context.getAttribute("name.conf"));
UnixUserGroupInformation.saveToConf(conf,
UnixUserGroupInformation.UGI_PROPERTY_NAME, ugi);
return DFSClient.createNamenode(nn.getNameNodeAddress(), conf);

   Like      Feedback     Apache Hadoop  NameNode


 Sample 213. Usage of org.apache.hadoop.metrics.MetricsUtil

MetricsContext metricsContext = MetricsUtil.getContext("dfs");
directoryMetrics = MetricsUtil.createRecord(metricsContext, "FSDirectory");
directoryMetrics.setTag("sessionId", conf.get("session.id"));

   Like      Feedback     Apache Hadoop  MetricsUtil


 Sample 214. Usage of org.apache.hadoop.metrics.MetricsContext

MetricsContext metricsContext = MetricsUtil.getContext("dfs");
directoryMetrics = MetricsUtil.createRecord(metricsContext, "FSDirectory");
directoryMetrics.setTag("sessionId", conf.get("session.id"));

   Like      Feedback     Apache Hadoop MetricsContext


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 215. Usage of MD5MD5CRC32FileChecksum

final MD5MD5CRC32FileChecksum checksum = DFSClient.getFileChecksum(filename, nnproxy, socketFactory, socketTimeout);
MD5MD5CRC32FileChecksum.write(xml, checksum);

   Like      Feedback     MD5MD5CRC32FileChecksum  Apache Hadoop


 Sample 216. Usage of java.nio.channels.FileLock

File lockF = new File(root, STORAGE_FILE_LOCK);
lockF.deleteOnExit();
RandomAccessFile file = new RandomAccessFile(lockF, "rws");
FileLock res = null;
try {
   res = file.getChannel().tryLock();
} catch(OverlappingFileLockException oe) {

}

   Like      Feedback     java.nio  FileLock  input output  file handling


 Sample 217. Usage of org.xml.sax.XMLReader

XMLReader xr = XMLReaderFactory.createXMLReader();
xr.setContentHandler(this);
HttpURLConnection connection = openConnection("/listPaths" + path,
"ugi=" + ugi + (recur? "&recursive=yes" : ""));
connection.setRequestMethod("GET");
connection.connect();

InputStream resp = connection.getInputStream();
xr.parse(new InputSource(resp));

   Like      Feedback     org.xml.sax.XMLReader


 Sample 218. Usage of SslListener

SslListener sslListener = new SslListener();
sslListener.setHost(addr.getHostName());
sslListener.setPort(addr.getPort());
sslListener.setKeystore(keystore);
sslListener.setPassword(storPass);
sslListener.setKeyPassword(keyPass);
webServer.addListener(sslListener);

   Like      Feedback     SslListener


 Sample 219. Usage of org.jets3t.service.security.AWSCredentials and S3Credentials

S3Credentials s3Credentials = new S3Credentials();
s3Credentials.initialize(uri, conf);
try {
   AWSCredentials awsCredentials = new AWSCredentials(s3Credentials.getAccessKey(),
   s3Credentials.getSecretAccessKey());
   this.s3Service = new RestS3Service(awsCredentials);
} catch (S3ServiceException e) {
}

   Like      Feedback     AWSCredentials  S3Credentials  Apache Hadoop


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 220. Usage of javax.xml.transform.Transformer, TransformerFactory

TransformerFactory tFactory = TransformerFactory.newInstance();

Transformer transformer = tFactory.newTransformer(
new StreamSource(styleSheet)
);

transformer.transform(new StreamSource(xml), new StreamResult(out));

   Like      Feedback     TransformerFactory  Transformer


 Sample 221. Bitwise comparison of objects , compareTo Implementation

public int compareTo(Object other) {
   Buffer right = ((Buffer) other);
   byte[] lb = this.get();
   byte[] rb = right.get();
   for (int i = 0; i < count && i < right.count; i++) {
      int a = (lb[i] & 0xff);
      int b = (rb[i] & 0xff);
      if (a != b) {
         return a - b;
      }
   }
   return count - right.count;
}

   Like      Feedback     compareTo  java.nio.Buffer


 Sample 222. Get Length of String having UTF8 Characters

public static int utf8Length(String string) {
   CharacterIterator iter = new StringCharacterIterator(string);
   char ch = iter.first();
   int size = 0;
   while (ch != CharacterIterator.DONE) {
      if ((ch >= 0xD800) && (ch < 0xDC00)) {
         char trail = iter.next();
         if ((trail > 0xDBFF) && (trail < 0xE000)) {
            size += 4;
         } else {
            size += 3;
            iter.previous(); // rewind one
         }
      } else if (ch < 0x80) {
         size++;
      } else if (ch < 0x800) {
         size += 2;
      } else {
         size += 3;
      }
      ch = iter.next();
   }
   return size;
}

   Like      Feedback     UTF8 characters  CharacterIterator.DONE  CharacterIterator  StringCharacterIterator


 Sample 223. Count Occurences of substring in a String using StringUtils ( Apache Commons )

if(StringUtils.countMatches(snippet, "{") == StringUtils.countMatches(snippet, "}")){
         System.out.println("Yes a Valid Code Snippet");
      }

   Like      Feedback     StringUtils  Apache Commons  Count Occurences of substring


 Sample 224. Example / Sample of import org.apache.hadoop.hdfs.server.namenode.DatanodeDescriptor.BlockTargetPair;

  public BlockCommand(int action, List<BlockTargetPair> blocktargetlist) {

super(action);



blocks = new Block[blocktargetlist.size()];

targets = new DatanodeInfo[blocks.length][];

for(int i = 0; i < blocks.length; i++) {

BlockTargetPair p = blocktargetlist.get(i);

blocks[i] = p.block;

targets[i] = p.targets;

}

}




   Like      Feedback      org.apache.hadoop.hdfs.server.namenode.DatanodeDescriptor.BlockTargetPair


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 225. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.server.namenode.DatanodeDescriptor.BlockTargetPair

  public BlockCommand(int action, List<BlockTargetPair> blocktargetlist) {

super(action);



blocks = new Block[blocktargetlist.size()];

targets = new DatanodeInfo[blocks.length][];

for(int i = 0; i < blocks.length; i++) {

BlockTargetPair p = blocktargetlist.get(i);

blocks[i] = p.block;

targets[i] = p.targets;

}

}




   Like      Feedback      org.apache.hadoop.hdfs.server.namenode.DatanodeDescriptor.BlockTargetPair


 Sample 226. Code Sample / Example / Snippet of org.apache.hadoop.util.Daemon

  public static void main(String[] argv) throws Exception {

StringUtils.startupShutdownMessage(SecondaryNameNode.class, argv, LOG);

Configuration tconf = new Configuration();

if (argv.length >= 1) {

SecondaryNameNode secondary = new SecondaryNameNode(tconf);

int ret = secondary.processArgs(argv);

System.exit(ret);

}



Daemon checkpointThread = new Daemon(new SecondaryNameNode(tconf));

checkpointThread.start();

}


   Like      Feedback      org.apache.hadoop.util.Daemon


 Sample 227. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.server.namenode.NameNode

  protected ClientProtocol createNameNodeProxy(UnixUserGroupInformation ugi

) throws IOException {

ServletContext context = getServletContext();

NameNode nn = (NameNode)context.getAttribute("name.node");

Configuration conf = new Configuration(

(Configuration)context.getAttribute("name.conf"));

UnixUserGroupInformation.saveToConf(conf,

UnixUserGroupInformation.UGI_PROPERTY_NAME, ugi);

return DFSClient.createNamenode(nn.getNameNodeAddress(), conf);

}


   Like      Feedback      org.apache.hadoop.hdfs.server.namenode.NameNode


 Sample 228. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.server.namenode.FSNamesystem

  private void doMerge(CheckpointSignature sig) throws IOException {

FSNamesystem namesystem =

new FSNamesystem(checkpointImage, conf);

assert namesystem.dir.fsImage == checkpointImage;

checkpointImage.doMerge(sig);

}


   Like      Feedback      org.apache.hadoop.hdfs.server.namenode.FSNamesystem


 Sample 229. Code Sample / Example / Snippet of org.apache.hadoop.fs.FileStatus

  public synchronized void setPermission(String src, FsPermission permission

) throws IOException {

checkOwner(src);

dir.setPermission(src, permission);

getEditLog().logSync();

if (auditLog.isInfoEnabled()) {

final FileStatus stat = dir.getFileInfo(src);

logAuditEvent(UserGroupInformation.getCurrentUGI(),

Server.getRemoteIp(),

"setPermission", src, null, stat);

}

}


   Like      Feedback      org.apache.hadoop.fs.FileStatus


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 230. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.protocol.Block

  private Block allocateBlock(String src, INode[] inodes) throws IOException {

Block b = null;

do {

b = new Block(FSNamesystem.randBlockId.nextLong(), 0,

getGenerationStamp());

} while (isValidBlock(b));

b = dir.addBlock(src, inodes, b);

NameNode.stateChangeLog.info("BLOCK* NameSystem.allocateBlock: "

+src+ ". "+b);

return b;

}




   Like      Feedback      org.apache.hadoop.hdfs.protocol.Block


 Sample 231. Code Sample / Example / Snippet of javax.rmi.CORBA.ValueHandler

    public synchronized IOR getFVDCodeBaseIOR()

{

checkShutdownState();



if (codeBaseIOR != null) // i.e. We are already connected to it

return codeBaseIOR;



CodeBase cb;



ValueHandler vh = ORBUtility.createValueHandler();



cb = (CodeBase)vh.getRunTimeCodeBase();

return ORBUtility.connectAndGetIOR( this, cb ) ;

}


   Like      Feedback      javax.rmi.CORBA.ValueHandler


 Sample 232. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory

  public File getFsEditName() throws IOException {

return getEditLog().getFsEditName();

}



File getFsTimeName() {

StorageDirectory sd = null;

for (Iterator<StorageDirectory> it =

dirIterator(); it.hasNext();)

sd = it.next();

return getImageFile(sd, NameNodeFile.TIME);

}


   Like      Feedback      org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory


 Sample 233. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.server.common.UpgradeStatusReport

  public String getUpgradeStatusText() {

String statusText = "";

try {

UpgradeStatusReport status =

fsn.distributedUpgradeProgress(UpgradeAction.GET_STATUS);

statusText = (status == null ?

"There are no upgrades in progress." :

status.getStatusText(false));

} catch(IOException e) {

statusText = "Upgrade status unknown.";

}

return statusText;

}


   Like      Feedback      org.apache.hadoop.hdfs.server.common.UpgradeStatusReport


 Sample 234. Code Sample / Example / Snippet of org.apache.hadoop.util.DataChecksum

  private static BlockMetadataHeader readHeader(short version, DataInputStream in) 

throws IOException {

DataChecksum checksum = DataChecksum.newDataChecksum(in);

return new BlockMetadataHeader(version, checksum);

}


   Like      Feedback      org.apache.hadoop.util.DataChecksum


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 235. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.protocol.UnregisteredDatanodeException

  public DatanodeDescriptor getDatanode(DatanodeID nodeID) throws IOException {

UnregisteredDatanodeException e = null;

DatanodeDescriptor node = datanodeMap.get(nodeID.getStorageID());

if (node == null)

return null;

if (!node.getName().equals(nodeID.getName())) {

e = new UnregisteredDatanodeException(nodeID, node);

NameNode.stateChangeLog.fatal("BLOCK* NameSystem.getDatanode: "

+ e.getLocalizedMessage());

throw e;

}

return node;

}




   Like      Feedback      org.apache.hadoop.hdfs.protocol.UnregisteredDatanodeException


 Sample 236. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.DistributedFileSystem

  public int metaSave(String[] argv, int idx) throws IOException {

String pathname = argv[idx];

DistributedFileSystem dfs = (DistributedFileSystem) fs;

dfs.metaSave(pathname);

System.out.println("Created file " + pathname + " on server " +

dfs.getUri());

return 0;

}


   Like      Feedback      org.apache.hadoop.hdfs.DistributedFileSystem


 Sample 237. Code Sample / Example / Snippet of org.mortbay.jetty.servlet.FilterHolder

  protected void defineFilter(WebApplicationContext ctx, String name,

String classname, Map<String, String> parameters, String[] urls) {



WebApplicationHandler handler = ctx.getWebApplicationHandler();

FilterHolder holder = handler.defineFilter(name, classname);

if (parameters != null) {

for(Map.Entry<String, String> e : parameters.entrySet()) {

holder.setInitParameter(e.getKey(), e.getValue());

}

}



for (String url : urls) {

handler.addFilterPathMapping(url, name, Dispatcher.__ALL);

}

}


   Like      Feedback      org.mortbay.jetty.servlet.FilterHolder


 Sample 238. Code Sample / Example / Snippet of org.mortbay.jetty.servlet.WebApplicationHandler

  protected void defineFilter(WebApplicationContext ctx, String name,

String classname, Map<String, String> parameters, String[] urls) {



WebApplicationHandler handler = ctx.getWebApplicationHandler();

FilterHolder holder = handler.defineFilter(name, classname);

if (parameters != null) {

for(Map.Entry<String, String> e : parameters.entrySet()) {

holder.setInitParameter(e.getKey(), e.getValue());

}

}



for (String url : urls) {

handler.addFilterPathMapping(url, name, Dispatcher.__ALL);

}

}


   Like      Feedback      org.mortbay.jetty.servlet.WebApplicationHandler


 Sample 239. Code Sample / Example / Snippet of org.apache.hadoop.io.DataOutputBuffer

    private void writeHeader() throws IOException {

out.write(Server.HEADER.array());

out.write(Server.CURRENT_VERSION);

DataOutputBuffer buf = new DataOutputBuffer();

ObjectWritable.writeObject(buf, remoteId.getTicket(),

UserGroupInformation.class, conf);

int bufLen = buf.getLength();

out.writeInt(bufLen);

out.write(buf.getData(), 0, bufLen);

}


   Like      Feedback      org.apache.hadoop.io.DataOutputBuffer


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 240. Code Sample / Example / Snippet of org.apache.hadoop.security.UserGroupInformation

    public Connection(ConnectionId remoteId) throws IOException {

if (remoteId.getAddress().isUnresolved()) {

throw new UnknownHostException("unknown host: " +

remoteId.getAddress().getHostName());

}

this.remoteId = remoteId;

UserGroupInformation ticket = remoteId.getTicket();

this.setName("IPC Client (" + socketFactory.hashCode() +") connection to " +

remoteId.getAddress().toString() +

" from " + ((ticket==null)?"an unknown user":ticket.getUserName()));

this.setDaemon(true);

}


   Like      Feedback      org.apache.hadoop.security.UserGroupInformation


 Sample 241. Code Sample / Example / Snippet of org.apache.hadoop.io.ObjectWritable

    public void readFields(DataInput in) throws IOException {

methodName = UTF8.readString(in);

parameters = new Object[in.readInt()];

parameterClasses = new Class[parameters.length];

ObjectWritable objectWritable = new ObjectWritable();

for (int i = 0; i < parameters.length; i++) {

parameters[i] = ObjectWritable.readObject(in, objectWritable, this.conf);

parameterClasses[i] = objectWritable.getDeclaredClass();

}

}


   Like      Feedback      org.apache.hadoop.io.ObjectWritable


 Sample 242. Code Sample / Example / Snippet of org.apache.hadoop.fs.FileSystem

  public static long getTimestamp(Configuration conf, URI cache)

throws IOException {

FileSystem fileSystem = FileSystem.get(cache, conf);

Path filePath = new Path(cache.getPath());



return fileSystem.getFileStatus(filePath).getModificationTime();

}


   Like      Feedback      org.apache.hadoop.fs.FileSystem


 Sample 243. Code Sample / Example / Snippet of org.apache.hadoop.util.Shell.ShellCommandExecutor

    public void runScript(List<String> args, File dir) throws IOException {

ShellCommandExecutor shexec =

new ShellCommandExecutor(args.toArray(new String[0]), dir);

shexec.execute();

int exitCode = shexec.getExitCode();

if (exitCode != 0) {

throw new IOException("Task debug script exit with nonzero status of "

+ exitCode + ".");

}

}


   Like      Feedback      org.apache.hadoop.util.Shell.ShellCommandExecutor


 Sample 244. Code Sample / Example / Snippet of java.text.NumberFormat

  public static String getUniqueName(JobConf conf, String name) {

int partition = conf.getInt("mapred.task.partition", -1);

if (partition == -1) {

throw new IllegalArgumentException(

"This method can only be called from within a Job");

}



String taskType = (conf.getBoolean("mapred.task.is.map", true)) ? "m" : "r";



NumberFormat numberFormat = NumberFormat.getInstance();

numberFormat.setMinimumIntegerDigits(5);

numberFormat.setGroupingUsed(false);



return name + "-" + taskType + "-" + numberFormat.format(partition);

}


   Like      Feedback      java.text.NumberFormat


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 245. Code Sample / Example / Snippet of org.apache.hadoop.fs.FSDataInputStream

    private void init() throws IOException {

if (reader == null) {

FSDataInputStream in = fs.open(file);

in.seek(segmentOffset);

reader = new Reader<K, V>(conf, in, segmentLength, codec);

}

}


   Like      Feedback      org.apache.hadoop.fs.FSDataInputStream


 Sample 246. Code Sample / Example / Snippet of org.apache.hadoop.fs.BlockLocation

  protected int getBlockIndex(BlockLocation[] blkLocations, 

long offset) {

for (int i = 0 ; i < blkLocations.length; i++) {

if ((blkLocations[i].getOffset() <= offset) &&

(offset < blkLocations[i].getOffset() + blkLocations[i].getLength())){

return i;

}

}

BlockLocation last = blkLocations[blkLocations.length -1];

long fileLength = last.getOffset() + last.getLength() -1;

throw new IllegalArgumentException("Offset " + offset +

" is outside of file (0.." +

fileLength + ")");

}


   Like      Feedback      org.apache.hadoop.fs.BlockLocation


 Sample 247. Code Sample / Example / Snippet of org.apache.commons.httpclient.HttpMethod

  private static int httpNotification(String uri) throws IOException {

URI url = new URI(uri, false);

HttpClient m_client = new HttpClient();

HttpMethod method = new GetMethod(url.getEscapedURI());

method.setRequestHeader("Accept", "*/*");

return m_client.executeMethod(method);

}


   Like      Feedback      org.apache.commons.httpclient.HttpMethod


 Sample 248. Code Sample / Example / Snippet of org.apache.commons.httpclient.HttpClient

  private static int httpNotification(String uri) throws IOException {

URI url = new URI(uri, false);

HttpClient m_client = new HttpClient();

HttpMethod method = new GetMethod(url.getEscapedURI());

method.setRequestHeader("Accept", "*/*");

return m_client.executeMethod(method);

}


   Like      Feedback      org.apache.commons.httpclient.HttpClient


 Sample 249. Code Sample / Example / Snippet of org.apache.hadoop.util.MergeSort

  public RawKeyValueIterator sort() {

MergeSort m = new MergeSort(this);

int count = super.count;

if (count == 0) return null;

int [] pointers = super.pointers;

int [] pointersCopy = new int[count];

System.arraycopy(pointers, 0, pointersCopy, 0, count);

m.mergeSort(pointers, pointersCopy, 0, count);

return new MRSortResultIterator(super.keyValBuffer, pointersCopy,

super.startOffsets, super.keyLengths, super.valueLengths);

}


   Like      Feedback      org.apache.hadoop.util.MergeSort


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 250. Code Sample / Example / Snippet of org.apache.hadoop.mapred.TaskTracker.TaskInProgress

  public synchronized boolean statusUpdate(TaskAttemptID taskid, 

TaskStatus taskStatus)

throws IOException {

TaskInProgress tip = tasks.get(taskid);

if (tip != null) {

tip.reportProgress(taskStatus);

return true;

} else {

LOG.warn("Progress from unknown child task: "+taskid);

return false;

}

}


   Like      Feedback      org.apache.hadoop.mapred.TaskTracker.TaskInProgress


 Sample 251. Code Sample / Example / Snippet of org.apache.hadoop.mapred.Counters.Counter

  public synchronized void incrAllCounters(Counters other) {

for (Group otherGroup: other) {

Group group = getGroup(otherGroup.getName());

group.displayName = otherGroup.displayName;

for (Counter otherCounter : otherGroup) {

Counter counter = group.getCounterForName(otherCounter.getName());

counter.displayName = otherCounter.displayName;

counter.value += otherCounter.value;

}

}

}


   Like      Feedback      org.apache.hadoop.mapred.Counters.Counter


 Sample 252. Code Sample / Example / Snippet of org.apache.hadoop.mapred.Mapper

  public void map(Object key, Object value, OutputCollector output,

Reporter reporter) throws IOException {

Mapper mapper = chain.getFirstMap();

if (mapper != null) {

mapper.map(key, value, chain.getMapperCollector(0, output, reporter),

reporter);

}

}


   Like      Feedback      org.apache.hadoop.mapred.Mapper


 Sample 253. Code Sample / Example / Snippet of java.util.StringTokenizer

  public static List<String> getNamedOutputsList(JobConf conf) {

List<String> names = new ArrayList<String>();

StringTokenizer st = new StringTokenizer(conf.get(NAMED_OUTPUTS, ""), " ");

while (st.hasMoreTokens()) {

names.add(st.nextToken());

}

return names;

}


   Like      Feedback      java.util.StringTokenizer


 Sample 254. Code Sample / Example / Snippet of org.apache.hadoop.io.serializer.Serialization

  public OutputCollector getMapperCollector(int mapperIndex,

OutputCollector output,

Reporter reporter) {

Serialization keySerialization = mappersKeySerialization.get(mapperIndex);

Serialization valueSerialization =

mappersValueSerialization.get(mapperIndex);

return new ChainOutputCollector(mapperIndex, keySerialization,

valueSerialization, output, reporter);

}


   Like      Feedback      org.apache.hadoop.io.serializer.Serialization


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 255. Code Sample / Example / Snippet of org.apache.hadoop.mapred.lib.KeyFieldHelper.KeyDescription

  public void setKeyFieldSpec(int start, int end) {

if (end >= start) {

KeyDescription k = new KeyDescription();

k.beginFieldIdx = start;

k.endFieldIdx = end;

keySpecSeen = true;

allKeySpecs.add(k);

}

}




   Like      Feedback     org.apache.hadoop.mapred.lib.KeyFieldHelper.KeyDescription


 Sample 256. Code Sample / Example / Snippet of com.sun.corba.se.spi.orb.PropertyParser

    protected PropertyParser makeParser()

{

PropertyParser result = new PropertyParser() ;

for (int ctr=0; ctr<entries.length; ctr++ ) {

ParserData entry = entries[ctr] ;

entry.addToParser( result ) ;

}



return result ;

}


   Like      Feedback      com.sun.corba.se.spi.orb.PropertyParser


 Sample 257. Code Sample / Example / Snippet of com.sun.corba.se.spi.orb.Operation

        public PropertyParser makeParser()

{

PropertyParser parser = new PropertyParser() ;

Operation action = OperationFactory.compose(

OperationFactory.suffixAction(),

OperationFactory.classAction()

) ;

parser.addPrefix( ORBConstants.SUN_PREFIX + "ORBUserConfigurators",

action, "userConfigurators", Class.class ) ;

return parser ;

}


   Like      Feedback      com.sun.corba.se.spi.orb.Operation


 Sample 258. Code Sample / Example / Snippet of java.util.Calendar

    public static double year()

{

Calendar cal = Calendar.getInstance();

return cal.get(Calendar.YEAR);

}


   Like      Feedback      java.util.Calendar


 Sample 259. Code Sample / Example / Snippet of java.text.SimpleDateFormat

    private static String getNameOrAbbrev(String format)

{

Calendar cal = Calendar.getInstance();

SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.ENGLISH);

return dateFormat.format(cal.getTime());

}


   Like      Feedback      java.text.SimpleDateFormat


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 260. Code Sample / Example / Snippet of java.util.zip.DeflaterOutputStream

    private byte[] deflate(byte[] b) throws IOException {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

DeflaterOutputStream dos = new DeflaterOutputStream(baos);

dos.write(b);

dos.close();

return baos.toByteArray();

}


   Like      Feedback      java.util.zip.DeflaterOutputStream


 Sample 261. Code Sample / Example / Snippet of javax.swing.MenuElement

    public MenuElement[] getSelectedPath() {

MenuElement res[] = new MenuElement[selection.size()];

int i,c;

for(i=0,c=selection.size();i<c;i++)

res[i] = selection.elementAt(i);

return res;

}


   Like      Feedback      javax.swing.MenuElement


 Sample 262. Code Sample / Example / Snippet of java.util.EventListener

    private void readObject(ObjectInputStream s)

throws IOException, ClassNotFoundException {

listenerList = NULL_ARRAY;

s.defaultReadObject();

Object listenerTypeOrNull;



while (null != (listenerTypeOrNull = s.readObject())) {

ClassLoader cl = Thread.currentThread().getContextClassLoader();

EventListener l = (EventListener)s.readObject();

String name = (String) listenerTypeOrNull;

ReflectUtil.checkPackageAccess(name);

add((Class<EventListener>)Class.forName(name, true, cl), l);

}

}




   Like      Feedback      java.util.EventListener


 Sample 263. Code Sample / Example / Snippet of java.awt.Polygon

    private Polygon getBorderShape(int side) {

Polygon shape = null;

int[] widths = getWidths();

if (widths[side] != 0) {

shape = new Polygon(new int[4], new int[4], 0);

shape.addPoint(0, 0);

shape.addPoint(-widths[(side + 3) % 4], -widths[side]);

shape.addPoint(widths[(side + 1) % 4], -widths[side]);

shape.addPoint(0, 0);

}

return shape;

}


   Like      Feedback      java.awt.Polygon


 Sample 264. Code Sample / Example / Snippet of javax.swing.JEditorPane

        public EditorKit getEditorKitForContentType(String type) {

EditorKit editorKit = super.getEditorKitForContentType(type);

JEditorPane outerMostJEditorPane = null;

if ((outerMostJEditorPane = getOutermostJEditorPane()) != null) {

EditorKit inheritedEditorKit = outerMostJEditorPane.getEditorKitForContentType(type);

if (! editorKit.getClass().equals(inheritedEditorKit.getClass())) {

editorKit = (EditorKit) inheritedEditorKit.clone();

setEditorKitForContentType(type, editorKit);

}

}

return editorKit;

}


   Like      Feedback      javax.swing.JEditorPane


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 265. Code Sample / Example / Snippet of javax.swing.GrayFilter

    public static Image createDisabledImage (Image i) {

GrayFilter filter = new GrayFilter(true, 50);

ImageProducer prod = new FilteredImageSource(i.getSource(), filter);

Image grayImage = Toolkit.getDefaultToolkit().createImage(prod);

return grayImage;

}


   Like      Feedback      javax.swing.GrayFilter


 Sample 266. Code Sample / Example / Snippet of javax.naming.CompositeName

    public static void main(String[] args) throws Exception {

CompositeName c = new CompositeName("aaa/bbb");

java.io.FileOutputStream f1 = new java.io.FileOutputStream("/tmp/ser");

java.io.ObjectOutputStream s1 = new java.io.ObjectOutputStream(f1);

s1.writeObject(c);

s1.close();

java.io.FileInputStream f2 = new java.io.FileInputStream("/tmp/ser");

java.io.ObjectInputStream s2 = new java.io.ObjectInputStream(f2);

c = (CompositeName)s2.readObject();



System.out.println("Size: " + c.size());

System.out.println("Size: " + c.snit);

}


   Like      Feedback      javax.naming.CompositeName


 Sample 267. Code Sample / Example / Snippet of java.time.zone.ZoneRules

    public static LocalDateTime ofInstant(Instant instant, ZoneId zone) {

Objects.requireNonNull(instant, "instant");

Objects.requireNonNull(zone, "zone");

ZoneRules rules = zone.getRules();

ZoneOffset offset = rules.getOffset(instant);

return ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);

}


   Like      Feedback      java.time.zone.ZoneRules


 Sample 268. Code Sample / Example / Snippet of java.time.temporal.ChronoUnit

    public LocalDateTime plus(long amountToAdd, TemporalUnit unit) {

if (unit instanceof ChronoUnit) {

ChronoUnit f = (ChronoUnit) unit;

switch (f) {

case NANOS: return plusNanos(amountToAdd);

case MICROS: return plusDays(amountToAdd / MICROS_PER_DAY).plusNanos((amountToAdd % MICROS_PER_DAY) * 1000);

case MILLIS: return plusDays(amountToAdd / MILLIS_PER_DAY).plusNanos((amountToAdd % MILLIS_PER_DAY) * 1000_000);

case SECONDS: return plusSeconds(amountToAdd);

case MINUTES: return plusMinutes(amountToAdd);

case HOURS: return plusHours(amountToAdd);

case HALF_DAYS: return plusDays(amountToAdd / 256).plusHours((amountToAdd % 256) * 12); // no overflow (256 is multiple of 2)

}

return with(date.plus(amountToAdd, unit), time);

}

return unit.addTo(this, amountToAdd);

}




   Like      Feedback      java.time.temporal.ChronoUnit


 Sample 269. Code Sample / Example / Snippet of java.time.zone.ZoneOffsetTransition

    public static ZonedDateTime ofLocal(LocalDateTime localDateTime, ZoneId zone, ZoneOffset preferredOffset) {

Objects.requireNonNull(localDateTime, "localDateTime");

Objects.requireNonNull(zone, "zone");

if (zone instanceof ZoneOffset) {

return new ZonedDateTime(localDateTime, (ZoneOffset) zone, zone);

}

ZoneRules rules = zone.getRules();

List<ZoneOffset> validOffsets = rules.getValidOffsets(localDateTime);

ZoneOffset offset;

if (validOffsets.size() == 1) {

offset = validOffsets.get(0);

} else if (validOffsets.size() == 0) {

ZoneOffsetTransition trans = rules.getTransition(localDateTime);

localDateTime = localDateTime.plusSeconds(trans.getDuration().getSeconds());

offset = trans.getOffsetAfter();

} else {

if (preferredOffset != null && validOffsets.contains(preferredOffset)) {

offset = preferredOffset;

} else {

offset = Objects.requireNonNull(validOffsets.get(0), "offset"); // protect against bad ZoneRules

}

}

return new ZonedDateTime(localDateTime, offset, zone);

}


   Like      Feedback      java.time.zone.ZoneOffsetTransition


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 270. Concatenate two Streams

public static IntStream concat(IntStream a, IntStream b) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);

Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt(
a.spliterator(), b.spliterator());
IntStream stream = StreamSupport.intStream(split, a.isParallel() || b.isParallel());
return stream.onClose(Streams.composedClose(a, b));
}

   Like      Feedback     Concatenate two Streams   java 8  java8


 Sample 271. Code Sample / Example / Snippet of java.time.LocalDateTime

    public boolean equals(Object obj) {

if (this == obj) {

return true;

}

if (obj instanceof LocalDateTime) {

LocalDateTime other = (LocalDateTime) obj;

return date.equals(other.date) && time.equals(other.time);

}

return false;

}


   Like      Feedback      java.time.LocalDateTime


 Sample 272. Code Sample / Example / Snippet of java.time.Instant

        public Instant instant() {

if ((tickNanos % 1000_000) == 0) {

long millis = baseClock.millis();

return Instant.ofEpochMilli(millis - Math.floorMod(millis, tickNanos / 1000_000L));

}

Instant instant = baseClock.instant();

long nanos = instant.getNano();

long adjust = Math.floorMod(nanos, tickNanos);

return instant.minusNanos(adjust);

}


   Like      Feedback      java.time.Instant


 Sample 273. Code Sample / Example / Snippet of java.time.ZoneOffset

public static LocalTime now(Clock clock) {

Objects.requireNonNull(clock, "clock");

final Instant now = clock.instant(); // called once

ZoneOffset offset = clock.getZone().getRules().getOffset(now);

long localSecond = now.getEpochSecond() + offset.getTotalSeconds(); // overflow caught later

int secsOfDay = (int) Math.floorMod(localSecond, SECONDS_PER_DAY);

return ofNanoOfDay(secsOfDay * NANOS_PER_SECOND + now.getNano());

}

   Like      Feedback      java.time.ZoneOffset


 Sample 274. Code Sample / Example / Snippet of java.time.ZoneId

    private void readObject(ObjectInputStream s) throws InvalidObjectException {

throw new InvalidObjectException("Deserialization via serialization delegate");

}



void writeExternal(DataOutput out) throws IOException {

dateTime.writeExternal(out);

offset.writeExternal(out);

zone.write(out);

}



static ZonedDateTime readExternal(ObjectInput in) throws IOException, ClassNotFoundException {

LocalDateTime dateTime = LocalDateTime.readExternal(in);

ZoneOffset offset = ZoneOffset.readExternal(in);

ZoneId zone = (ZoneId) Ser.read(in);

return ZonedDateTime.ofLenient(dateTime, offset, zone);

}


   Like      Feedback      java.time.ZoneId


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 275. Code Sample / Example / Snippet of java.time.ZonedDateTime

    public long until(Temporal endExclusive, TemporalUnit unit) {

ZonedDateTime end = ZonedDateTime.from(endExclusive);

if (unit instanceof ChronoUnit) {

end = end.withZoneSameInstant(zone);

if (unit.isDateBased()) {

return dateTime.until(end.dateTime, unit);

} else {

return toOffsetDateTime().until(end.toOffsetDateTime(), unit);

}

}

return unit.between(this, end);

}


   Like      Feedback      java.time.ZonedDateTime


 Sample 276. Code Sample / Example / Snippet of java.time.Year

private ZoneOffsetTransition[] findTransitionArray(int year) {

Integer yearObj = year;

ZoneOffsetTransition[] transArray = lastRulesCache.get(yearObj);

if (transArray != null) {

return transArray;

}

ZoneOffsetTransitionRule[] ruleArray = lastRules;

transArray = new ZoneOffsetTransition[ruleArray.length];

for (int i = 0; i < ruleArray.length; i++) {

transArray[i] = ruleArray[i].createTransition(year);

}

if (year < LAST_CACHED_YEAR) {

lastRulesCache.putIfAbsent(yearObj, transArray);

}

return transArray;

}

   Like      Feedback      java.time.Year


 Sample 277. Code Sample / Example / Snippet of java.time.LocalDate

    public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute) {

LocalDate date = LocalDate.of(year, month, dayOfMonth);

LocalTime time = LocalTime.of(hour, minute);

return new LocalDateTime(date, time);

}


   Like      Feedback      java.time.LocalDate


 Sample 278. Code Sample / Example / Snippet of java.time.Month

    public static LocalDate ofYearDay(int year, int dayOfYear) {

YEAR.checkValidValue(year);

DAY_OF_YEAR.checkValidValue(dayOfYear);

boolean leap = IsoChronology.INSTANCE.isLeapYear(year);

if (dayOfYear == 366 && leap == false) {

throw new DateTimeException("Invalid date 'DayOfYear 366' as '" + year + "' is not a leap year");

}

Month moy = Month.of((dayOfYear - 1) / 31 + 1);

int monthEnd = moy.firstDayOfYear(leap) + moy.length(leap) - 1;

if (dayOfYear > monthEnd) {

moy = moy.plus(1);

}

int dom = dayOfYear - moy.firstDayOfYear(leap) + 1;

return new LocalDate(year, moy.getValue(), dom);

}


   Like      Feedback      java.time.Month


 Sample 279. Code Sample / Example / Snippet of java.time.LocalTime

    public static LocalTime from(TemporalAccessor temporal) {

Objects.requireNonNull(temporal, "temporal");

LocalTime time = temporal.query(TemporalQueries.localTime());

if (time == null) {

throw new DateTimeException("Unable to obtain LocalTime from TemporalAccessor: " +

temporal + " of type " + temporal.getClass().getName());

}

return time;

}


   Like      Feedback      java.time.LocalTime


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 280. Code Sample / Example / Snippet of java.time.Period

    public Period plus(TemporalAmount amountToAdd) {

Period isoAmount = Period.from(amountToAdd);

return create(

Math.addExact(years, isoAmount.years),

Math.addExact(months, isoAmount.months),

Math.addExact(days, isoAmount.days));

}


   Like      Feedback      java.time.Period


 Sample 281. Code Sample / Example / Snippet of java.time.chrono.Chronology

        public ChronoLocalDate resolve(

Map<TemporalField, Long> fieldValues, TemporalAccessor partialTemporal, ResolverStyle resolverStyle) {

long value = fieldValues.remove(this);

Chronology chrono = Chronology.from(partialTemporal);

if (resolverStyle == ResolverStyle.LENIENT) {

return chrono.dateEpochDay(Math.subtractExact(value, offset));

}

range().checkValidValue(value, this);

return chrono.dateEpochDay(value - offset);

}


   Like      Feedback      java.time.chrono.Chronology


 Sample 282. Code Sample / Example / Snippet of java.time.temporal.ValueRange

        private int localizedWeekBasedYear(TemporalAccessor temporal) {

int dow = localizedDayOfWeek(temporal);

int year = temporal.get(YEAR);

int doy = temporal.get(DAY_OF_YEAR);

int offset = startOfWeekOffset(doy, dow);

int week = computeWeek(offset, doy);

if (week == 0) {

return year - 1;

} else {

ValueRange dayRange = temporal.range(DAY_OF_YEAR);

int yearLen = (int)dayRange.getMaximum();

int newYearWeek = computeWeek(offset, yearLen + weekDef.getMinimalDaysInFirstWeek());

if (week >= newYearWeek) {

return year + 1;

}

}

return year;

}


   Like      Feedback      java.time.temporal.ValueRange


 Sample 283. Code Sample / Example / Snippet of org.apache.spark.sql.expressions.UserDefinedAggregateFunction

  public void testUDAF() {

DataFrame df = hc.range(0, 100).unionAll(hc.range(0, 100)).select(col("id").as("value"));

UserDefinedAggregateFunction udaf = new MyDoubleSum();

UserDefinedAggregateFunction registeredUDAF = hc.udf().register("mydoublesum", udaf);

DataFrame aggregatedDF =

df.groupBy()

.agg(

udaf.distinct(col("value")),

udaf.apply(col("value")),

registeredUDAF.apply(col("value")),

callUDF("mydoublesum", col("value")));



List<Row> expectedResult = new ArrayList<>();

expectedResult.add(RowFactory.create(4950.0, 9900.0, 9900.0, 9900.0));

checkAnswer(

aggregatedDF,

expectedResult);

}


   Like      Feedback      org.apache.spark.sql.expressions.UserDefinedAggregateFunction


 Sample 284. Code Sample / Example / Snippet of org.apache.spark.SparkEnv

  public UnsafeExternalRowSorter(

StructType schema,

Ordering<InternalRow> ordering,

PrefixComparator prefixComparator,

PrefixComputer prefixComputer,

long pageSizeBytes) throws IOException {

this.schema = schema;

this.prefixComputer = prefixComputer;

final SparkEnv sparkEnv = SparkEnv.get();

final TaskContext taskContext = TaskContext.get();

sorter = UnsafeExternalSorter.create(

taskContext.taskMemoryManager(),

sparkEnv.blockManager(),

taskContext,

new RowComparator(ordering, schema.length()),

prefixComparator,

pageSizeBytes

);

}


   Like      Feedback      org.apache.spark.SparkEnv


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 285. Code Sample / Example / Snippet of org.apache.spark.TaskContext

  public UnsafeExternalRowSorter(

StructType schema,

Ordering<InternalRow> ordering,

PrefixComparator prefixComparator,

PrefixComputer prefixComputer,

long pageSizeBytes) throws IOException {

this.schema = schema;

this.prefixComputer = prefixComputer;

final SparkEnv sparkEnv = SparkEnv.get();

final TaskContext taskContext = TaskContext.get();

sorter = UnsafeExternalSorter.create(

taskContext.taskMemoryManager(),

sparkEnv.blockManager(),

taskContext,

new RowComparator(ordering, schema.length()),

prefixComparator,

pageSizeBytes

);

}


   Like      Feedback      org.apache.spark.TaskContext


 Sample 286. Code Sample / Example / Snippet of org.apache.spark.sql.catalyst.expressions.UnsafeRow

        public UnsafeRow next() {

try {

sortedIterator.loadNext();

row.pointTo(

sortedIterator.getBaseObject(),

sortedIterator.getBaseOffset(),

numFields,

sortedIterator.getRecordLength());

if (!hasNext()) {

UnsafeRow copy = row.copy(); // so that we don't have dangling pointers to freed page

row = null; // so that we don't keep references to the base object

cleanupResources();

return copy;

} else {

return row;

}

} catch (IOException e) {

cleanupResources();

Platform.throwException(e);

}

throw new RuntimeException("Exception should have been re-thrown in next()");

};


   Like      Feedback      org.apache.spark.sql.catalyst.expressions.UnsafeRow


 Sample 287. Code Sample / Example / Snippet of org.apache.spark.sql.Row

    public List<String> getD() {

return d;

}

}



void validateDataFrameWithBeans(Bean bean, DataFrame df) {

StructType schema = df.schema();

Assert.assertEquals(new StructField("a", DoubleType$.MODULE$, false, Metadata.empty()),

schema.apply("a"));

Assert.assertEquals(

new StructField("b", new ArrayType(IntegerType$.MODULE$, true), true, Metadata.empty()),

schema.apply("b"));

ArrayType valueType = new ArrayType(DataTypes.IntegerType, false);

MapType mapType = new MapType(DataTypes.StringType, valueType, true);

Assert.assertEquals(

new StructField("c", mapType, true, Metadata.empty()),

schema.apply("c"));

Assert.assertEquals(

new StructField("d", new ArrayType(DataTypes.StringType, true), true, Metadata.empty()),

schema.apply("d"));

Row first = df.select("a", "b", "c", "d").first();


   Like      Feedback      org.apache.spark.sql.Row


 Sample 288. Code Sample / Example / Snippet of org.apache.spark.sql.types.StructType

    public List<String> getD() {

return d;

}

}



void validateDataFrameWithBeans(Bean bean, DataFrame df) {

StructType schema = df.schema();


   Like      Feedback      org.apache.spark.sql.types.StructType


 Sample 289. Code Sample / Example / Snippet of org.apache.spark.sql.catalyst.expressions.UnsafeProjection

  public UnsafeFixedWidthAggregationMap(

InternalRow emptyAggregationBuffer,

StructType aggregationBufferSchema,

StructType groupingKeySchema,

TaskMemoryManager taskMemoryManager,

int initialCapacity,

long pageSizeBytes,

boolean enablePerfMetrics) {

this.aggregationBufferSchema = aggregationBufferSchema;

this.groupingKeyProjection = UnsafeProjection.create(groupingKeySchema);

this.groupingKeySchema = groupingKeySchema;

this.map =

new BytesToBytesMap(taskMemoryManager, initialCapacity, pageSizeBytes, enablePerfMetrics);

this.enablePerfMetrics = enablePerfMetrics;



final UnsafeProjection valueProjection = UnsafeProjection.create(aggregationBufferSchema);

this.emptyAggregationBuffer = valueProjection.apply(emptyAggregationBuffer).getBytes();

}


   Like      Feedback      org.apache.spark.sql.catalyst.expressions.UnsafeProjection


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 290. Code Sample / Example / Snippet of org.apache.spark.unsafe.memory.MemoryLocation

      public boolean next() {

if (mapLocationIterator.hasNext()) {

final BytesToBytesMap.Location loc = mapLocationIterator.next();

final MemoryLocation keyAddress = loc.getKeyAddress();

final MemoryLocation valueAddress = loc.getValueAddress();

key.pointTo(

keyAddress.getBaseObject(),

keyAddress.getBaseOffset(),

groupingKeySchema.length(),

loc.getKeyLength()

);

value.pointTo(

valueAddress.getBaseObject(),

valueAddress.getBaseOffset(),

aggregationBufferSchema.length(),

loc.getValueLength()

);

return true;

} else {

return false;

}

}


   Like      Feedback      org.apache.spark.unsafe.memory.MemoryLocation


 Sample 291. Code Sample / Example / Snippet of org.apache.spark.api.java.JavaDoubleRDD

  public void map() {

JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5));

JavaDoubleRDD doubles = rdd.mapToDouble(x -> 1.0 * x).cache();

doubles.collect();

JavaPairRDD<Integer, Integer> pairs = rdd.mapToPair(x -> new Tuple2<>(x, x))

.cache();

pairs.collect();

JavaRDD<String> strings = rdd.map(Object::toString).cache();

strings.collect();

}


   Like      Feedback      org.apache.spark.api.java.JavaDoubleRDD


 Sample 292. Code Sample / Example / Snippet of org.apache.spark.SparkConf

  public static void main(String[] args) throws Exception {

SparkConf sparkConf = new SparkConf().setAppName(APP_NAME);

final JavaSparkContext sc = new JavaSparkContext(sparkConf);



JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5), 5).map(

new IdentityWithDelay<Integer>());

JavaFutureAction<List<Integer>> jobFuture = rdd.collectAsync();

while (!jobFuture.isDone()) {

Thread.sleep(1000); // 1 second

List<Integer> jobIds = jobFuture.jobIds();

if (jobIds.isEmpty()) {

continue;

}

int currentJobId = jobIds.get(jobIds.size() - 1);

SparkJobInfo jobInfo = sc.statusTracker().getJobInfo(currentJobId);

SparkStageInfo stageInfo = sc.statusTracker().getStageInfo(jobInfo.stageIds()[0]);

System.out.println(stageInfo.numTasks() + " tasks total: " + stageInfo.numActiveTasks() +

" active, " + stageInfo.numCompletedTasks() + " complete");

}



System.out.println("Job results are: " + jobFuture.get());

sc.stop();

}


   Like      Feedback      org.apache.spark.SparkConf


 Sample 293. Code Sample / Example / Snippet of org.apache.spark.SparkJobInfo

  public static void main(String[] args) throws Exception {

SparkConf sparkConf = new SparkConf().setAppName(APP_NAME);

final JavaSparkContext sc = new JavaSparkContext(sparkConf);



JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5), 5).map(

new IdentityWithDelay<Integer>());

JavaFutureAction<List<Integer>> jobFuture = rdd.collectAsync();

while (!jobFuture.isDone()) {

Thread.sleep(1000); // 1 second

List<Integer> jobIds = jobFuture.jobIds();

if (jobIds.isEmpty()) {

continue;

}

int currentJobId = jobIds.get(jobIds.size() - 1);

SparkJobInfo jobInfo = sc.statusTracker().getJobInfo(currentJobId);

SparkStageInfo stageInfo = sc.statusTracker().getStageInfo(jobInfo.stageIds()[0]);

System.out.println(stageInfo.numTasks() + " tasks total: " + stageInfo.numActiveTasks() +

" active, " + stageInfo.numCompletedTasks() + " complete");

}



System.out.println("Job results are: " + jobFuture.get());

sc.stop();

}


   Like      Feedback      org.apache.spark.SparkJobInfo


 Sample 294. Code Sample / Example / Snippet of org.apache.spark.SparkStageInfo

  public static void main(String[] args) throws Exception {

SparkConf sparkConf = new SparkConf().setAppName(APP_NAME);

final JavaSparkContext sc = new JavaSparkContext(sparkConf);



JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5), 5).map(

new IdentityWithDelay<Integer>());

JavaFutureAction<List<Integer>> jobFuture = rdd.collectAsync();

while (!jobFuture.isDone()) {

Thread.sleep(1000); // 1 second

List<Integer> jobIds = jobFuture.jobIds();

if (jobIds.isEmpty()) {

continue;

}

int currentJobId = jobIds.get(jobIds.size() - 1);

SparkJobInfo jobInfo = sc.statusTracker().getJobInfo(currentJobId);

SparkStageInfo stageInfo = sc.statusTracker().getStageInfo(jobInfo.stageIds()[0]);

System.out.println(stageInfo.numTasks() + " tasks total: " + stageInfo.numActiveTasks() +

" active, " + stageInfo.numCompletedTasks() + " complete");

}



System.out.println("Job results are: " + jobFuture.get());

sc.stop();

}


   Like      Feedback      org.apache.spark.SparkStageInfo


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 295. Code Sample / Example / Snippet of org.apache.spark.sql.SQLContext

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaDCTExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



JavaRDD<Row> data = jsc.parallelize(Arrays.asList(

RowFactory.create(Vectors.dense(0.0, 1.0, -2.0, 3.0)),

RowFactory.create(Vectors.dense(-1.0, 2.0, 4.0, -7.0)),

RowFactory.create(Vectors.dense(14.0, -2.0, -5.0, 1.0))

));

StructType schema = new StructType(new StructField[]{

new StructField("features", new VectorUDT(), false, Metadata.empty()),

});

DataFrame df = jsql.createDataFrame(data, schema);

DCT dct = new DCT()

.setInputCol("features")

.setOutputCol("featuresDCT")

.setInverse(false);

DataFrame dctDf = dct.transform(df);

dctDf.select("featuresDCT").show(3);

jsc.stop();

}


   Like      Feedback      org.apache.spark.sql.SQLContext


 Sample 296. Code Sample / Example / Snippet of org.apache.spark.ml.feature.DCT

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaDCTExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



JavaRDD<Row> data = jsc.parallelize(Arrays.asList(

RowFactory.create(Vectors.dense(0.0, 1.0, -2.0, 3.0)),

RowFactory.create(Vectors.dense(-1.0, 2.0, 4.0, -7.0)),

RowFactory.create(Vectors.dense(14.0, -2.0, -5.0, 1.0))

));

StructType schema = new StructType(new StructField[]{

new StructField("features", new VectorUDT(), false, Metadata.empty()),

});

DataFrame df = jsql.createDataFrame(data, schema);

DCT dct = new DCT()

.setInputCol("features")

.setOutputCol("featuresDCT")

.setInverse(false);

DataFrame dctDf = dct.transform(df);

dctDf.select("featuresDCT").show(3);

jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.feature.DCT


 Sample 297. Code Sample / Example / Snippet of org.apache.spark.ml.feature.StopWordsRemover

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaStopWordsRemoverExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



StopWordsRemover remover = new StopWordsRemover()

.setInputCol("raw")

.setOutputCol("filtered");



JavaRDD<Row> rdd = jsc.parallelize(Arrays.asList(

RowFactory.create(Arrays.asList("I", "saw", "the", "red", "baloon")),

RowFactory.create(Arrays.asList("Mary", "had", "a", "little", "lamb"))

));



StructType schema = new StructType(new StructField[]{

new StructField(

"raw", DataTypes.createArrayType(DataTypes.StringType), false, Metadata.empty())

});



DataFrame dataset = jsql.createDataFrame(rdd, schema);

remover.transform(dataset).show();

jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.feature.StopWordsRemover


 Sample 298. Code Sample / Example / Snippet of org.apache.spark.ml.param.IntParam

  public String uid() {

return uid_;

}



IntParam maxIter = new IntParam(this, "maxIter", "max number of iterations");


   Like      Feedback      org.apache.spark.ml.param.IntParam


 Sample 299. Code Sample / Example / Snippet of org.apache.spark.mllib.linalg.Vector

  public MyJavaLogisticRegressionModel train(DataFrame dataset) {

JavaRDD<LabeledPoint> oldDataset = extractLabeledPoints(dataset).toJavaRDD();



int numFeatures = oldDataset.take(1).get(0).features().size();

Vector weights = Vectors.zeros(numFeatures); // Learning would happen here.



return new MyJavaLogisticRegressionModel(uid(), weights).setParent(this);

}


   Like      Feedback      org.apache.spark.mllib.linalg.Vector


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 300. Code Sample / Example / Snippet of org.apache.spark.ml.feature.StandardScaler

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaStandardScalerExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");



StandardScaler scaler = new StandardScaler()

.setInputCol("features")

.setOutputCol("scaledFeatures")

.setWithStd(true)

.setWithMean(false);



StandardScalerModel scalerModel = scaler.fit(dataFrame);



DataFrame scaledData = scalerModel.transform(dataFrame);

scaledData.show();

jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.feature.StandardScaler


 Sample 301. Code Sample / Example / Snippet of org.apache.spark.ml.feature.StandardScalerModel

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaStandardScalerExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");



StandardScaler scaler = new StandardScaler()

.setInputCol("features")

.setOutputCol("scaledFeatures")

.setWithStd(true)

.setWithMean(false);



StandardScalerModel scalerModel = scaler.fit(dataFrame);



DataFrame scaledData = scalerModel.transform(dataFrame);

scaledData.show();

jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.feature.StandardScalerModel


 Sample 302. Code Sample / Example / Snippet of org.apache.spark.ml.feature.Normalizer

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaNormalizerExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");



Normalizer normalizer = new Normalizer()

.setInputCol("features")

.setOutputCol("normFeatures")

.setP(1.0);



DataFrame l1NormData = normalizer.transform(dataFrame);

l1NormData.show();



DataFrame lInfNormData =

normalizer.transform(dataFrame, normalizer.p().w(Double.POSITIVE_INFINITY));

lInfNormData.show();

jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.feature.Normalizer


 Sample 303. Code Sample / Example / Snippet of org.apache.spark.ml.classification.LogisticRegression

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaLogisticRegressionWithElasticNetExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext sqlContext = new SQLContext(jsc);



DataFrame training = sqlContext.read().format("libsvm")

.load("data/mllib/sample_libsvm_data.txt");



LogisticRegression lr = new LogisticRegression()

.setMaxIter(10)

.setRegParam(0.3)

.setElasticNetParam(0.8);



LogisticRegressionModel lrModel = lr.fit(training);



System.out.println("Coefficients: "

+ lrModel.coefficients() + " Intercept: " + lrModel.intercept());



jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.classification.LogisticRegression


 Sample 304. Code Sample / Example / Snippet of org.apache.spark.ml.classification.LogisticRegressionModel

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaLogisticRegressionWithElasticNetExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext sqlContext = new SQLContext(jsc);



DataFrame training = sqlContext.read().format("libsvm")

.load("data/mllib/sample_libsvm_data.txt");



LogisticRegression lr = new LogisticRegression()

.setMaxIter(10)

.setRegParam(0.3)

.setElasticNetParam(0.8);



LogisticRegressionModel lrModel = lr.fit(training);



System.out.println("Coefficients: "

+ lrModel.coefficients() + " Intercept: " + lrModel.intercept());



jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.classification.LogisticRegressionModel


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 305. Code Sample / Example / Snippet of org.apache.spark.ml.feature.SQLTransformer

  public static void main(String[] args) {



SparkConf conf = new SparkConf().setAppName("JavaSQLTransformerExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext sqlContext = new SQLContext(jsc);



JavaRDD<Row> jrdd = jsc.parallelize(Arrays.asList(

RowFactory.create(0, 1.0, 3.0),

RowFactory.create(2, 2.0, 5.0)

));

StructType schema = new StructType(new StructField [] {

new StructField("id", DataTypes.IntegerType, false, Metadata.empty()),

new StructField("v1", DataTypes.DoubleType, false, Metadata.empty()),

new StructField("v2", DataTypes.DoubleType, false, Metadata.empty())

});

DataFrame df = sqlContext.createDataFrame(jrdd, schema);



SQLTransformer sqlTrans = new SQLTransformer().setStatement(

"SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__");



sqlTrans.transform(df).show();

}


   Like      Feedback      org.apache.spark.ml.feature.SQLTransformer


 Sample 306. Code Sample / Example / Snippet of org.apache.spark.ml.feature.MinMaxScalerModel

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JaveMinMaxScalerExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");

MinMaxScaler scaler = new MinMaxScaler()

.setInputCol("features")

.setOutputCol("scaledFeatures");



MinMaxScalerModel scalerModel = scaler.fit(dataFrame);



DataFrame scaledData = scalerModel.transform(dataFrame);

scaledData.show();

jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.feature.MinMaxScalerModel


 Sample 307. Code Sample / Example / Snippet of org.apache.spark.ml.feature.MinMaxScaler

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JaveMinMaxScalerExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");

MinMaxScaler scaler = new MinMaxScaler()

.setInputCol("features")

.setOutputCol("scaledFeatures");



MinMaxScalerModel scalerModel = scaler.fit(dataFrame);



DataFrame scaledData = scalerModel.transform(dataFrame);

scaledData.show();

jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.feature.MinMaxScaler


 Sample 308. Code Sample / Example / Snippet of org.apache.spark.mllib.classification.LogisticRegressionModel

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaLogisticRegressionWithElasticNetExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext sqlContext = new SQLContext(jsc);



DataFrame training = sqlContext.read().format("libsvm")

.load("data/mllib/sample_libsvm_data.txt");



LogisticRegression lr = new LogisticRegression()

.setMaxIter(10)

.setRegParam(0.3)

.setElasticNetParam(0.8);



LogisticRegressionModel lrModel = lr.fit(training);



System.out.println("Coefficients: "

+ lrModel.coefficients() + " Intercept: " + lrModel.intercept());



jsc.stop();

}


   Like      Feedback      org.apache.spark.mllib.classification.LogisticRegressionModel


 Sample 309. Code Sample / Example / Snippet of org.apache.storm.task.OutputCollector

  public void shouldEmitNothingIfNoObjectHasBeenCountedYetAndTickTupleIsReceived() {

Tuple tickTuple = MockTupleHelpers.mockTickTuple();

RollingCountBolt bolt = new RollingCountBolt();

Map conf = mock(Map.class);

TopologyContext context = mock(TopologyContext.class);

OutputCollector collector = mock(OutputCollector.class);

bolt.prepare(conf, context, collector);



bolt.execute(tickTuple);



verifyZeroInteractions(collector);

}


   Like      Feedback      org.apache.storm.task.OutputCollector


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 310. Code Sample / Example / Snippet of org.apache.spark.mllib.clustering.DistributedLDAModel

DistributedLDAModel ldaModel = (DistributedLDAModel)new LDA().setK(3).run(corpus);    
System.out.println("Learned topics (as distributions over vocab of " + ldaModel.vocabSize() + " words):");
Matrix topics = ldaModel.topicsMatrix(); for (int topic = 0; topic < 3; topic++) {

   Like      Feedback      org.apache.spark.mllib.clustering.DistributedLDAModel


 Sample 311. Code Sample / Example / Snippet of org.apache.storm.task.TopologyContext

  public void shouldEmitNothingIfNoObjectHasBeenCountedYetAndTickTupleIsReceived() {

Tuple tickTuple = MockTupleHelpers.mockTickTuple();

RollingCountBolt bolt = new RollingCountBolt();

Map conf = mock(Map.class);

TopologyContext context = mock(TopologyContext.class);

OutputCollector collector = mock(OutputCollector.class);

bolt.prepare(conf, context, collector);



bolt.execute(tickTuple);



verifyZeroInteractions(collector);

}


   Like      Feedback      org.apache.storm.task.TopologyContext


 Sample 312. Code Sample / Example / Snippet of org.apache.spark.mllib.fpm.AssociationRules

  public static void main(String[] args) {



SparkConf sparkConf = new SparkConf().setAppName("JavaAssociationRulesExample");

JavaSparkContext sc = new JavaSparkContext(sparkConf);



JavaRDD<FPGrowth.FreqItemset<String>> freqItemsets = sc.parallelize(Arrays.asList(

new FreqItemset<String>(new String[] {"a"}, 15L),

new FreqItemset<String>(new String[] {"b"}, 35L),

new FreqItemset<String>(new String[] {"a", "b"}, 12L)

));



AssociationRules arules = new AssociationRules()

.setMinConfidence(0.8);

JavaRDD<AssociationRules.Rule<String>> results = arules.run(freqItemsets);



for (AssociationRules.Rule<String> rule : results.collect()) {

System.out.println(

rule.javaAntecedent() + " => " + rule.javaConsequent() + ", " + rule.confidence());

}

}


   Like      Feedback      org.apache.spark.mllib.fpm.AssociationRules


 Sample 313. Code Sample / Example / Snippet of org.apache.spark.mllib.regression.IsotonicRegressionModel

        public Tuple3<Double, Double, Double> call(String line) {

String[] parts = line.split(",");

return new Tuple3<>(new Double(parts[0]), new Double(parts[1]), 1.0);

}

}

);



JavaRDD<Tuple3<Double, Double, Double>>[] splits = parsedData.randomSplit(new double[]{0.6, 0.4}, 11L);

JavaRDD<Tuple3<Double, Double, Double>> training = splits[0];

JavaRDD<Tuple3<Double, Double, Double>> test = splits[1];



final IsotonicRegressionModel model = new IsotonicRegression().setIsotonic(true).run(training);



JavaPairRDD<Double, Double> predictionAndLabel = test.mapToPair(

new PairFunction<Tuple3<Double, Double, Double>, Double, Double>() {


   Like      Feedback      org.apache.spark.mllib.regression.IsotonicRegressionModel


 Sample 314. Code Sample / Example / Snippet of org.apache.spark.mllib.fpm.PrefixSpan

  public static void main(String[] args) {



SparkConf sparkConf = new SparkConf().setAppName("JavaPrefixSpanExample");

JavaSparkContext sc = new JavaSparkContext(sparkConf);



JavaRDD<List<List<Integer>>> sequences = sc.parallelize(Arrays.asList(

Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3)),

Arrays.asList(Arrays.asList(1), Arrays.asList(3, 2), Arrays.asList(1, 2)),

Arrays.asList(Arrays.asList(1, 2), Arrays.asList(5)),

Arrays.asList(Arrays.asList(6))

), 2);

PrefixSpan prefixSpan = new PrefixSpan()

.setMinSupport(0.5)

.setMaxPatternLength(5);

PrefixSpanModel<Integer> model = prefixSpan.run(sequences);

for (PrefixSpan.FreqSequence<Integer> freqSeq: model.freqSequences().toJavaRDD().collect()) {

System.out.println(freqSeq.javaSequence() + ", " + freqSeq.freq());

}

}


   Like      Feedback      org.apache.spark.mllib.fpm.PrefixSpan


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 315. Code Sample / Example / Snippet of org.apache.spark.mllib.clustering.PowerIterationClustering

  public static void main(String[] args) {

SparkConf sparkConf = new SparkConf().setAppName("JavaPowerIterationClusteringExample");

JavaSparkContext sc = new JavaSparkContext(sparkConf);



@SuppressWarnings("unchecked")

JavaRDD<Tuple3<Long, Long, Double>> similarities = sc.parallelize(Lists.newArrayList(

new Tuple3<Long, Long, Double>(0L, 1L, 0.9),

new Tuple3<Long, Long, Double>(1L, 2L, 0.9),

new Tuple3<Long, Long, Double>(2L, 3L, 0.9),

new Tuple3<Long, Long, Double>(3L, 4L, 0.1),

new Tuple3<Long, Long, Double>(4L, 5L, 0.9)));



PowerIterationClustering pic = new PowerIterationClustering()

.setK(2)

.setMaxIterations(10);

PowerIterationClusteringModel model = pic.run(similarities);



for (PowerIterationClustering.Assignment a: model.assignments().toJavaRDD().collect()) {

System.out.println(a.id() + " -> " + a.cluster());

}



sc.stop();

}


   Like      Feedback      org.apache.spark.mllib.clustering.PowerIterationClustering


 Sample 316. Code Sample / Example / Snippet of org.apache.spark.mllib.clustering.PowerIterationClusteringModel

  public static void main(String[] args) {

SparkConf sparkConf = new SparkConf().setAppName("JavaPowerIterationClusteringExample");

JavaSparkContext sc = new JavaSparkContext(sparkConf);



@SuppressWarnings("unchecked")

JavaRDD<Tuple3<Long, Long, Double>> similarities = sc.parallelize(Lists.newArrayList(

new Tuple3<Long, Long, Double>(0L, 1L, 0.9),

new Tuple3<Long, Long, Double>(1L, 2L, 0.9),

new Tuple3<Long, Long, Double>(2L, 3L, 0.9),

new Tuple3<Long, Long, Double>(3L, 4L, 0.1),

new Tuple3<Long, Long, Double>(4L, 5L, 0.9)));



PowerIterationClustering pic = new PowerIterationClustering()

.setK(2)

.setMaxIterations(10);

PowerIterationClusteringModel model = pic.run(similarities);



for (PowerIterationClustering.Assignment a: model.assignments().toJavaRDD().collect()) {

System.out.println(a.id() + " -> " + a.cluster());

}



sc.stop();

}


   Like      Feedback      org.apache.spark.mllib.clustering.PowerIterationClusteringModel


 Sample 317. Code Sample / Example / Snippet of org.apache.spark.mllib.stat.test.StreamingTest

  public void streamingTest() {

List<BinarySample> trainingBatch = Arrays.asList(

new BinarySample(true, 1.0),

new BinarySample(false, 2.0));

JavaDStream<BinarySample> training =

attachTestInputStream(ssc, Arrays.asList(trainingBatch, trainingBatch), 2);

int numBatches = 2;

StreamingTest model = new StreamingTest()

.setWindowSize(0)

.setPeacePeriod(0)

.setTestMethod("welch");

model.registerStream(training);

attachTestOutputStream(training);

runStreams(ssc, numBatches, numBatches);

}


   Like      Feedback      org.apache.spark.mllib.stat.test.StreamingTest


 Sample 318. Code Sample / Example / Snippet of org.apache.spark.network.server.TransportServerBootstrap

  public void beforeEach() throws IOException {

TransportContext context =

new TransportContext(conf, new ExternalShuffleBlockHandler(conf, null));

TransportServerBootstrap bootstrap = new SaslServerBootstrap(conf,

new TestSecretKeyHolder("my-app-id", "secret"));

this.server = context.createServer(Arrays.asList(bootstrap));

}


   Like      Feedback      org.apache.spark.network.server.TransportServerBootstrap


 Sample 319. Code Sample / Example / Snippet of org.apache.spark.network.TransportContext

  public void beforeEach() throws IOException {

TransportContext context =

new TransportContext(conf, new ExternalShuffleBlockHandler(conf, null));

TransportServerBootstrap bootstrap = new SaslServerBootstrap(conf,

new TestSecretKeyHolder("my-app-id", "secret"));

this.server = context.createServer(Arrays.asList(bootstrap));

}


   Like      Feedback      org.apache.spark.network.TransportContext


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 320. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.ExternalShuffleBlockResolver.AppExecId

  public void jsonSerializationOfExecutorRegistration() throws IOException {

ObjectMapper mapper = new ObjectMapper();

AppExecId appId = new AppExecId("foo", "bar");

String appIdJson = mapper.writeValueAsString(appId);

AppExecId parsedAppId = mapper.readValue(appIdJson, AppExecId.class);

assertEquals(parsedAppId, appId);



ExecutorShuffleInfo shuffleInfo =

new ExecutorShuffleInfo(new String[]{"/bippy", "/flippy"}, 7, "hash");

String shuffleJson = mapper.writeValueAsString(shuffleInfo);

ExecutorShuffleInfo parsedShuffleInfo =

mapper.readValue(shuffleJson, ExecutorShuffleInfo.class);

assertEquals(parsedShuffleInfo, shuffleInfo);



String legacyAppIdJson = "{"appId":"foo", "execId":"bar"}";

assertEquals(appId, mapper.readValue(legacyAppIdJson, AppExecId.class));

String legacyShuffleJson = "{"localDirs": ["/bippy", "/flippy"], " +

""subDirsPerLocalDir": 7, "shuffleManager": "hash"}";

assertEquals(shuffleInfo, mapper.readValue(legacyShuffleJson, ExecutorShuffleInfo.class));

}


   Like      Feedback      org.apache.spark.network.shuffle.ExternalShuffleBlockResolver.AppExecId


 Sample 321. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.protocol.ExecutorShuffleInfo

  public void jsonSerializationOfExecutorRegistration() throws IOException {

ObjectMapper mapper = new ObjectMapper();

AppExecId appId = new AppExecId("foo", "bar");

String appIdJson = mapper.writeValueAsString(appId);

AppExecId parsedAppId = mapper.readValue(appIdJson, AppExecId.class);

assertEquals(parsedAppId, appId);



ExecutorShuffleInfo shuffleInfo =

new ExecutorShuffleInfo(new String[]{"/bippy", "/flippy"}, 7, "hash");

String shuffleJson = mapper.writeValueAsString(shuffleInfo);

ExecutorShuffleInfo parsedShuffleInfo =

mapper.readValue(shuffleJson, ExecutorShuffleInfo.class);

assertEquals(parsedShuffleInfo, shuffleInfo);



String legacyAppIdJson = "{"appId":"foo", "execId":"bar"}";

assertEquals(appId, mapper.readValue(legacyAppIdJson, AppExecId.class));

String legacyShuffleJson = "{"localDirs": ["/bippy", "/flippy"], " +

""subDirsPerLocalDir": 7, "shuffleManager": "hash"}";

assertEquals(shuffleInfo, mapper.readValue(legacyShuffleJson, ExecutorShuffleInfo.class));

}


   Like      Feedback      org.apache.spark.network.shuffle.protocol.ExecutorShuffleInfo


 Sample 322. Code Sample / Example / Snippet of org.apache.spark.network.server.RpcHandler

  public void testNoSaslServer() {

RpcHandler handler = new TestRpcHandler();

TransportContext context = new TransportContext(conf, handler);

clientFactory = context.createClientFactory(

Lists.<TransportClientBootstrap>newArrayList(

new SaslClientBootstrap(conf, "app-1", secretKeyHolder)));

TransportServer server = context.createServer();

try {

clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());

} catch (Exception e) {

assertTrue(e.getMessage(), e.getMessage().contains("Digest-challenge format violation"));

} finally {

server.close();

}

}


   Like      Feedback      org.apache.spark.network.server.RpcHandler


 Sample 323. Code Sample / Example / Snippet of org.apache.spark.network.server.TransportServer

  public void testNoSaslServer() {

RpcHandler handler = new TestRpcHandler();

TransportContext context = new TransportContext(conf, handler);

clientFactory = context.createClientFactory(

Lists.<TransportClientBootstrap>newArrayList(

new SaslClientBootstrap(conf, "app-1", secretKeyHolder)));

TransportServer server = context.createServer();

try {

clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());

} catch (Exception e) {

assertTrue(e.getMessage(), e.getMessage().contains("Digest-challenge format violation"));

} finally {

server.close();

}

}


   Like      Feedback      org.apache.spark.network.server.TransportServer


 Sample 324. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.BlockFetchingListener

  public void testNoFailures() throws IOException {

BlockFetchingListener listener = mock(BlockFetchingListener.class);



List<? extends Map<String, Object>> interactions = Arrays.asList(

ImmutableMap.<String, Object>builder()

.put("b0", block0)

.put("b1", block1)

.build()

);



performInteractions(interactions, listener);



verify(listener).onBlockFetchSuccess("b0", block0);

verify(listener).onBlockFetchSuccess("b1", block1);

verifyNoMoreInteractions(listener);

}


   Like      Feedback      org.apache.spark.network.shuffle.BlockFetchingListener


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 325. Code Sample / Example / Snippet of org.apache.spark.network.client.TransportClient

  public void testGoodClient() throws IOException {

clientFactory = context.createClientFactory(

Lists.<TransportClientBootstrap>newArrayList(

new SaslClientBootstrap(conf, "app-1", secretKeyHolder)));



TransportClient client = clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());

String msg = "Hello, World!";

ByteBuffer resp = client.sendRpcSync(JavaUtils.stringToBytes(msg), TIMEOUT_MS);

assertEquals(msg, JavaUtils.bytesToString(resp));

}


   Like      Feedback      org.apache.spark.network.client.TransportClient


 Sample 326. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.ExternalShuffleBlockResolver

  public void noCleanupAndCleanup() throws IOException {

TestShuffleDataContext dataContext = createSomeData();



ExternalShuffleBlockResolver resolver =

new ExternalShuffleBlockResolver(conf, null, sameThreadExecutor);

resolver.registerExecutor("app", "exec0", dataContext.createExecutorInfo("shuffleMgr"));

resolver.applicationRemoved("app", false /* cleanup */);



assertStillThere(dataContext);



resolver.registerExecutor("app", "exec1", dataContext.createExecutorInfo("shuffleMgr"));

resolver.applicationRemoved("app", true /* cleanup */);



assertCleanedUp(dataContext);

}


   Like      Feedback      org.apache.spark.network.shuffle.ExternalShuffleBlockResolver


 Sample 327. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.ExternalShuffleClient

  private void validate(String appId, String secretKey, boolean encrypt) throws IOException {

ExternalShuffleClient client =

new ExternalShuffleClient(conf, new TestSecretKeyHolder(appId, secretKey), true, encrypt);

client.init(appId);

client.registerWithShuffleServer(TestUtils.getLocalHost(), server.getPort(), "exec0",

new ExecutorShuffleInfo(new String[0], 0, ""));

client.close();

}


   Like      Feedback      org.apache.spark.network.shuffle.ExternalShuffleClient


 Sample 328. Code Sample / Example / Snippet of org.apache.spark.network.protocol.StreamChunkId

  public void handleSuccessfulFetch() throws Exception {

StreamChunkId streamChunkId = new StreamChunkId(1, 0);



TransportResponseHandler handler = new TransportResponseHandler(new LocalChannel());

ChunkReceivedCallback callback = mock(ChunkReceivedCallback.class);

handler.addFetchRequest(streamChunkId, callback);

assertEquals(1, handler.numOutstandingRequests());



handler.handle(new ChunkFetchSuccess(streamChunkId, new TestManagedBuffer(123)));

verify(callback, times(1)).onSuccess(eq(0), (ManagedBuffer) any());

assertEquals(0, handler.numOutstandingRequests());

}


   Like      Feedback      org.apache.spark.network.protocol.StreamChunkId


 Sample 329. Code Sample / Example / Snippet of org.apache.spark.network.client.TransportResponseHandler

  public void handleSuccessfulFetch() throws Exception {

StreamChunkId streamChunkId = new StreamChunkId(1, 0);



TransportResponseHandler handler = new TransportResponseHandler(new LocalChannel());

ChunkReceivedCallback callback = mock(ChunkReceivedCallback.class);

handler.addFetchRequest(streamChunkId, callback);

assertEquals(1, handler.numOutstandingRequests());



handler.handle(new ChunkFetchSuccess(streamChunkId, new TestManagedBuffer(123)));

verify(callback, times(1)).onSuccess(eq(0), (ManagedBuffer) any());

assertEquals(0, handler.numOutstandingRequests());

}


   Like      Feedback      org.apache.spark.network.client.TransportResponseHandler


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 330. Code Sample / Example / Snippet of org.apache.storm.topology.BasicOutputCollector

  public void shouldEmitSomethingIfTickTupleIsReceived() {

Tuple tickTuple = MockTupleHelpers.mockTickTuple();

BasicOutputCollector collector = mock(BasicOutputCollector.class);

TotalRankingsBolt bolt = new TotalRankingsBolt();



bolt.execute(tickTuple, collector);



verify(collector).emit(any(Values.class));

}


   Like      Feedback      org.apache.storm.topology.BasicOutputCollector


 Sample 331. Code Sample / Example / Snippet of org.apache.storm.starter.tools.Rankings

  public void copyConstructorShouldReturnCopy(int topN, List<Rankable> rankables) {

Rankings rankings = new Rankings(topN);

for (Rankable r : rankables) {

rankings.updateWith(r);

}



Rankings copy = new Rankings(rankings);



assertThat(copy.maxSize()).isEqualTo(rankings.maxSize());

assertThat(copy.getRankings()).isEqualTo(rankings.getRankings());

}


   Like      Feedback      org.apache.storm.starter.tools.Rankings


 Sample 332. Code Sample / Example / Snippet of org.apache.storm.tuple.Tuple

  public void shouldEmitSomethingIfTickTupleIsReceived() {

Tuple tickTuple = MockTupleHelpers.mockTickTuple();

BasicOutputCollector collector = mock(BasicOutputCollector.class);

TotalRankingsBolt bolt = new TotalRankingsBolt();



bolt.execute(tickTuple, collector);



verify(collector).emit(any(Values.class));

}


   Like      Feedback      org.apache.storm.tuple.Tuple


 Sample 333. Code Sample / Example / Snippet of org.apache.storm.Config

    public static void main(String[] args) throws Exception {

TopologyBuilder builder = new TopologyBuilder();

builder.setSpout("spout", new RandomIntegerSpout());

builder.setBolt("sumbolt", new WindowSumBolt().withWindow(new Count(5), new Count(3))

.withMessageIdField("msgid"), 1).shuffleGrouping("spout");

builder.setBolt("printer", new PrinterBolt(), 1).shuffleGrouping("sumbolt");

Config conf = new Config();

conf.setDebug(false);

if (args != null && args.length > 0) {

conf.setNumWorkers(1);

StormSubmitter.submitTopologyWithProgressBar(args[0], conf, builder.createTopology());

} else {

LocalCluster cluster = new LocalCluster();

StormTopology topology = builder.createTopology();

cluster.submitTopology("test", conf, topology);

Utils.sleep(40000);

cluster.killTopology("test");

cluster.shutdown();

}

}


   Like      Feedback      org.apache.storm.Config


 Sample 334. Code Sample / Example / Snippet of org.apache.storm.topology.TopologyBuilder

    public static void main(String[] args) throws Exception {

TopologyBuilder builder = new TopologyBuilder();

builder.setSpout("spout", new RandomIntegerSpout());

builder.setBolt("sumbolt", new WindowSumBolt().withWindow(new Count(5), new Count(3))

.withMessageIdField("msgid"), 1).shuffleGrouping("spout");

builder.setBolt("printer", new PrinterBolt(), 1).shuffleGrouping("sumbolt");

Config conf = new Config();

conf.setDebug(false);

if (args != null && args.length > 0) {

conf.setNumWorkers(1);

StormSubmitter.submitTopologyWithProgressBar(args[0], conf, builder.createTopology());

} else {

LocalCluster cluster = new LocalCluster();

StormTopology topology = builder.createTopology();

cluster.submitTopology("test", conf, topology);

Utils.sleep(40000);

cluster.killTopology("test");

cluster.shutdown();

}

}


   Like      Feedback      org.apache.storm.topology.TopologyBuilder


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 335. Code Sample / Example / Snippet of org.apache.storm.LocalCluster

    public static void main(String[] args) throws Exception {

TopologyBuilder builder = new TopologyBuilder();

builder.setSpout("spout", new RandomIntegerSpout());

builder.setBolt("sumbolt", new WindowSumBolt().withWindow(new Count(5), new Count(3))

.withMessageIdField("msgid"), 1).shuffleGrouping("spout");

builder.setBolt("printer", new PrinterBolt(), 1).shuffleGrouping("sumbolt");

Config conf = new Config();

conf.setDebug(false);

if (args != null && args.length > 0) {

conf.setNumWorkers(1);

StormSubmitter.submitTopologyWithProgressBar(args[0], conf, builder.createTopology());

} else {

LocalCluster cluster = new LocalCluster();

StormTopology topology = builder.createTopology();

cluster.submitTopology("test", conf, topology);

Utils.sleep(40000);

cluster.killTopology("test");

cluster.shutdown();

}

}


   Like      Feedback      org.apache.storm.LocalCluster


 Sample 336. Code Sample / Example / Snippet of org.apache.storm.testing.MemoryTransactionalSpout

  public static void main(String[] args) throws Exception {

MemoryTransactionalSpout spout = new MemoryTransactionalSpout(DATA, new Fields("word"), PARTITION_TAKE_PER_BATCH);

TransactionalTopologyBuilder builder = new TransactionalTopologyBuilder("global-count", "spout", spout, 3);

builder.setBolt("partial-count", new BatchCount(), 5).noneGrouping("spout");

builder.setBolt("sum", new UpdateGlobalCount()).globalGrouping("partial-count");



LocalCluster cluster = new LocalCluster();



Config config = new Config();

config.setDebug(true);

config.setMaxSpoutPending(3);



cluster.submitTopology("global-count-topology", config, builder.buildTopology());



Thread.sleep(3000);

cluster.shutdown();

}


   Like      Feedback      org.apache.storm.testing.MemoryTransactionalSpout


 Sample 337. Code Sample / Example / Snippet of org.apache.storm.transactional.TransactionalTopologyBuilder

  public static void main(String[] args) throws Exception {

MemoryTransactionalSpout spout = new MemoryTransactionalSpout(DATA, new Fields("word"), PARTITION_TAKE_PER_BATCH);

TransactionalTopologyBuilder builder = new TransactionalTopologyBuilder("global-count", "spout", spout, 3);

builder.setBolt("partial-count", new BatchCount(), 5).noneGrouping("spout");

builder.setBolt("sum", new UpdateGlobalCount()).globalGrouping("partial-count");



LocalCluster cluster = new LocalCluster();



Config config = new Config();

config.setDebug(true);

config.setMaxSpoutPending(3);



cluster.submitTopology("global-count-topology", config, builder.buildTopology());



Thread.sleep(3000);

cluster.shutdown();

}


   Like      Feedback      org.apache.storm.transactional.TransactionalTopologyBuilder


 Sample 338. Code Sample / Example / Snippet of org.apache.storm.trident.windowing.WindowsStoreFactory

    public static void main(String[] args) throws Exception {

Config conf = new Config();

WindowsStoreFactory mapState = new InMemoryWindowsStoreFactory();



if (args.length == 0) {

List<? extends WindowConfig> list = Arrays.asList(

SlidingCountWindow.of(1000, 100)

,TumblingCountWindow.of(1000)

,SlidingDurationWindow.of(new BaseWindowedBolt.Duration(6, TimeUnit.SECONDS), new BaseWindowedBolt.Duration(3, TimeUnit.SECONDS))

,TumblingDurationWindow.of(new BaseWindowedBolt.Duration(3, TimeUnit.SECONDS))

);



for (WindowConfig windowConfig : list) {

LocalCluster cluster = new LocalCluster();

cluster.submitTopology("wordCounter", conf, buildTopology(mapState, windowConfig));

Utils.sleep(60 * 1000);

cluster.shutdown();

}

System.exit(0);

} else {

conf.setNumWorkers(3);

StormSubmitter.submitTopologyWithProgressBar(args[0], conf, buildTopology(mapState, SlidingCountWindow.of(1000, 100)));

}

}


   Like      Feedback      org.apache.storm.trident.windowing.WindowsStoreFactory


 Sample 339. Code Sample / Example / Snippet of org.apache.storm.trident.Stream

    public static StormTopology buildTopology(WindowsStoreFactory windowStore, WindowConfig windowConfig) throws Exception {

FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 3, new Values("the cow jumped over the moon"),

new Values("the man went to the store and bought some candy"), new Values("four score and seven years ago"),

new Values("how many apples can you eat"), new Values("to be or not to be the person"));

spout.setCycle(true);



TridentTopology topology = new TridentTopology();



Stream stream = topology.newStream("spout1", spout).parallelismHint(16).each(new Fields("sentence"),

new Split(), new Fields("word"))

.window(windowConfig, windowStore, new Fields("word"), new CountAsAggregator(), new Fields("count"))

.peek(new Consumer() {

@Override

public void accept(TridentTuple input) {

LOG.info("Received tuple: [{}]", input);

}

});



return topology.build();

}


   Like      Feedback      org.apache.storm.trident.Stream