Search Java Code Snippets


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





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

 Sample 1. Code Sample / Example / Snippet of org.apache.ace.agent.AgentContext

    protected final AgentContext getAgentContext() {

AgentContext context = m_contextRef.get();

if (context == null) {

throw new IllegalStateException("Handler is not started: " + m_identifier);

}

return context;

}


   Like      Feedback      org.apache.ace.agent.AgentContext


 Sample 2. Update Google Adwords Bids for a particular keyword using Keyword Id

Usage of

import com.google.api.ads.adwords.axis.v201802.cm.AdGroupCriterion;
import com.google.api.ads.adwords.axis.v201802.cm.AdGroupCriterionOperation;
import com.google.api.ads.adwords.axis.v201802.cm.AdGroupCriterionReturnValue;
import com.google.api.ads.adwords.axis.v201802.cm.AdGroupCriterionServiceInterface;
import com.google.api.ads.adwords.axis.v201802.cm.BiddableAdGroupCriterion;
import com.google.api.ads.adwords.axis.v201802.cm.BiddingStrategyConfiguration;
import com.google.api.ads.adwords.axis.v201802.cm.Bids;
import com.google.api.ads.adwords.axis.v201802.cm.CampaignCriterionServiceInterface;
import com.google.api.ads.adwords.axis.v201802.cm.CpcBid;
import com.google.api.ads.adwords.axis.v201802.cm.Keyword;
import com.google.api.ads.adwords.axis.v201802.cm.Money;

public void updateBidForKeyword(Long adGroupId, Long keywordId, Long bidAmount) {
      
AdWordsSession adwordSession = null;

// initialize AdWords session

try {
            // Generate a refreshable OAuth2 credential
            Credential oAuth2Credential = new OfflineCredentials.Builder().forApi(Api.ADWORDS)
                  .fromFile().build()
                  .generateCredential();

            // Construct an AdWordsSession.
            adwordSession = new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();

         } catch (Exception ex) {

         }

// Get CampaignCriterionService using AdWordsSession

AdWordsServices adWordsServices = new AdWordsServices();

      CampaignCriterionServiceInterface campaignCriterionService = adWordsServices.get(adwordSession, CampaignCriterionServiceInterface.class);

      AdGroupCriterionServiceInterface adGroupCriterionService = GoogleAuthenticationService
            .getAdGroupCriterionService();

      Keyword keyword = new Keyword();
      keyword.setId(keywordId);

      BiddableAdGroupCriterion keywordBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
      keywordBiddableAdGroupCriterion.setAdGroupId(adGroupId);
      keywordBiddableAdGroupCriterion.setCriterion(keyword);

      BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
      CpcBid bid = new CpcBid();
      bid.setBid(new Money(null, bidAmount));
      biddingStrategyConfiguration.setBids(new Bids[] { bid });
      keywordBiddableAdGroupCriterion.setBiddingStrategyConfiguration(biddingStrategyConfiguration);

      AdGroupCriterionOperation keywordAdGroupCriterionOperation = new AdGroupCriterionOperation();
      keywordAdGroupCriterionOperation.setOperand(keywordBiddableAdGroupCriterion);
      keywordAdGroupCriterionOperation.setOperator(Operator.SET);

      AdGroupCriterionOperation[] operations = new AdGroupCriterionOperation[] { keywordAdGroupCriterionOperation };

      AdGroupCriterionReturnValue result = null;

      try {
         result = adGroupCriterionService.mutate(operations);
      } catch (Exception e) {
         e.printStackTrace();
      }
      
      // Display campaigns.
      for (AdGroupCriterion campaignCriterion : result.getValue()) {
         System.out.printf("Campaign criterion with criterion ID %d, " + "and type '%s' was added.%n",
               campaignCriterion.getCriterion().getId(), campaignCriterion.getCriterion().getCriterionType());
      }

   }

   Like      Feedback     Google Adwords  Adwords  Adwords Java Api  Update Adwords Bids  Update Adwords Bids for keyword


 Sample 3. Specify a Predicate ( Filter ) for a campaign Id for Google Adwords reports

Usage of

import com.google.api.ads.adwords.lib.jaxb.v201802.Selector;
com.google.api.ads.adwords.lib.jaxb.v201802.Predicate;
com.google.api.ads.adwords.lib.jaxb.v201802.PredicateOperator;

// Create selector
Selector selector = new Selector();
selector.getFields().addAll(Arrays.asList("Id","Criteria","Conversions"));
      
Predicate predicate = new Predicate();
predicate.setField("CampaignId");
PredicateOperator predicateOperator = PredicateOperator.EQUALS;
predicate.setOperator(predicateOperator);
predicate.getValues().add(campaignId);
      
selector.getPredicates().add(predicate);

   Like      Feedback     Google Adwords Api  Adwords Java Api  Adwords


 Sample 4. 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


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. 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 6. 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 7. Code Sample / Example / Snippet of org.apache.calcite.rel.logical.LogicalProject

    public RelNode convert(RelNode rel) {

final LogicalProject project = (LogicalProject) rel;

final RelTraitSet traitSet = project.getTraitSet().replace(out);

return new MongoProject(project.getCluster(), traitSet,

convert(project.getInput(), out), project.getProjects(),

project.getRowType());

}


   Like      Feedback      org.apache.calcite.rel.logical.LogicalProject


 Sample 8. 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


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

Using String method -

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

Iterative -

Strategy - Loop through each character of a String from last to first and append the character to StringBuilder / StringBuffer

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 -

Strategy - Call the method with substring starting from 2nd character recursively till we have just 1 character.

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  control statements  loop statement  stringbuffer.append  java.lang.String  java.lang.StringBuffer  String Manipulation


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. 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 11. 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 12. 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 13. Generate Random Number till 100

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

   Like      Feedback     Random Number Generation  Random


 Sample 14. Given a Map with Country Name as key and its capitals as values, Find the name of countries having more than 1 capital ?

Map<String,List<String>> capitals = new HashMap();
capitals.put("United States", Arrays.asList("Washington DC"));
capitals.put("Canada", Arrays.asList("Ottawa"));
capitals.put("South Africa", Arrays.asList("Pretoria", "Cape Down", "Bloemfontein"));
      
for(Map.Entry<String,List<String>> entry: capitals.entrySet()){
   if(entry.getValue().size() > 1){
      System.out.println(entry.getKey());
   }
}

   Like      Feedback     Map of String and List


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. 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


 Sample 16. 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 17. 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


 Sample 18. 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 19. 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


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. 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 21. 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  object initialization using getInstance


 Sample 22. 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


 Sample 23. 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 24. Code Sample / Example / Snippet of org.bouncycastle.asn1.x500.X500Name

    public X509Certificate createCertificate(X500Principal issuerDN, PrivateKey issuerKey, String name, Date notBefore, Date notAfter, PublicKey key) throws IllegalArgumentException {

try {

X500Name issuer = new X500Name(issuerDN.getName());

X500Name commonName = new X500Name(name);

BigInteger serial = BigInteger.valueOf(++m_serial);



SubjectPublicKeyInfo pubKeyInfo = convertToSubjectPublicKeyInfo(key);



X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, commonName, pubKeyInfo);



X509CertificateHolder certHolder = builder.build(new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(issuerKey));

return new JcaX509CertificateConverter().getCertificate(certHolder);

}

catch (IllegalArgumentException e) {

throw e;

}

catch (Exception e) {

throw new RuntimeException(e);

}

}


   Like      Feedback      org.bouncycastle.asn1.x500.X500Name


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. Write a Program to implement stack using an array

public class Stack{
static int top = 0;
static Element[] stack = new Element[10];

static class Element {
int body;

Element(int value){
body = value;
}
}

public static void main(String[] args){
push(5);
System.out.println(top);
push(7);
System.out.println(top);
poll();
System.out.println(top);
poll();
System.out.println(top);
}

private static void push(int value){
Element newElement = new Element(value);
top++;
}

private static Element poll(){
Element topElement = stack[top];
top--;
return topElement;
}
}

   Like      Feedback     stack


 Sample 26. 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 27. 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 28. 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 29. 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 30. 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 31. Lazy Initialization using Hibernate

@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@ManyToOne(fetch = FetchType.LAZY)
private Set<Department> dept = new Department();
}

   Like      Feedback     Lazy Initialization using Hibernate


 Sample 32. 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 33. 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 34. Code Sample / Example / Snippet of java.text.StringCharacterIterator

    public static String encode(String source) {

if (source == null) {

return "$e";

}

StringBuffer result = new StringBuffer();

StringCharacterIterator sci = new StringCharacterIterator(source);

for (char c = sci.current(); c != CharacterIterator.DONE; c = sci.next()) {

if (c == '$') {

result.append("$$");

}

else if (c == ',') {

result.append("$k");

}

else if (c == ' ') {

result.append("$n");

}

else if (c == ' ') {

result.append("$r");

}

else {

result.append(c);

}

}

return result.toString();

}


   Like      Feedback      java.text.StringCharacterIterator


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. 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 36. 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 37. 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 38. 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 39. 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 40. Example of keywords , identifiers and literals in Java

int count = 0; // int is a keyword, count is an identifier and 0 is a literal

   Like      Feedback     keywords  identifiers  literals


 Sample 41. Calculate square of a number using Lambda Expression

public interface Calc {
int square(int value);
}

public static void main(String[] args){
Calc calc = (int val) -> val * val;
System.out.println(calc.square(5));
}

   Like      Feedback     lambda Expression  java 8


 Sample 42. Write a Program that gets a set of numbers , filters out the non prime numbers , calculate the factorial of each prime number and then finds the average of all factorials using Lambda expressions

public class BuggyBread1 {
   
   public static void main(String args[]) {
      
      // 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);
      intSet.add(5);

      double averageOfNonPrimeFactorials = intSet.stream().filter(p->checkIfPrime(p)).collect(Collectors.averagingInt(p->calculateFactorial(p)));
      
      System.out.println(averageOfNonPrimeFactorials );
   }
   
   static private boolean checkIfPrime(int num){
      for(int count=2;count < num;count++){
         if(num % count == 0){
            return false;
         }
      }
      return true;
   }
   
   static private int calculateFactorial(int num){
      int factorial = 1;
      for(int count=num;count > 0;count--){
         factorial = factorial * count;
      }
      return factorial;
   }
}

   Like      Feedback     java 8  lambda expressions  lambda  filter  Collectors  factorial  prime number


 Sample 43. Write a Program for Graph Breadth First Traversal using Apache Commons MultiMap

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class Graph {
   private static Multimap<Integer,Integer> adjacentDirectedNodesMap = ArrayListMultimap.create();
   private static Set<Integer> alreadyVisited = new HashSet();
   
   static{
      adjacentDirectedNodesMap.put(1, 2);
      adjacentDirectedNodesMap.put(1, 3);
      adjacentDirectedNodesMap.put(1, 5);
      adjacentDirectedNodesMap.put(2, 4);
      adjacentDirectedNodesMap.put(4, 5);
   }
   
   public static void main(String[] args){
      ArrayList visited = new ArrayList();
      
      Integer startNode = 1;
      
      displayAdjacentNodes(startNode);
      
   }
   
   private static void displayAdjacentNodes(Integer integer){
      System.out.println(integer);
      for(Map.Entry<Integer, Collection<Integer>> adjacentNodes: adjacentDirectedNodesMap.asMap().entrySet()){
         for(Integer integer1:adjacentNodes.getValue()){
            if(alreadyVisited.contains(integer1)){
               continue;
            }
            alreadyVisited.add(integer1);
            System.out.println(integer1);
         }
      }
   }
   
}

   Like      Feedback     graph traversal  breadth first traversal


 Sample 44. Declaring Abstract Class

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

   Like      Feedback     abstract classes  main method declaration  main method


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. 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 46. 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 47. 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 48. 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 49. 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 50. Concatenate Strings

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

   Like      Feedback     string  string concatenation  concat


 Sample 51. 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


 Sample 52. 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 53. 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 54. 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


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. 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 56. 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 57. 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 58. 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 59. 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


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. 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 61. 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 62. 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 63. 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 64. 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


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. 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 66. 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 67. 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 68. 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 69. 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 70. 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 71. 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 72. 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 73. 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 74. 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


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. 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 76. 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 77. 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 78. 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 79. 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 80. 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 81. 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 82. 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


 Sample 83. 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 84. 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


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. 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


 Sample 86. 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 87. Code Sample / Example / Snippet of org.apache.storm.tuple.Fields

    public static StormTopology buildDevicesTopology() {

String deviceID = "device-id";

String count = "count";

Fields allFields = new Fields(deviceID, count);



RandomNumberGeneratorSpout spout = new RandomNumberGeneratorSpout(allFields, 10, 1000);



TridentTopology topology = new TridentTopology();

Stream devicesStream = topology.newStream("devicegen-spout", spout).

each(allFields, new Debug("##### devices"));



devicesStream.minBy(deviceID).

each(allFields, new Debug("#### device with min id"));



devicesStream.maxBy(count).

each(allFields, new Debug("#### device with max count"));



return topology.build();

}


   Like      Feedback      org.apache.storm.tuple.Fields


 Sample 88. Code Sample / Example / Snippet of java.sql.ResultSetMetaData

  private void output(ResultSet resultSet, PrintStream out)

throws SQLException {

final ResultSetMetaData metaData = resultSet.getMetaData();

final int columnCount = metaData.getColumnCount();

while (resultSet.next()) {

for (int i = 1;; i++) {

out.print(resultSet.getString(i));

if (i < columnCount) {

out.print(", ");

} else {

out.println();

break;

}

}

}

}


   Like      Feedback      java.sql.ResultSetMetaData


 Sample 89. Code Sample / Example / Snippet of java.util.zip.GZIPInputStream

  private static CSVReader openCsv(File file) throws IOException {

final Reader fileReader;

if (file.getName().endsWith(".gz")) {

final GZIPInputStream inputStream =

new GZIPInputStream(new FileInputStream(file));

fileReader = new InputStreamReader(inputStream);

} else {

fileReader = new FileReader(file);

}

return new CSVReader(fileReader);

}


   Like      Feedback      java.util.zip.GZIPInputStream


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. Code Sample / Example / Snippet of org.apache.calcite.rel.metadata.RelMetadataQuery

    public static PhysProj create(final RelNode input,

final List<RexNode> projects, RelDataType rowType) {

final RelOptCluster cluster = input.getCluster();

final RelMetadataQuery mq = RelMetadataQuery.instance();

final RelTraitSet traitSet =

cluster.traitSet().replace(PHYSICAL)

.replaceIfs(

RelCollationTraitDef.INSTANCE,

new Supplier<List<RelCollation>>() {

public List<RelCollation> get() {

return RelMdCollation.project(mq, input, projects);

}

});

return new PhysProj(cluster, traitSet, input, projects, rowType);

}


   Like      Feedback      org.apache.calcite.rel.metadata.RelMetadataQuery


 Sample 91. Code Sample / Example / Snippet of org.apache.calcite.sql.SqlCollation

  public void checkCollation(

String expression,

String expectedCollationName,

SqlCollation.Coercibility expectedCoercibility) {

for (String sql : buildQueries(expression)) {

RelDataType actualType = getColumnType(sql);

SqlCollation collation = actualType.getCollation();



assertEquals(

expectedCollationName, collation.getCollationName());

assertEquals(expectedCoercibility, collation.getCoercibility());

}

}


   Like      Feedback      org.apache.calcite.sql.SqlCollation


 Sample 92. Code Sample / Example / Snippet of com.google.common.base.Joiner

public static void assertArrayEqual(
   String message, Object[] expected, Object[] actual) {
   Joiner joiner = Joiner.on(' ');
   String strExpected = expected == null ? null : joiner.join(expected);
   String strActual = actual == null ? null : joiner.join(actual);
   assertEquals(message, strExpected, strActual);
}

   Like      Feedback      com.google.common.base.Joiner  ternary operator  joiner.join  assertEquals


 Sample 93. Code Sample / Example / Snippet of java.util.Properties

    public Connection createConnection() throws SQLException {

final Properties info = new Properties();

for (Map.Entry<String, String> entry : map.entrySet()) {

info.setProperty(entry.getKey(), entry.getValue());

}

Connection connection =

DriverManager.getConnection("jdbc:calcite:", info);

for (ConnectionPostProcessor postProcessor : postProcessors) {

connection = postProcessor.apply(connection);

}

return connection;

}


   Like      Feedback      java.util.Properties


 Sample 94. Code Sample / Example / Snippet of java.security.KeyStore

    public SSLContextBuilder loadTrustMaterial(

final File file,

final char[] storePassword,

final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {

Args.notNull(file, "Truststore file");

final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

final FileInputStream instream = new FileInputStream(file);

try {

trustStore.load(instream, storePassword);

} finally {

instream.close();

}

return loadTrustMaterial(trustStore, trustStrategy);

}


   Like      Feedback      java.security.KeyStore


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. Code Sample / Example / Snippet of org.apache.hc.core5.http.protocol.RequestValidateHost

    public void testRequestHttp11HostHeaderPresent() throws Exception {

final HttpContext context = new BasicHttpContext(null);

final BasicHttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1);

request.setHeader(HttpHeaders.HOST, "blah");

final RequestValidateHost interceptor = new RequestValidateHost();

interceptor.process(request, context);

}


   Like      Feedback      org.apache.hc.core5.http.protocol.RequestValidateHost


 Sample 96. Code Sample / Example / Snippet of java.lang.reflect.Field

    public Object getDeclaredField(Class targetClass, String name, Object target)

throws Exception

{

if (System.getSecurityManager() != null)

{

Actions actions = (Actions) m_actions.get();

actions.set(Actions.GET_FIELD_ACTION, targetClass, name, target);

try

{

return AccessController.doPrivileged(actions, m_acc);

}

catch (PrivilegedActionException e)

{

throw e.getException();

}

}

else

{

Field field = targetClass.getDeclaredField(name);

field.setAccessible(true);



return field.get(target);

}

}


   Like      Feedback      java.lang.reflect.Field


 Sample 97. Code Sample / Example / Snippet of org.apache.felix.framework.wiring.BundleRequirementImpl

    private static List<BundleRevision> getResolvedSingletons(ResolverState state)

{

BundleRequirementImpl req = new BundleRequirementImpl(

null,

BundleCapabilityImpl.SINGLETON_NAMESPACE,

Collections.EMPTY_MAP,

Collections.EMPTY_MAP);

SortedSet<BundleCapability> caps = state.getCandidates(req, true);

List<BundleRevision> singletons = new ArrayList<>();

for (BundleCapability cap : caps)

{

if (cap.getRevision().getWiring() != null)

{

singletons.add(cap.getRevision());

}

}

return singletons;

}


   Like      Feedback      org.apache.felix.framework.wiring.BundleRequirementImpl


 Sample 98. Code Sample / Example / Snippet of java.security.KeyStore

    private KeyManager[] getKeyManagerFactory(String keystoreFile, String storePass) throws IOException, GeneralSecurityException {

KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());



InputStream is = null;

try {

is = new FileInputStream(keystoreFile);



KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

ks.load(is, storePass.toCharArray());



kmf.init(ks, storePass.toCharArray());



return kmf.getKeyManagers();

}

finally {

try {

if (is != null) {

is.close();

}

}

catch (IOException e) {

}

}

}


   Like      Feedback      java.security.KeyStore


 Sample 99. Code Sample / Example / Snippet of java.util.jar.JarOutputStream

    private File createBundle(String symbolicName, String version) throws IOException {

File tmpFile = File.createTempFile("tmpbundle-", "jar");

tmpFile.deleteOnExit();

Manifest manifest = new Manifest();

manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

if (symbolicName != null) {

manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, symbolicName);

}

if (version != null) {

manifest.getMainAttributes().putValue(Constants.BUNDLE_VERSION, version);

}

JarOutputStream target = new JarOutputStream(new FileOutputStream(tmpFile), manifest);

target.close();

return tmpFile;

}


   Like      Feedback      java.util.jar.JarOutputStream


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. Code Sample / Example / Snippet of org.apache.ace.agent.AgentControl

    protected void configureProvisionedServices() throws Exception {

String serverURL = String.format("http://localhost:%d/", TestConstants.PORT);

String obrURL = serverURL.concat("obr/");

configure("org.apache.ace.deployment.servlet.agent",

"org.apache.ace.server.servlet.endpoint", "/agent",

"obr.url", obrURL,

"authentication.enabled", "false");



Map<String, String> props = new HashMap<>();

props.put(AgentConstants.CONFIG_DISCOVERY_SERVERURLS, serverURL);



AgentControl agentControl = getService(AgentControl.class);

agentControl.getConfigurationHandler().putAll(props);

}


   Like      Feedback      org.apache.ace.agent.AgentControl


 Sample 101. Code Sample / Example / Snippet of java.io.FileOutputStream

    public static void copy(File input, File output) throws IOException {

FileInputStream fis = new FileInputStream(input);

FileOutputStream fos = new FileOutputStream(output);



try {

FileChannel ic = fis.getChannel();

FileChannel oc = fos.getChannel();

try {

oc.transferFrom(ic, 0, ic.size());

}

finally {

oc.close();

ic.close();

}

}

finally {

fis.close();

fos.close();

}

}


   Like      Feedback      java.io.FileOutputStream


 Sample 102. Code Sample / Example / Snippet of javax.swing.JTextArea

    private static final String DEFAULT_PROPERTIES_FILE = "QueueMonitor.properties";



String propertiesFile = DEFAULT_PROPERTIES_FILE;

String broker = "tcp://localhost:61616";

String connectID = "QueueMonitor";

String username = "QueueMonitor";

String password = "QueueMonitor";

String browseQueues = "Q1,Q2,Q3";

String textFontName = "Dialog";

String textFontStyle = "PLAIN";

String textFontSize = "12";

String title = "QueueMonitor";



JTextArea textArea = new JTextArea();


   Like      Feedback      javax.swing.JTextArea


 Sample 103. Code Sample / Example / Snippet of org.apache.bcel.classfile.AnnotationEntry

    protected String dumpAnnotationEntries(final AnnotationEntry[] as)

{

final StringBuilder result = new StringBuilder();

result.append("[");

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

{

final AnnotationEntry annotation = as[i];

result.append(annotation.toShortString());

if (i + 1 < as.length) {

result.append(",");

}

}

result.append("]");

return result.toString();

}


   Like      Feedback      org.apache.bcel.classfile.AnnotationEntry


 Sample 104. Code Sample / Example / Snippet of org.apache.bcel.generic.ConstantPoolGen

    public void testCreateIntegerElementValue() throws Exception

{

final ClassGen cg = createClassGen("HelloWorld");

final ConstantPoolGen cp = cg.getConstantPool();

final SimpleElementValueGen evg = new SimpleElementValueGen(

ElementValueGen.PRIMITIVE_INT, cp, 555);

assertTrue("Should have the same index in the constantpool but "

+ evg.getIndex() + "!=" + cp.lookupInteger(555),

evg.getIndex() == cp.lookupInteger(555));

checkSerialize(evg, cp);

}


   Like      Feedback      org.apache.bcel.generic.ConstantPoolGen


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. Code Sample / Example / Snippet of org.apache.bcel.generic.Type

      Type             t     = BasicType.getType((byte)idents[i].getType());

LocalVariableGen lg = method.addLocalVariable(ident, t, null, null);

int slot = lg.getIndex();



entry.setLocalVariable(lg);

InstructionHandle start = il.getEnd();

exprs[i].byte_code(il, method, cp);

start = (start == null)? il.getStart() : start.getNext();

lg.setStart(start);

il.append(new ISTORE(slot)); ASTFunDecl.pop();

l[i] = lg;


   Like      Feedback      org.apache.bcel.generic.Type


 Sample 106. Code Sample / Example / Snippet of org.apache.bcel.classfile.Deprecated

    public Attribute copy( final ConstantPool _constant_pool ) {

final Deprecated c = (Deprecated) clone();

if (bytes != null) {

c.bytes = new byte[bytes.length];

System.arraycopy(bytes, 0, c.bytes, 0, bytes.length);

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.Deprecated


 Sample 107. Code Sample / Example / Snippet of org.apache.bcel.classfile.Field

        public void visitGETSTATIC(final GETSTATIC o) {

try {

final String field_name = o.getFieldName(cpg);

final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());

final Field[] fields = jc.getFields();

Field f = null;

for (final Field field : fields) {

if (field.getName().equals(field_name)) {

f = field;

break;

}

}

if (f == null) {

throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());

}



if (! (f.isStatic())) {

constraintViolated(o, "Referenced field '"+f+"' is not static which it should be.");

}

} catch (final ClassNotFoundException e) {

throw new AssertionViolatedException("Missing class: " + e, e);

}

}




   Like      Feedback      org.apache.bcel.classfile.Field


 Sample 108. Looping through elements of an ArrayList

public static void main(String[] args){
      List list = new ArrayList();
      list.add(1);
      list.add(2);
      list.add(3);
      for(Integer element: list){
         System.out.println(element);
      }
   }

   Like      Feedback     arraylist  list  collections


 Sample 109. Write a program that reads file using FileReader and BufferedReader

File file = new File("/home/sample.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

   Like      Feedback     File handling  FileReader  BufferedReader


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. Display Elements of a List using Java 8 Consumer

List myList = new ArrayList();
      
myList.add("A");
myList.add("B");
myList.add("C");

myList.forEach(System.out::println);

   Like      Feedback     Print elements of a list   java 8  consumer  foreach   list  arraylist  collections


 Sample 111. Get only files from a directory using FileFilter

File dir = new File("C:/Folder");

File[] files = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isFile();
}
});

   Like      Feedback     FileFilter


 Sample 112. Write a Program for Graph Depth First Traversal using Apache Commons MultiMap

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class Graph {
   private static Multimap<Integer,Integer> adjacentDirectedNodesMap = ArrayListMultimap.create();
   private static Set<Integer> alreadyVisited = new HashSet();
   
   static{
      adjacentDirectedNodesMap.put(1, 2);
      adjacentDirectedNodesMap.put(1, 3);
      adjacentDirectedNodesMap.put(1, 5);
      adjacentDirectedNodesMap.put(2, 4);
      adjacentDirectedNodesMap.put(4, 5);
   }
   
   public static void main(String[] args){
      ArrayList visited = new ArrayList();
      
      Integer startNode = 1;
      
      displayAdjacentNodes(startNode);
      
   }
   
   private static void displayAdjacentNodes(Integer integer){
      if(alreadyVisited.contains(integer)){
         return;
      }
      alreadyVisited.add(integer);
      System.out.println(integer);
      for(Integer adjacentNodes: adjacentDirectedNodesMap.get(integer)){
         displayAdjacentNodes(adjacentNodes);
      }
   }
   
}

   Like      Feedback     graph traversal  depth first algorithm


 Sample 113. Write a program to show thread usage in Java by implementing runnable interface

public class MyClass {
   static class MyThreadClass implements Runnable{

      public void start() {
         Thread t = new Thread(this,"threadName");
         t.start();
      }
      
      @Override
      public void run() {
         System.out.println("Hello");
         try {
            Thread.sleep(1000);
            System.out.println("Hello Again");
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
         
      }
      
   }
   
   public static void main(String[] args){
      MyThreadClass myThreadClass = new MyThreadClass();
      myThreadClass.start();
      
      MyThreadClass myThreadClass2 = new MyThreadClass();
      myThreadClass2.start();
   }
}

   Like      Feedback     Threads  runnable interface


 Sample 114. Declaring static block

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

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

private init(){
}
}

   Like      Feedback     static block  abstract class declaration


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. 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


 Sample 116. 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 117. 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 118. 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 119. 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


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. 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 121. 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 122. 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


 Sample 123. 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 124. 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


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. 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 126. 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 127. 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


 Sample 128. 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 129. 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


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. 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 131. 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 132. 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


 Sample 133. 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 134. 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()


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. 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 136. 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


 Sample 137. 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 138. 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 139. 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()


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. 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


 Sample 141. 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 142. 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 143. 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


 Sample 144. 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


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. 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 146. 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


 Sample 147. 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 148. 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 149. 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


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. 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 151. 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


 Sample 152. 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 153. Initialize Date using SimpleDateFormat and parsing string

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

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


 Sample 154. 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


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. 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 156. 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


 Sample 157. Initialize Joda DateTime

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

   Like      Feedback     DateTime   Joda


 Sample 158. 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 159. 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


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. 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 161. 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


 Sample 162. 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 163. 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 164. 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


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. 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


 Sample 166. 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 167. 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 168. 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


 Sample 169. 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


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. 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 171. 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 172. 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 173. 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


 Sample 174. 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


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. 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 176. 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 177. 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


 Sample 178. 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 179. 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


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. 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 181. Create a new File

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

   Like      Feedback     file   file handling  file.createnewfile


 Sample 182. Create a new Directory

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

   Like      Feedback     file handling  creating new directory  file.mkdir


 Sample 183. 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 184. 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


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. 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 186. 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


 Sample 187. Print the length of year as per IsoChronology

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

   Like      Feedback     AbstractChronology  IsoChronology


 Sample 188. Prints Length of year as per HijrahChronology

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

   Like      Feedback     AbstractChronology  HijrahChronology


 Sample 189. 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 190. 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 191. 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 192. 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 193. 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


 Sample 194. 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


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. 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 196. Initializing Executor Service within Kafka

int numberOfThreads = 10;

ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);

   Like      Feedback     kafka  kafka executor


 Sample 197. 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 198. 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 199. Get the Square Root of a Number

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

   Like      Feedback     square root  sqrt  Math.sqrt


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. 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 201. 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 202. 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 203. Load Library

System.loadLibrary("jawt");

   Like      Feedback     System Class  system  System.loadLibrary


 Sample 204. 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


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. 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 206. 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 207. 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


 Sample 208. 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 209. 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


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. 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 211. 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 212. 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 213. Convert int to String

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

   Like      Feedback     String  String.valueOf  int to String


 Sample 214. 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


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. 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 216. Usage of java.io.FileInputStream

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

   Like      Feedback     ileInputStrea


 Sample 217. 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 218. 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 219. 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


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. 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 221. 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


 Sample 222. 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 223. 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 224. 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


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. 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


 Sample 226. 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 227. 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


 Sample 228. 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 229. 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


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. 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 231. 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


 Sample 232. 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 233. Get Yesterdays Date using Apache Commons DateUtils

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

   Like      Feedback     DateUtils  Apache Commons


 Sample 234. 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


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. 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 236. 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


 Sample 237. 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 238. 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 239. 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 240. 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 241. 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 242. 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 243. 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 244. 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 245. 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 246. 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 247. 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 248. 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 249. 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 250. 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 251. 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 252. 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 253. 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 254. 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 255. 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 256. 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 257. Email Validation using org.apache.commons.validator.routines.EmailValidator

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

   Like      Feedback     email validation


 Sample 258. 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


 Sample 259. Usage of org.apache.avro.reflect.Union

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

   Like      Feedback     Apache Avro


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. Usage of java.lang.reflect.ParameterizedType

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

   Like      Feedback     Reflection  ParameterizedType


 Sample 261. 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 262. 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 263. 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


 Sample 264. 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


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. 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 266. 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 267. 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 268. 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


 Sample 269. Usage of MD5MD5CRC32FileChecksum

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

   Like      Feedback     MD5MD5CRC32FileChecksum  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 270. 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 271. 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 272. 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 273. 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


 Sample 274. 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


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. 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 276. 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 277. 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 278. 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


 Sample 279. 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


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 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 281. 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 282. 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


 Sample 283. 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 284. 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


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.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 286. 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 287. 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


 Sample 288. 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 289. 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


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.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 291. 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 292. 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


 Sample 293. 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 294. 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


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.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 296. 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


 Sample 297. 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 298. 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 299. 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


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.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 301. 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


 Sample 302. 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 303. 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 304. 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


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 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 306. 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


 Sample 307. 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 308. 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 309. 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


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 java.util.Calendar

    public static double year()

{

Calendar cal = Calendar.getInstance();

return cal.get(Calendar.YEAR);

}


   Like      Feedback      java.util.Calendar


 Sample 311. 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


 Sample 312. 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 313. 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 314. 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


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 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


 Sample 316. 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 317. 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 318. 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 319. 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 320. 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 321. 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 322. 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 323. 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


 Sample 324. 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


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 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 326. 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 327. 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 328. 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 329. 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


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 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 331. 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 332. 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


 Sample 333. 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 334. 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


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.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 336. 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


 Sample 337. 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 338. Code Sample / Example / Snippet of org.apache.spark.api.java.JavaDoubleRDD