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

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

   Like      Feedback     Random Number Generation  Random


 Sample 11. 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 12. 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 13. 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 14. 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


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


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

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

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

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

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


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


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


 Sample 22. 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 23. 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 24. Find the Average of all collection elements using Lambda Expressions

// Declare and Initialize the Collection

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

// Add Elements

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

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

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

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collector


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 25. 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 26. 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 27. 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 28. 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()


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


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. 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 31. 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 32. 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 33. 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


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


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. Declaring Abstract Class

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

   Like      Feedback     abstract classes  main method declaration  main method


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


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. 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 46. 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 47. 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 48. 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


 Sample 49. Concatenate Strings

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

   Like      Feedback     string  string concatenation  concat


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. 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 51. 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 52. 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 53. Rest Web Service ( Get ) using Jersey

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

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


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


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. 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 56. 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 57. 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 58. Sorting an arraylist using Collections.sort

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

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

Collections.sort(myList);

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

   Like      Feedback     list  arraylist  collections.sort  collections


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


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. 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 61. 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 62. 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 63. Get the Calendar Type from the abstract chronology

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

   Like      Feedback     AbstractChronology  java 8  AbstractChronology.getCalendarType


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


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. 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 66. 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 67. 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 68. 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


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


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. 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 71. 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 72. 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 73. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.server.namenode.DatanodeDescriptor.BlockTargetPair

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

super(action);



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

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

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

BlockTargetPair p = blocktargetlist.get(i);

blocks[i] = p.block;

targets[i] = p.targets;

}

}




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


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


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 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 76. 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 77. 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 78. 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


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


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.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 81. 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 82. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.ExternalShuffleClient

  private void validate(String appId, String secretKey, boolean encrypt) throws IOException {

ExternalShuffleClient client =

new ExternalShuffleClient(conf, new TestSecretKeyHolder(appId, secretKey), true, encrypt);

client.init(appId);

client.registerWithShuffleServer(TestUtils.getLocalHost(), server.getPort(), "exec0",

new ExecutorShuffleInfo(new String[0], 0, ""));

client.close();

}


   Like      Feedback      org.apache.spark.network.shuffle.ExternalShuffleClient


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


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


 Sample 88. 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 89. 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


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


 Sample 93. 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 94. 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


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


 Sample 98. 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 99. 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


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


 Sample 103. 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 104. 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


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


 Sample 108. 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 109. 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


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. 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 111. 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 112. 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 113. Declaring static block

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

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

private init(){
}
}

   Like      Feedback     static block  abstract class declaration


 Sample 114. Web Crawler using crawler4j - Crawler Controller

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

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

// Set Config

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

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

// Instantiate the controller for this crawl.

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

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

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

// Exit
System.exit(0);

   Like      Feedback     crawler4j


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 115. 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 116. 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 117. 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 118. SWT / JFace - TreeViewer - Different Menus for Parent and Child

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

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

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

   Like      Feedback     swt  jface  jface tree   jface table  jface menu   MenuDetectEvent


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


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 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 121. 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 122. 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 123. Rest Web Service ( Post ) using Jersey, XML

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

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


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


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. 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 126. 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 127. 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 128. Method to check if the WebUrl matches a Pattern.

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

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

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


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


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. 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 131. 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 132. 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 133. Check if a string contains a substring.

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

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

   Like      Feedback     string  substring  indexOf()


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


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 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 136. 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 137. 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 138. Remove templatized arguments from a String

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

   Like      Feedback     string  string trim  trim  char  .toCharArray()


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

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

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


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 140. 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 141. 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 142. 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 143. Usage of StringBuffer

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

   Like      Feedback     stringbuffer


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


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. 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 146. 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 147. 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 148. Method to get a map of words and their count by passing in the string

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

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

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

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


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


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

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

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


 Sample 153. Get current time using GregorianCalendar

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

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


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


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. 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 156. Initialize Joda DateTime

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

   Like      Feedback     DateTime   Joda


 Sample 157. 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 158. Selenium - Get the element using WebDriver

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

// or use annotation @FindBy as following

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

   Like      Feedback     selenium  webdriver  automation testing


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


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. 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 161. 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 162. 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 163. Internal Implementation of java.time.chrono.era

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

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

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

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

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

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

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

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

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


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

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

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


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 165. 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 166. 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 167. 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 168. Write to a file using File, FileOutputStream and ObjectOutputStream

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

   Like      Feedback     File   FileOutputStream   ObjectOutputStream   file handling


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


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. 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 171. 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 172. 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 173. Method to get Date after n days using Calendar

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

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

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


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


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. 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 176. 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 177. 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 178. Initialize member elements ( maps ) using constructor

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

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

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

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

   Like      Feedback     constructor   initializing maps   initializing treemap   enum


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


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

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

   Like      Feedback     file   file handling  file.createnewfile


 Sample 181. Create a new Directory

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

   Like      Feedback     file handling  creating new directory  file.mkdir


 Sample 182. 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 183. Today's Date as per Japanese Chronology

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

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


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


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 ThaiBuddhistChronology

AbstractChronology abstractChrono = ThaiBuddhistChronology.INSTANCE;

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

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


 Sample 186. Print the length of year as per IsoChronology

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

   Like      Feedback     AbstractChronology  IsoChronology


 Sample 187. Prints Length of year as per HijrahChronology

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

   Like      Feedback     AbstractChronology  HijrahChronology


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


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


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. 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 191. 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 192. 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 193. Round a Big Decimal Number with 5 precision and to upper value using MathContext

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

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


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


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

int numberOfThreads = 10;

ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);

   Like      Feedback     kafka  kafka executor


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

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

   Like      Feedback     square root  sqrt  Math.sqrt


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


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

System.loadLibrary("jawt");

   Like      Feedback     System Class  system  System.loadLibrary


 Sample 203. Loading Class using Class.forName ( Reflection )

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

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

   Like      Feedback     Class.forName  Reflection


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


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. 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 206. 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 207. 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 208. Repeat a string using Google Guava Strings Class

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

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


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


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

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

   Like      Feedback     String  String.valueOf  int to String


 Sample 213. RabbitMQ message receiver

import java.util.concurrent.CountDownLatch;

public class Receiver {

   private CountDownLatch latch = new CountDownLatch(1);

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

   public CountDownLatch getLatch() {
      return latch;
   }

}

   Like      Feedback     Spring AMQP  Rabbit MQ  RabbitMQ


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


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

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

   Like      Feedback     ileInputStrea


 Sample 216. 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 217. 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 218. Usage of org.joda.time.DateMidnight

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

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


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


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. 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 221. 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 222. 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 223. Make a Map entry read only using Apache Commons UnmodifiableMapEntry

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

   Like      Feedback     read only map entry  UnmodifiableMapEntry  Apache commons collections


 Sample 224. Cache Hibernate Entities using EHCache

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

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

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

CacheManager.getInstance().addCache(employeeCache);

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


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 225. 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 226. 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 227. 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 228. Find the Frequency of a Particular element in a Collection using apache Commons IterableUtils

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

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


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


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

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

   Like      Feedback     DateUtils  Apache Commons


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

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

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

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

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

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


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


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


 Sample 239. 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 )


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. 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 241. 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 242. 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 243. 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


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


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. 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 246. 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 247. 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 248. 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


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


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. 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 251. 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 252. 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 253. 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


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


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. 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 256. Email Validation using org.apache.commons.validator.routines.EmailValidator

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

   Like      Feedback     email validation


 Sample 257. 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 258. Usage of org.apache.avro.reflect.Union

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

   Like      Feedback     Apache Avro


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

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

   Like      Feedback     Reflection  ParameterizedType


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 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 261. 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 262. 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 263. Usage of org.apache.hadoop.fs.permission.FsPermission

FsPermission mode = inode.getFsPermission();

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

   Like      Feedback     Apache Hadoop  FsPermission


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


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

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

   Like      Feedback     MD5MD5CRC32FileChecksum  Apache Hadoop


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


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 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 271. 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 272. 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 273. Usage of javax.xml.transform.Transformer, TransformerFactory

TransformerFactory tFactory = TransformerFactory.newInstance();

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

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

   Like      Feedback     TransformerFactory  Transformer


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


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. 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 276. 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 277. 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 278. Code Sample / Example / Snippet of org.apache.hadoop.util.Daemon

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

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

Configuration tconf = new Configuration();

if (argv.length >= 1) {

SecondaryNameNode secondary = new SecondaryNameNode(tconf);

int ret = secondary.processArgs(argv);

System.exit(ret);

}



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

checkpointThread.start();

}


   Like      Feedback      org.apache.hadoop.util.Daemon


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


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.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 281. 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 282. 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 283. Code Sample / Example / Snippet of javax.rmi.CORBA.ValueHandler

    public synchronized IOR getFVDCodeBaseIOR()

{

checkShutdownState();



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

return codeBaseIOR;



CodeBase cb;



ValueHandler vh = ORBUtility.createValueHandler();



cb = (CodeBase)vh.getRunTimeCodeBase();

return ORBUtility.connectAndGetIOR( this, cb ) ;

}


   Like      Feedback      javax.rmi.CORBA.ValueHandler


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


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.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 286. 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 287. 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 288. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.DistributedFileSystem

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

String pathname = argv[idx];

DistributedFileSystem dfs = (DistributedFileSystem) fs;

dfs.metaSave(pathname);

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

dfs.getUri());

return 0;

}


   Like      Feedback      org.apache.hadoop.hdfs.DistributedFileSystem


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


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.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 291. 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 292. 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 293. Code Sample / Example / Snippet of org.apache.hadoop.fs.FileSystem

  public static long getTimestamp(Configuration conf, URI cache)

throws IOException {

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

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



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

}


   Like      Feedback      org.apache.hadoop.fs.FileSystem


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


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 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 296. 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 297. 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 298. Code Sample / Example / Snippet of org.apache.commons.httpclient.HttpMethod

  private static int httpNotification(String uri) throws IOException {

URI url = new URI(uri, false);

HttpClient m_client = new HttpClient();

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

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

return m_client.executeMethod(method);

}


   Like      Feedback      org.apache.commons.httpclient.HttpMethod


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


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.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 301. 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 302. 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 303. Code Sample / Example / Snippet of org.apache.hadoop.mapred.Mapper

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

Reporter reporter) throws IOException {

Mapper mapper = chain.getFirstMap();

if (mapper != null) {

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

reporter);

}

}


   Like      Feedback      org.apache.hadoop.mapred.Mapper


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


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 305. Code Sample / Example / Snippet of org.apache.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 306. 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 307. 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 308. Code Sample / Example / Snippet of com.sun.corba.se.spi.orb.Operation

        public PropertyParser makeParser()

{

PropertyParser parser = new PropertyParser() ;

Operation action = OperationFactory.compose(

OperationFactory.suffixAction(),

OperationFactory.classAction()

) ;

parser.addPrefix( ORBConstants.SUN_PREFIX + "ORBUserConfigurators",

action, "userConfigurators", Class.class ) ;

return parser ;

}


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


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


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.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 311. 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 312. 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 313. Code Sample / Example / Snippet of java.awt.Polygon

    private Polygon getBorderShape(int side) {

Polygon shape = null;

int[] widths = getWidths();

if (widths[side] != 0) {

shape = new Polygon(new int[4], new int[4], 0);

shape.addPoint(0, 0);

shape.addPoint(-widths[(side + 3) % 4], -widths[side]);

shape.addPoint(widths[(side + 1) % 4], -widths[side]);

shape.addPoint(0, 0);

}

return shape;

}


   Like      Feedback      java.awt.Polygon


 Sample 314. Code Sample / Example / Snippet of javax.swing.JEditorPane

        public EditorKit getEditorKitForContentType(String type) {

EditorKit editorKit = super.getEditorKitForContentType(type);

JEditorPane outerMostJEditorPane = null;

if ((outerMostJEditorPane = getOutermostJEditorPane()) != null) {

EditorKit inheritedEditorKit = outerMostJEditorPane.getEditorKitForContentType(type);

if (! editorKit.getClass().equals(inheritedEditorKit.getClass())) {

editorKit = (EditorKit) inheritedEditorKit.clone();

setEditorKitForContentType(type, editorKit);

}

}

return editorKit;

}


   Like      Feedback      javax.swing.JEditorPane


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 315. 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 316. 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 317. 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 318. 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


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


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 320. Code Sample / Example / Snippet of 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 321. 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 322. 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 323. Code Sample / Example / Snippet of java.time.ZonedDateTime

    public long until(Temporal endExclusive, TemporalUnit unit) {

ZonedDateTime end = ZonedDateTime.from(endExclusive);

if (unit instanceof ChronoUnit) {

end = end.withZoneSameInstant(zone);

if (unit.isDateBased()) {

return dateTime.until(end.dateTime, unit);

} else {

return toOffsetDateTime().until(end.toOffsetDateTime(), unit);

}

}

return unit.between(this, end);

}


   Like      Feedback      java.time.ZonedDateTime


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


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.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 326. 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 327. 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 328. Code Sample / Example / Snippet of java.time.chrono.Chronology

        public ChronoLocalDate resolve(

Map<TemporalField, Long> fieldValues, TemporalAccessor partialTemporal, ResolverStyle resolverStyle) {

long value = fieldValues.remove(this);

Chronology chrono = Chronology.from(partialTemporal);

if (resolverStyle == ResolverStyle.LENIENT) {

return chrono.dateEpochDay(Math.subtractExact(value, offset));

}

range().checkValidValue(value, this);

return chrono.dateEpochDay(value - offset);

}


   Like      Feedback      java.time.chrono.Chronology


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


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 330. Code Sample / Example / Snippet of org.apache.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 331. 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 332. 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 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

  public void map() {

JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5));

JavaDoubleRDD doubles = rdd.mapToDouble(x -> 1.0 * x).cache();

doubles.collect();

JavaPairRDD<Integer, Integer> pairs = rdd.mapToPair(x -> new Tuple2<>(x, x))

.cache();

pairs.collect();

JavaRDD<String> strings = rdd.map(Object::toString).cache();

strings.collect();

}


   Like      Feedback      org.apache.spark.api.java.JavaDoubleRDD


 Sample 339. Code Sample / Example / Snippet of org.apache.spark.SparkConf

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

SparkConf sparkConf = new SparkConf().setAppName(APP_NAME);

final JavaSparkContext sc = new JavaSparkContext(sparkConf);



JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5), 5).map(

new IdentityWithDelay<Integer>());

JavaFutureAction<List<Integer>> jobFuture = rdd.collectAsync();

while (!jobFuture.isDone()) {

Thread.sleep(1000); // 1 second

List<Integer> jobIds = jobFuture.jobIds();

if (jobIds.isEmpty()) {

continue;

}

int currentJobId = jobIds.get(jobIds.size() - 1);

SparkJobInfo jobInfo = sc.statusTracker().getJobInfo(currentJobId);

SparkStageInfo stageInfo = sc.statusTracker().getStageInfo(jobInfo.stageIds()[0]);

System.out.println(stageInfo.numTasks() + " tasks total: " + stageInfo.numActiveTasks() +

" active, " + stageInfo.numCompletedTasks() + " complete");

}



System.out.println("Job results are: " + jobFuture.get());

sc.stop();

}


   Like      Feedback      org.apache.spark.SparkConf


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

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

SparkConf sparkConf = new SparkConf().setAppName(APP_NAME);

final JavaSparkContext sc = new JavaSparkContext(sparkConf);



JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5), 5).map(

new IdentityWithDelay<Integer>());

JavaFutureAction<List<Integer>> jobFuture = rdd.collectAsync();

while (!jobFuture.isDone()) {

Thread.sleep(1000); // 1 second

List<Integer> jobIds = jobFuture.jobIds();

if (jobIds.isEmpty()) {

continue;

}

int currentJobId = jobIds.get(jobIds.size() - 1);

SparkJobInfo jobInfo = sc.statusTracker().getJobInfo(currentJobId);

SparkStageInfo stageInfo = sc.statusTracker().getStageInfo(jobInfo.stageIds()[0]);

System.out.println(stageInfo.numTasks() + " tasks total: " + stageInfo.numActiveTasks() +

" active, " + stageInfo.numCompletedTasks() + " complete");

}



System.out.println("Job results are: " + jobFuture.get());

sc.stop();

}


   Like      Feedback      org.apache.spark.SparkJobInfo


 Sample 341. Code Sample / Example / Snippet of org.apache.spark.SparkStageInfo

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

SparkConf sparkConf = new SparkConf().setAppName(APP_NAME);

final JavaSparkContext sc = new JavaSparkContext(sparkConf);



JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5), 5).map(

new IdentityWithDelay<Integer>());

JavaFutureAction<List<Integer>> jobFuture = rdd.collectAsync();

while (!jobFuture.isDone()) {

Thread.sleep(1000); // 1 second

List<Integer> jobIds = jobFuture.jobIds();

if (jobIds.isEmpty()) {

continue;

}

int currentJobId = jobIds.get(jobIds.size() - 1);

SparkJobInfo jobInfo = sc.statusTracker().getJobInfo(currentJobId);

SparkStageInfo stageInfo = sc.statusTracker().getStageInfo(jobInfo.stageIds()[0]);

System.out.println(stageInfo.numTasks() + " tasks total: " + stageInfo.numActiveTasks() +

" active, " + stageInfo.numCompletedTasks() + " complete");

}



System.out.println("Job results are: " + jobFuture.get());

sc.stop();

}


   Like      Feedback      org.apache.spark.SparkStageInfo


 Sample 342. Code Sample / Example / Snippet of org.apache.spark.sql.SQLContext

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaDCTExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



JavaRDD<Row> data = jsc.parallelize(Arrays.asList(

RowFactory.create(Vectors.dense(0.0, 1.0, -2.0, 3.0)),

RowFactory.create(Vectors.dense(-1.0, 2.0, 4.0, -7.0)),

RowFactory.create(Vectors.dense(14.0, -2.0, -5.0, 1.0))

));

StructType schema = new StructType(new StructField[]{

new StructField("features", new VectorUDT(), false, Metadata.empty()),

});

DataFrame df = jsql.createDataFrame(data, schema);

DCT dct = new DCT()

.setInputCol("features")

.setOutputCol("featuresDCT")

.setInverse(false);

DataFrame dctDf = dct.transform(df);

dctDf.select("featuresDCT").show(3);

jsc.stop();

}


   Like      Feedback      org.apache.spark.sql.SQLContext


 Sample 343. Code Sample / Example / Snippet of org.apache.spark.ml.feature.DCT

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaDCTExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



JavaRDD<Row> data = jsc.parallelize(Arrays.asList(

RowFactory.create(Vectors.dense(0.0, 1.0, -2.0, 3.0)),

RowFactory.create(Vectors.dense(-1.0, 2.0, 4.0, -7.0)),

RowFactory.create(Vectors.dense(14.0, -2.0, -5.0, 1.0))

));

StructType schema = new StructType(new StructField[]{

new StructField("features", new VectorUDT(), false, Metadata.empty()),

});

DataFrame df = jsql.createDataFrame(data, schema);

DCT dct = new DCT()

.setInputCol("features")

.setOutputCol("featuresDCT")

.setInverse(false);

DataFrame dctDf = dct.transform(df);

dctDf.select("featuresDCT").show(3);

jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.feature.DCT


 Sample 344. Code Sample / Example / Snippet of org.apache.spark.ml.param.IntParam

  public String uid() {

return uid_;

}



IntParam maxIter = new IntParam(this, "maxIter", "max number of iterations");


   Like      Feedback      org.apache.spark.ml.param.IntParam


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 345. Code Sample / Example / Snippet of org.apache.spark.mllib.linalg.Vector

  public MyJavaLogisticRegressionModel train(DataFrame dataset) {

JavaRDD<LabeledPoint> oldDataset = extractLabeledPoints(dataset).toJavaRDD();



int numFeatures = oldDataset.take(1).get(0).features().size();

Vector weights = Vectors.zeros(numFeatures); // Learning would happen here.



return new MyJavaLogisticRegressionModel(uid(), weights).setParent(this);

}


   Like      Feedback      org.apache.spark.mllib.linalg.Vector


 Sample 346. Code Sample / Example / Snippet of org.apache.spark.ml.feature.StandardScaler

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaStandardScalerExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");



StandardScaler scaler = new StandardScaler()

.setInputCol("features")

.setOutputCol("scaledFeatures")

.setWithStd(true)

.setWithMean(false);



StandardScalerModel scalerModel = scaler.fit(dataFrame);



DataFrame scaledData = scalerModel.transform(dataFrame);

scaledData.show();

jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.feature.StandardScaler


 Sample 347. Code Sample / Example / Snippet of org.apache.spark.ml.feature.StandardScalerModel

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaStandardScalerExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");



StandardScaler scaler = new StandardScaler()

.setInputCol("features")

.setOutputCol("scaledFeatures")

.setWithStd(true)

.setWithMean(false);



StandardScalerModel scalerModel = scaler.fit(dataFrame);



DataFrame scaledData = scalerModel.transform(dataFrame);

scaledData.show();

jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.feature.StandardScalerModel


 Sample 348. Code Sample / Example / Snippet of org.apache.spark.ml.feature.Normalizer

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaNormalizerExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");



Normalizer normalizer = new Normalizer()

.setInputCol("features")

.setOutputCol("normFeatures")

.setP(1.0);



DataFrame l1NormData = normalizer.transform(dataFrame);

l1NormData.show();



DataFrame lInfNormData =

normalizer.transform(dataFrame, normalizer.p().w(Double.POSITIVE_INFINITY));

lInfNormData.show();

jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.feature.Normalizer


 Sample 349. Code Sample / Example / Snippet of org.apache.spark.ml.classification.LogisticRegression

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaLogisticRegressionWithElasticNetExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext sqlContext = new SQLContext(jsc);



DataFrame training = sqlContext.read().format("libsvm")

.load("data/mllib/sample_libsvm_data.txt");



LogisticRegression lr = new LogisticRegression()

.setMaxIter(10)

.setRegParam(0.3)

.setElasticNetParam(0.8);



LogisticRegressionModel lrModel = lr.fit(training);



System.out.println("Coefficients: "

+ lrModel.coefficients() + " Intercept: " + lrModel.intercept());



jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.classification.LogisticRegression


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 350. Code Sample / Example / Snippet of org.apache.spark.ml.feature.SQLTransformer

  public static void main(String[] args) {



SparkConf conf = new SparkConf().setAppName("JavaSQLTransformerExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext sqlContext = new SQLContext(jsc);



JavaRDD<Row> jrdd = jsc.parallelize(Arrays.asList(

RowFactory.create(0, 1.0, 3.0),

RowFactory.create(2, 2.0, 5.0)

));

StructType schema = new StructType(new StructField [] {

new StructField("id", DataTypes.IntegerType, false, Metadata.empty()),

new StructField("v1", DataTypes.DoubleType, false, Metadata.empty()),

new StructField("v2", DataTypes.DoubleType, false, Metadata.empty())

});

DataFrame df = sqlContext.createDataFrame(jrdd, schema);



SQLTransformer sqlTrans = new SQLTransformer().setStatement(

"SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__");



sqlTrans.transform(df).show();

}


   Like      Feedback      org.apache.spark.ml.feature.SQLTransformer


 Sample 351. Code Sample / Example / Snippet of org.apache.spark.ml.feature.MinMaxScalerModel

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JaveMinMaxScalerExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");

MinMaxScaler scaler = new MinMaxScaler()

.setInputCol("features")

.setOutputCol("scaledFeatures");



MinMaxScalerModel scalerModel = scaler.fit(dataFrame);



DataFrame scaledData = scalerModel.transform(dataFrame);

scaledData.show();

jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.feature.MinMaxScalerModel


 Sample 352. Code Sample / Example / Snippet of org.apache.spark.ml.feature.MinMaxScaler

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JaveMinMaxScalerExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext jsql = new SQLContext(jsc);



DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");

MinMaxScaler scaler = new MinMaxScaler()

.setInputCol("features")

.setOutputCol("scaledFeatures");



MinMaxScalerModel scalerModel = scaler.fit(dataFrame);



DataFrame scaledData = scalerModel.transform(dataFrame);

scaledData.show();

jsc.stop();

}


   Like      Feedback      org.apache.spark.ml.feature.MinMaxScaler


 Sample 353. Code Sample / Example / Snippet of org.apache.spark.mllib.classification.LogisticRegressionModel

  public static void main(String[] args) {

SparkConf conf = new SparkConf().setAppName("JavaLogisticRegressionWithElasticNetExample");

JavaSparkContext jsc = new JavaSparkContext(conf);

SQLContext sqlContext = new SQLContext(jsc);



DataFrame training = sqlContext.read().format("libsvm")

.load("data/mllib/sample_libsvm_data.txt");



LogisticRegression lr = new LogisticRegression()

.setMaxIter(10)

.setRegParam(0.3)

.setElasticNetParam(0.8);



LogisticRegressionModel lrModel = lr.fit(training);



System.out.println("Coefficients: "

+ lrModel.coefficients() + " Intercept: " + lrModel.intercept());



jsc.stop();

}


   Like      Feedback      org.apache.spark.mllib.classification.LogisticRegressionModel


 Sample 354. Code Sample / Example / Snippet of org.apache.storm.task.TopologyContext

  public void shouldEmitNothingIfNoObjectHasBeenCountedYetAndTickTupleIsReceived() {

Tuple tickTuple = MockTupleHelpers.mockTickTuple();

RollingCountBolt bolt = new RollingCountBolt();

Map conf = mock(Map.class);

TopologyContext context = mock(TopologyContext.class);

OutputCollector collector = mock(OutputCollector.class);

bolt.prepare(conf, context, collector);



bolt.execute(tickTuple);



verifyZeroInteractions(collector);

}


   Like      Feedback      org.apache.storm.task.TopologyContext


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 355. Code Sample / Example / Snippet of org.apache.spark.mllib.fpm.AssociationRules

  public static void main(String[] args) {



SparkConf sparkConf = new SparkConf().setAppName("JavaAssociationRulesExample");

JavaSparkContext sc = new JavaSparkContext(sparkConf);



JavaRDD<FPGrowth.FreqItemset<String>> freqItemsets = sc.parallelize(Arrays.asList(

new FreqItemset<String>(new String[] {"a"}, 15L),

new FreqItemset<String>(new String[] {"b"}, 35L),

new FreqItemset<String>(new String[] {"a", "b"}, 12L)

));



AssociationRules arules = new AssociationRules()

.setMinConfidence(0.8);

JavaRDD<AssociationRules.Rule<String>> results = arules.run(freqItemsets);



for (AssociationRules.Rule<String> rule : results.collect()) {

System.out.println(

rule.javaAntecedent() + " => " + rule.javaConsequent() + ", " + rule.confidence());

}

}


   Like      Feedback      org.apache.spark.mllib.fpm.AssociationRules


 Sample 356. Code Sample / Example / Snippet of org.apache.spark.mllib.regression.IsotonicRegressionModel

        public Tuple3<Double, Double, Double> call(String line) {

String[] parts = line.split(",");

return new Tuple3<>(new Double(parts[0]), new Double(parts[1]), 1.0);

}

}

);



JavaRDD<Tuple3<Double, Double, Double>>[] splits = parsedData.randomSplit(new double[]{0.6, 0.4}, 11L);

JavaRDD<Tuple3<Double, Double, Double>> training = splits[0];

JavaRDD<Tuple3<Double, Double, Double>> test = splits[1];



final IsotonicRegressionModel model = new IsotonicRegression().setIsotonic(true).run(training);



JavaPairRDD<Double, Double> predictionAndLabel = test.mapToPair(

new PairFunction<Tuple3<Double, Double, Double>, Double, Double>() {


   Like      Feedback      org.apache.spark.mllib.regression.IsotonicRegressionModel


 Sample 357. Code Sample / Example / Snippet of org.apache.spark.mllib.fpm.PrefixSpan

  public static void main(String[] args) {



SparkConf sparkConf = new SparkConf().setAppName("JavaPrefixSpanExample");

JavaSparkContext sc = new JavaSparkContext(sparkConf);



JavaRDD<List<List<Integer>>> sequences = sc.parallelize(Arrays.asList(

Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3)),

Arrays.asList(Arrays.asList(1), Arrays.asList(3, 2), Arrays.asList(1, 2)),

Arrays.asList(Arrays.asList(1, 2), Arrays.asList(5)),

Arrays.asList(Arrays.asList(6))

), 2);

PrefixSpan prefixSpan = new PrefixSpan()

.setMinSupport(0.5)

.setMaxPatternLength(5);

PrefixSpanModel<Integer> model = prefixSpan.run(sequences);

for (PrefixSpan.FreqSequence<Integer> freqSeq: model.freqSequences().toJavaRDD().collect()) {

System.out.println(freqSeq.javaSequence() + ", " + freqSeq.freq());

}

}


   Like      Feedback      org.apache.spark.mllib.fpm.PrefixSpan


 Sample 358. Code Sample / Example / Snippet of org.apache.spark.mllib.clustering.PowerIterationClustering

  public static void main(String[] args) {

SparkConf sparkConf = new SparkConf().setAppName("JavaPowerIterationClusteringExample");

JavaSparkContext sc = new JavaSparkContext(sparkConf);



@SuppressWarnings("unchecked")

JavaRDD<Tuple3<Long, Long, Double>> similarities = sc.parallelize(Lists.newArrayList(

new Tuple3<Long, Long, Double>(0L, 1L, 0.9),

new Tuple3<Long, Long, Double>(1L, 2L, 0.9),

new Tuple3<Long, Long, Double>(2L, 3L, 0.9),

new Tuple3<Long, Long, Double>(3L, 4L, 0.1),

new Tuple3<Long, Long, Double>(4L, 5L, 0.9)));



PowerIterationClustering pic = new PowerIterationClustering()

.setK(2)

.setMaxIterations(10);

PowerIterationClusteringModel model = pic.run(similarities);



for (PowerIterationClustering.Assignment a: model.assignments().toJavaRDD().collect()) {

System.out.println(a.id() + " -> " + a.cluster());

}



sc.stop();

}


   Like      Feedback      org.apache.spark.mllib.clustering.PowerIterationClustering


 Sample 359. Code Sample / Example / Snippet of org.apache.spark.mllib.clustering.PowerIterationClusteringModel

  public static void main(String[] args) {

SparkConf sparkConf = new SparkConf().setAppName("JavaPowerIterationClusteringExample");

JavaSparkContext sc = new JavaSparkContext(sparkConf);



@SuppressWarnings("unchecked")

JavaRDD<Tuple3<Long, Long, Double>> similarities = sc.parallelize(Lists.newArrayList(

new Tuple3<Long, Long, Double>(0L, 1L, 0.9),

new Tuple3<Long, Long, Double>(1L, 2L, 0.9),

new Tuple3<Long, Long, Double>(2L, 3L, 0.9),

new Tuple3<Long, Long, Double>(3L, 4L, 0.1),

new Tuple3<Long, Long, Double>(4L, 5L, 0.9)));



PowerIterationClustering pic = new PowerIterationClustering()

.setK(2)

.setMaxIterations(10);

PowerIterationClusteringModel model = pic.run(similarities);



for (PowerIterationClustering.Assignment a: model.assignments().toJavaRDD().collect()) {

System.out.println(a.id() + " -> " + a.cluster());

}



sc.stop();

}


   Like      Feedback      org.apache.spark.mllib.clustering.PowerIterationClusteringModel


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 360. Code Sample / Example / Snippet of org.apache.spark.mllib.stat.test.StreamingTest

  public void streamingTest() {

List<BinarySample> trainingBatch = Arrays.asList(

new BinarySample(true, 1.0),

new BinarySample(false, 2.0));

JavaDStream<BinarySample> training =

attachTestInputStream(ssc, Arrays.asList(trainingBatch, trainingBatch), 2);

int numBatches = 2;

StreamingTest model = new StreamingTest()

.setWindowSize(0)

.setPeacePeriod(0)

.setTestMethod("welch");

model.registerStream(training);

attachTestOutputStream(training);

runStreams(ssc, numBatches, numBatches);

}


   Like      Feedback      org.apache.spark.mllib.stat.test.StreamingTest


 Sample 361. Code Sample / Example / Snippet of org.apache.spark.network.server.TransportServerBootstrap

  public void beforeEach() throws IOException {

TransportContext context =

new TransportContext(conf, new ExternalShuffleBlockHandler(conf, null));

TransportServerBootstrap bootstrap = new SaslServerBootstrap(conf,

new TestSecretKeyHolder("my-app-id", "secret"));

this.server = context.createServer(Arrays.asList(bootstrap));

}


   Like      Feedback      org.apache.spark.network.server.TransportServerBootstrap


 Sample 362. Code Sample / Example / Snippet of org.apache.spark.network.TransportContext

  public void beforeEach() throws IOException {

TransportContext context =

new TransportContext(conf, new ExternalShuffleBlockHandler(conf, null));

TransportServerBootstrap bootstrap = new SaslServerBootstrap(conf,

new TestSecretKeyHolder("my-app-id", "secret"));

this.server = context.createServer(Arrays.asList(bootstrap));

}


   Like      Feedback      org.apache.spark.network.TransportContext


 Sample 363. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.ExternalShuffleBlockResolver.AppExecId

  public void jsonSerializationOfExecutorRegistration() throws IOException {

ObjectMapper mapper = new ObjectMapper();

AppExecId appId = new AppExecId("foo", "bar");

String appIdJson = mapper.writeValueAsString(appId);

AppExecId parsedAppId = mapper.readValue(appIdJson, AppExecId.class);

assertEquals(parsedAppId, appId);



ExecutorShuffleInfo shuffleInfo =

new ExecutorShuffleInfo(new String[]{"/bippy", "/flippy"}, 7, "hash");

String shuffleJson = mapper.writeValueAsString(shuffleInfo);

ExecutorShuffleInfo parsedShuffleInfo =

mapper.readValue(shuffleJson, ExecutorShuffleInfo.class);

assertEquals(parsedShuffleInfo, shuffleInfo);



String legacyAppIdJson = "{"appId":"foo", "execId":"bar"}";

assertEquals(appId, mapper.readValue(legacyAppIdJson, AppExecId.class));

String legacyShuffleJson = "{"localDirs": ["/bippy", "/flippy"], " +

""subDirsPerLocalDir": 7, "shuffleManager": "hash"}";

assertEquals(shuffleInfo, mapper.readValue(legacyShuffleJson, ExecutorShuffleInfo.class));

}


   Like      Feedback      org.apache.spark.network.shuffle.ExternalShuffleBlockResolver.AppExecId


 Sample 364. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.protocol.ExecutorShuffleInfo

  public void jsonSerializationOfExecutorRegistration() throws IOException {

ObjectMapper mapper = new ObjectMapper();

AppExecId appId = new AppExecId("foo", "bar");

String appIdJson = mapper.writeValueAsString(appId);

AppExecId parsedAppId = mapper.readValue(appIdJson, AppExecId.class);

assertEquals(parsedAppId, appId);



ExecutorShuffleInfo shuffleInfo =

new ExecutorShuffleInfo(new String[]{"/bippy", "/flippy"}, 7, "hash");

String shuffleJson = mapper.writeValueAsString(shuffleInfo);

ExecutorShuffleInfo parsedShuffleInfo =

mapper.readValue(shuffleJson, ExecutorShuffleInfo.class);

assertEquals(parsedShuffleInfo, shuffleInfo);



String legacyAppIdJson = "{"appId":"foo", "execId":"bar"}";

assertEquals(appId, mapper.readValue(legacyAppIdJson, AppExecId.class));

String legacyShuffleJson = "{"localDirs": ["/bippy", "/flippy"], " +

""subDirsPerLocalDir": 7, "shuffleManager": "hash"}";

assertEquals(shuffleInfo, mapper.readValue(legacyShuffleJson, ExecutorShuffleInfo.class));

}


   Like      Feedback      org.apache.spark.network.shuffle.protocol.ExecutorShuffleInfo


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 365. Code Sample / Example / Snippet of org.apache.spark.network.server.RpcHandler

  public void testNoSaslServer() {

RpcHandler handler = new TestRpcHandler();

TransportContext context = new TransportContext(conf, handler);

clientFactory = context.createClientFactory(

Lists.<TransportClientBootstrap>newArrayList(

new SaslClientBootstrap(conf, "app-1", secretKeyHolder)));

TransportServer server = context.createServer();

try {

clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());

} catch (Exception e) {

assertTrue(e.getMessage(), e.getMessage().contains("Digest-challenge format violation"));

} finally {

server.close();

}

}


   Like      Feedback      org.apache.spark.network.server.RpcHandler


 Sample 366. Code Sample / Example / Snippet of org.apache.spark.network.server.TransportServer

  public void testNoSaslServer() {

RpcHandler handler = new TestRpcHandler();

TransportContext context = new TransportContext(conf, handler);

clientFactory = context.createClientFactory(

Lists.<TransportClientBootstrap>newArrayList(

new SaslClientBootstrap(conf, "app-1", secretKeyHolder)));

TransportServer server = context.createServer();

try {

clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());

} catch (Exception e) {

assertTrue(e.getMessage(), e.getMessage().contains("Digest-challenge format violation"));

} finally {

server.close();

}

}


   Like      Feedback      org.apache.spark.network.server.TransportServer


 Sample 367. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.BlockFetchingListener

  public void testNoFailures() throws IOException {

BlockFetchingListener listener = mock(BlockFetchingListener.class);



List<? extends Map<String, Object>> interactions = Arrays.asList(

ImmutableMap.<String, Object>builder()

.put("b0", block0)

.put("b1", block1)

.build()

);



performInteractions(interactions, listener);



verify(listener).onBlockFetchSuccess("b0", block0);

verify(listener).onBlockFetchSuccess("b1", block1);

verifyNoMoreInteractions(listener);

}


   Like      Feedback      org.apache.spark.network.shuffle.BlockFetchingListener


 Sample 368. Code Sample / Example / Snippet of org.apache.spark.network.client.TransportClient

  public void testGoodClient() throws IOException {

clientFactory = context.createClientFactory(

Lists.<TransportClientBootstrap>newArrayList(

new SaslClientBootstrap(conf, "app-1", secretKeyHolder)));



TransportClient client = clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());

String msg = "Hello, World!";

ByteBuffer resp = client.sendRpcSync(JavaUtils.stringToBytes(msg), TIMEOUT_MS);

assertEquals(msg, JavaUtils.bytesToString(resp));

}


   Like      Feedback      org.apache.spark.network.client.TransportClient


 Sample 369. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.ExternalShuffleBlockResolver

  public void noCleanupAndCleanup() throws IOException {

TestShuffleDataContext dataContext = createSomeData();



ExternalShuffleBlockResolver resolver =

new ExternalShuffleBlockResolver(conf, null, sameThreadExecutor);

resolver.registerExecutor("app", "exec0", dataContext.createExecutorInfo("shuffleMgr"));

resolver.applicationRemoved("app", false /* cleanup */);



assertStillThere(dataContext);



resolver.registerExecutor("app", "exec1", dataContext.createExecutorInfo("shuffleMgr"));

resolver.applicationRemoved("app", true /* cleanup */);



assertCleanedUp(dataContext);

}


   Like      Feedback      org.apache.spark.network.shuffle.ExternalShuffleBlockResolver


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

  public void handleSuccessfulFetch() throws Exception {

StreamChunkId streamChunkId = new StreamChunkId(1, 0);



TransportResponseHandler handler = new TransportResponseHandler(new LocalChannel());

ChunkReceivedCallback callback = mock(ChunkReceivedCallback.class);

handler.addFetchRequest(streamChunkId, callback);

assertEquals(1, handler.numOutstandingRequests());



handler.handle(new ChunkFetchSuccess(streamChunkId, new TestManagedBuffer(123)));

verify(callback, times(1)).onSuccess(eq(0), (ManagedBuffer) any());

assertEquals(0, handler.numOutstandingRequests());

}


   Like      Feedback      org.apache.spark.network.protocol.StreamChunkId


 Sample 371. Code Sample / Example / Snippet of org.apache.storm.topology.BasicOutputCollector

  public void shouldEmitSomethingIfTickTupleIsReceived() {

Tuple tickTuple = MockTupleHelpers.mockTickTuple();

BasicOutputCollector collector = mock(BasicOutputCollector.class);

TotalRankingsBolt bolt = new TotalRankingsBolt();



bolt.execute(tickTuple, collector);



verify(collector).emit(any(Values.class));

}


   Like      Feedback      org.apache.storm.topology.BasicOutputCollector


 Sample 372. Code Sample / Example / Snippet of org.apache.storm.starter.tools.Rankings

  public void copyConstructorShouldReturnCopy(int topN, List<Rankable> rankables) {

Rankings rankings = new Rankings(topN);

for (Rankable r : rankables) {

rankings.updateWith(r);

}



Rankings copy = new Rankings(rankings);



assertThat(copy.maxSize()).isEqualTo(rankings.maxSize());

assertThat(copy.getRankings()).isEqualTo(rankings.getRankings());

}


   Like      Feedback      org.apache.storm.starter.tools.Rankings


 Sample 373. Code Sample / Example / Snippet of org.apache.storm.Config

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

TopologyBuilder builder = new TopologyBuilder();

builder.setSpout("spout", new RandomIntegerSpout());

builder.setBolt("sumbolt", new WindowSumBolt().withWindow(new Count(5), new Count(3))

.withMessageIdField("msgid"), 1).shuffleGrouping("spout");

builder.setBolt("printer", new PrinterBolt(), 1).shuffleGrouping("sumbolt");

Config conf = new Config();

conf.setDebug(false);

if (args != null && args.length > 0) {

conf.setNumWorkers(1);

StormSubmitter.submitTopologyWithProgressBar(args[0], conf, builder.createTopology());

} else {

LocalCluster cluster = new LocalCluster();

StormTopology topology = builder.createTopology();

cluster.submitTopology("test", conf, topology);

Utils.sleep(40000);

cluster.killTopology("test");

cluster.shutdown();

}

}


   Like      Feedback      org.apache.storm.Config


 Sample 374. Code Sample / Example / Snippet of org.apache.storm.topology.TopologyBuilder

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

TopologyBuilder builder = new TopologyBuilder();

builder.setSpout("spout", new RandomIntegerSpout());

builder.setBolt("sumbolt", new WindowSumBolt().withWindow(new Count(5), new Count(3))

.withMessageIdField("msgid"), 1).shuffleGrouping("spout");

builder.setBolt("printer", new PrinterBolt(), 1).shuffleGrouping("sumbolt");

Config conf = new Config();

conf.setDebug(false);

if (args != null && args.length > 0) {

conf.setNumWorkers(1);

StormSubmitter.submitTopologyWithProgressBar(args[0], conf, builder.createTopology());

} else {

LocalCluster cluster = new LocalCluster();

StormTopology topology = builder.createTopology();

cluster.submitTopology("test", conf, topology);

Utils.sleep(40000);

cluster.killTopology("test");

cluster.shutdown();

}

}


   Like      Feedback      org.apache.storm.topology.TopologyBuilder


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

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

TopologyBuilder builder = new TopologyBuilder();

builder.setSpout("spout", new RandomIntegerSpout());

builder.setBolt("sumbolt", new WindowSumBolt().withWindow(new Count(5), new Count(3))

.withMessageIdField("msgid"), 1).shuffleGrouping("spout");

builder.setBolt("printer", new PrinterBolt(), 1).shuffleGrouping("sumbolt");

Config conf = new Config();

conf.setDebug(false);

if (args != null && args.length > 0) {

conf.setNumWorkers(1);

StormSubmitter.submitTopologyWithProgressBar(args[0], conf, builder.createTopology());

} else {

LocalCluster cluster = new LocalCluster();

StormTopology topology = builder.createTopology();

cluster.submitTopology("test", conf, topology);

Utils.sleep(40000);

cluster.killTopology("test");

cluster.shutdown();

}

}


   Like      Feedback      org.apache.storm.LocalCluster


 Sample 376. Code Sample / Example / Snippet of org.apache.storm.testing.MemoryTransactionalSpout

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

MemoryTransactionalSpout spout = new MemoryTransactionalSpout(DATA, new Fields("word"), PARTITION_TAKE_PER_BATCH);

TransactionalTopologyBuilder builder = new TransactionalTopologyBuilder("global-count", "spout", spout, 3);

builder.setBolt("partial-count", new BatchCount(), 5).noneGrouping("spout");

builder.setBolt("sum", new UpdateGlobalCount()).globalGrouping("partial-count");



LocalCluster cluster = new LocalCluster();



Config config = new Config();

config.setDebug(true);

config.setMaxSpoutPending(3);



cluster.submitTopology("global-count-topology", config, builder.buildTopology());



Thread.sleep(3000);

cluster.shutdown();

}


   Like      Feedback      org.apache.storm.testing.MemoryTransactionalSpout


 Sample 377. Code Sample / Example / Snippet of org.apache.storm.transactional.TransactionalTopologyBuilder

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

MemoryTransactionalSpout spout = new MemoryTransactionalSpout(DATA, new Fields("word"), PARTITION_TAKE_PER_BATCH);

TransactionalTopologyBuilder builder = new TransactionalTopologyBuilder("global-count", "spout", spout, 3);

builder.setBolt("partial-count", new BatchCount(), 5).noneGrouping("spout");

builder.setBolt("sum", new UpdateGlobalCount()).globalGrouping("partial-count");



LocalCluster cluster = new LocalCluster();



Config config = new Config();

config.setDebug(true);

config.setMaxSpoutPending(3);



cluster.submitTopology("global-count-topology", config, builder.buildTopology());



Thread.sleep(3000);

cluster.shutdown();

}


   Like      Feedback      org.apache.storm.transactional.TransactionalTopologyBuilder


 Sample 378. Code Sample / Example / Snippet of org.apache.storm.trident.windowing.WindowsStoreFactory

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

Config conf = new Config();

WindowsStoreFactory mapState = new InMemoryWindowsStoreFactory();



if (args.length == 0) {

List<? extends WindowConfig> list = Arrays.asList(

SlidingCountWindow.of(1000, 100)

,TumblingCountWindow.of(1000)

,SlidingDurationWindow.of(new BaseWindowedBolt.Duration(6, TimeUnit.SECONDS), new BaseWindowedBolt.Duration(3, TimeUnit.SECONDS))

,TumblingDurationWindow.of(new BaseWindowedBolt.Duration(3, TimeUnit.SECONDS))

);



for (WindowConfig windowConfig : list) {

LocalCluster cluster = new LocalCluster();

cluster.submitTopology("wordCounter", conf, buildTopology(mapState, windowConfig));

Utils.sleep(60 * 1000);

cluster.shutdown();

}

System.exit(0);

} else {

conf.setNumWorkers(3);

StormSubmitter.submitTopologyWithProgressBar(args[0], conf, buildTopology(mapState, SlidingCountWindow.of(1000, 100)));

}

}


   Like      Feedback      org.apache.storm.trident.windowing.WindowsStoreFactory


 Sample 379. Code Sample / Example / Snippet of org.apache.storm.trident.Stream

    public static StormTopology buildTopology(WindowsStoreFactory windowStore, WindowConfig windowConfig) throws Exception {

FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 3, new Values("the cow jumped over the moon"),

new Values("the man went to the store and bought some candy"), new Values("four score and seven years ago"),

new Values("how many apples can you eat"), new Values("to be or not to be the person"));

spout.setCycle(true);



TridentTopology topology = new TridentTopology();



Stream stream = topology.newStream("spout1", spout).parallelismHint(16).each(new Fields("sentence"),

new Split(), new Fields("word"))

.window(windowConfig, windowStore, new Fields("word"), new CountAsAggregator(), new Fields("count"))

.peek(new Consumer() {

@Override

public void accept(TridentTuple input) {

LOG.info("Received tuple: [{}]", input);

}

});



return topology.build();

}


   Like      Feedback      org.apache.storm.trident.Stream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 380. Code Sample / Example / Snippet of org.apache.storm.trident.TridentTopology

    public static StormTopology buildTopology(WindowsStoreFactory windowStore, WindowConfig windowConfig) throws Exception {

FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 3, new Values("the cow jumped over the moon"),

new Values("the man went to the store and bought some candy"), new Values("four score and seven years ago"),

new Values("how many apples can you eat"), new Values("to be or not to be the person"));

spout.setCycle(true);



TridentTopology topology = new TridentTopology();



Stream stream = topology.newStream("spout1", spout).parallelismHint(16).each(new Fields("sentence"),

new Split(), new Fields("word"))

.window(windowConfig, windowStore, new Fields("word"), new CountAsAggregator(), new Fields("count"))

.peek(new Consumer() {

@Override

public void accept(TridentTuple input) {

LOG.info("Received tuple: [{}]", input);

}

});



return topology.build();

}


   Like      Feedback      org.apache.storm.trident.TridentTopology


 Sample 381. Code Sample / Example / Snippet of org.apache.storm.kafka.ZkHosts

    private TransactionalTridentKafkaSpout createKafkaSpout() {

ZkHosts hosts = new ZkHosts(zkUrl);

TridentKafkaConfig config = new TridentKafkaConfig(hosts, "test");

config.scheme = new SchemeAsMultiScheme(new StringScheme());



config.startOffsetTime = kafka.api.OffsetRequest.LatestTime();

return new TransactionalTridentKafkaSpout(config);

}


   Like      Feedback      org.apache.storm.kafka.ZkHosts


 Sample 382. Code Sample / Example / Snippet of org.apache.storm.kafka.trident.TridentKafkaConfig

    private TransactionalTridentKafkaSpout createKafkaSpout() {

ZkHosts hosts = new ZkHosts(zkUrl);

TridentKafkaConfig config = new TridentKafkaConfig(hosts, "test");

config.scheme = new SchemeAsMultiScheme(new StringScheme());



config.startOffsetTime = kafka.api.OffsetRequest.LatestTime();

return new TransactionalTridentKafkaSpout(config);

}


   Like      Feedback      org.apache.storm.kafka.trident.TridentKafkaConfig


 Sample 383. Code Sample / Example / Snippet of org.apache.storm.kafka.bolt.KafkaBolt

    public StormTopology buildProducerTopology(Properties prop) {

TopologyBuilder builder = new TopologyBuilder();

builder.setSpout("spout", new RandomSentenceSpout(), 2);

KafkaBolt bolt = new KafkaBolt().withProducerProperties(prop)

.withTopicSelector(new DefaultTopicSelector("test"))

.withTupleToKafkaMapper(new FieldNameBasedTupleToKafkaMapper("key", "word"));

builder.setBolt("forwardToKafka", bolt, 1).shuffleGrouping("spout");

return builder.createTopology();

}


   Like      Feedback      org.apache.storm.kafka.bolt.KafkaBolt


 Sample 384. Code Sample / Example / Snippet of org.apache.storm.trident.TridentState

  public static StormTopology buildTopology(LocalDRPC drpc) {

FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 3, new Values("the cow jumped over the moon"),

new Values("the man went to the store and bought some candy"), new Values("four score and seven years ago"),

new Values("how many apples can you eat"), new Values("to be or not to be the person"));

spout.setCycle(true);



TridentTopology topology = new TridentTopology();

TridentState wordCounts = topology.newStream("spout1", spout).parallelismHint(16).each(new Fields("sentence"),

new Split(), new Fields("word")).groupBy(new Fields("word")).persistentAggregate(new MemoryMapState.Factory(),

new Count(), new Fields("count")).parallelismHint(16);



topology.newDRPCStream("words", drpc).each(new Fields("args"), new Split(), new Fields("word")).groupBy(new Fields(

"word")).stateQuery(wordCounts, new Fields("word"), new MapGet(), new Fields("count")).each(new Fields("count"),

new FilterNull()).aggregate(new Fields("count"), new Sum(), new Fields("sum"));

return topology.build();

}


   Like      Feedback      org.apache.storm.trident.TridentState


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 385. Code Sample / Example / Snippet of org.apache.storm.topology.base.BaseWindowedBolt

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

TopologyBuilder builder = new TopologyBuilder();

BaseWindowedBolt bolt = new SlidingWindowSumBolt()

.withWindow(new Duration(5, TimeUnit.SECONDS), new Duration(3, TimeUnit.SECONDS))

.withTimestampField("ts")

.withLag(new Duration(5, TimeUnit.SECONDS));

builder.setSpout("integer", new RandomIntegerSpout(), 1);

builder.setBolt("slidingsum", bolt, 1).shuffleGrouping("integer");

builder.setBolt("printer", new PrinterBolt(), 1).shuffleGrouping("slidingsum");

Config conf = new Config();

conf.setDebug(true);



if (args != null && args.length > 0) {

conf.setNumWorkers(1);

StormSubmitter.submitTopologyWithProgressBar(args[0], conf, builder.createTopology());

} else {

LocalCluster cluster = new LocalCluster();

cluster.submitTopology("test", conf, builder.createTopology());

Utils.sleep(40000);

cluster.killTopology("test");

cluster.shutdown();

}

}


   Like      Feedback      org.apache.storm.topology.base.BaseWindowedBolt


 Sample 386. Code Sample / Example / Snippet of org.apache.storm.drpc.LinearDRPCTopologyBuilder

  public static LinearDRPCTopologyBuilder construct() {

LinearDRPCTopologyBuilder builder = new LinearDRPCTopologyBuilder("reach");

builder.addBolt(new GetTweeters(), 4);

builder.addBolt(new GetFollowers(), 12).shuffleGrouping();

builder.addBolt(new PartialUniquer(), 6).fieldsGrouping(new Fields("id", "follower"));

builder.addBolt(new CountAggregator(), 3).fieldsGrouping(new Fields("id"));

return builder;

}


   Like      Feedback      org.apache.storm.drpc.LinearDRPCTopologyBuilder


 Sample 387. Code Sample / Example / Snippet of org.apache.storm.starter.bolt.IntermediateRankingsBolt

  public void shouldEmitSomethingIfTickTupleIsReceived() {

Tuple tickTuple = MockTupleHelpers.mockTickTuple();

BasicOutputCollector collector = mock(BasicOutputCollector.class);

IntermediateRankingsBolt bolt = new IntermediateRankingsBolt();



bolt.execute(tickTuple, collector);



verify(collector).emit(any(Values.class));

}


   Like      Feedback      org.apache.storm.starter.bolt.IntermediateRankingsBolt


 Sample 388. Code Sample / Example / Snippet of org.apache.storm.starter.bolt.TotalRankingsBolt

  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.starter.bolt.TotalRankingsBolt


 Sample 389. Code Sample / Example / Snippet of org.apache.storm.starter.bolt.RollingCountBolt

  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.starter.bolt.RollingCountBolt


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 390. Code Sample / Example / Snippet of org.apache.storm.blobstore.AtomicOutputStream

    private static void createBlobWithContent(String blobKey, ClientBlobStore clientBlobStore, File file)

throws AuthorizationException, KeyAlreadyExistsException, IOException,KeyNotFoundException {

String stringBlobACL = "o::rwa";

AccessControl blobACL = BlobStoreAclHandler.parseAccessControl(stringBlobACL);

List<AccessControl> acls = new LinkedList<AccessControl>();

acls.add(blobACL); // more ACLs can be added here

SettableBlobMeta settableBlobMeta = new SettableBlobMeta(acls);

AtomicOutputStream blobStream = clientBlobStore.createBlob(blobKey,settableBlobMeta);

blobStream.write(readFile(file).toString().getBytes());

blobStream.close();

}


   Like      Feedback      org.apache.storm.blobstore.AtomicOutputStream


 Sample 391. Code Sample / Example / Snippet of org.apache.storm.transactional.TransactionAttempt

    public void execute(Tuple tuple, BasicOutputCollector collector) {

TransactionAttempt attempt = (TransactionAttempt) tuple.getValue(0);

int curr = tuple.getInteger(2);

Integer prev = tuple.getInteger(3);



int currBucket = curr / BUCKET_SIZE;

Integer prevBucket = null;

if (prev != null) {

prevBucket = prev / BUCKET_SIZE;

}



if (prevBucket == null) {

collector.emit(new Values(attempt, currBucket, 1));

}

else if (currBucket != prevBucket) {

collector.emit(new Values(attempt, currBucket, 1));

collector.emit(new Values(attempt, prevBucket, -1));

}

}


   Like      Feedback      org.apache.storm.transactional.TransactionAttempt


 Sample 392. Code Sample / Example / Snippet of org.apache.storm.starter.tools.Rankable

  public Object[][] duplicatesData() {

Rankable A1 = new RankableObjectWithFields("A", 1);

Rankable A2 = new RankableObjectWithFields("A", 2);

Rankable A3 = new RankableObjectWithFields("A", 3);

return new Object[][]{ { Lists.newArrayList(ANY_RANKABLE, ANY_RANKABLE, ANY_RANKABLE) }, { Lists.newArrayList(A1,

A2, A3) }, };

}


   Like      Feedback      org.apache.storm.starter.tools.Rankable


 Sample 393. Code Sample / Example / Snippet of org.apache.storm.starter.tools.RankableObjectWithFields

  public void toStringShouldContainStringRepresentationsOfObjectAndCount(Object obj, long count) {

RankableObjectWithFields r = new RankableObjectWithFields(obj, count);



String strRepresentation = r.toString();



assertThat(strRepresentation).contains(obj.toString()).contains("" + count);

}




   Like      Feedback      org.apache.storm.starter.tools.RankableObjectWithFields


 Sample 394. Code Sample / Example / Snippet of org.apache.storm.starter.tools.NthLastModifiedTimeTracker

  public void shouldReturnCorrectModifiedTimeEvenWhenNotYetMarkedAsModified(int secondsToAdvance) {

Time.startSimulating();

NthLastModifiedTimeTracker tracker = new NthLastModifiedTimeTracker(ANY_NUM_TIMES_TO_TRACK);



advanceSimulatedTimeBy(secondsToAdvance);

int seconds = tracker.secondsSinceOldestModification();



assertThat(seconds).isEqualTo(secondsToAdvance);



Time.stopSimulating();

}


   Like      Feedback      org.apache.storm.starter.tools.NthLastModifiedTimeTracker


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 395. Code Sample / Example / Snippet of org.apache.storm.kafka.trident.GlobalPartitionInformation

    public static GlobalPartitionInformation buildPartitionInfo(int numPartitions, int brokerPort) {

GlobalPartitionInformation globalPartitionInformation = new GlobalPartitionInformation(TOPIC);

for (int i = 0; i < numPartitions; i++) {

globalPartitionInformation.addPartition(i, Broker.fromString("broker-" + i + " :" + brokerPort));

}

return globalPartitionInformation;

}


   Like      Feedback      org.apache.storm.kafka.trident.GlobalPartitionInformation


 Sample 396. Code Sample / Example / Snippet of org.apache.storm.kafka.DynamicBrokersReader

    public void testErrorLogsWhenConfigIsMissing() throws Exception {

String connectionString = server.getConnectString();

Map conf = new HashMap();

conf.put(Config.STORM_ZOOKEEPER_SESSION_TIMEOUT, 1000);

conf.put(Config.STORM_ZOOKEEPER_RETRY_TIMES, 4);

conf.put(Config.STORM_ZOOKEEPER_RETRY_INTERVAL, 5);



DynamicBrokersReader dynamicBrokersReader1 = new DynamicBrokersReader(conf, connectionString, masterPath, topic);



}


   Like      Feedback      org.apache.storm.kafka.DynamicBrokersReader


 Sample 397. Code Sample / Example / Snippet of org.apache.storm.trident.topology.TransactionAttempt

    public void execute(Tuple tuple, BasicOutputCollector collector) {

TransactionAttempt attempt = (TransactionAttempt) tuple.getValue(0);

int curr = tuple.getInteger(2);

Integer prev = tuple.getInteger(3);



int currBucket = curr / BUCKET_SIZE;

Integer prevBucket = null;

if (prev != null) {

prevBucket = prev / BUCKET_SIZE;

}



if (prevBucket == null) {

collector.emit(new Values(attempt, currBucket, 1));

}

else if (currBucket != prevBucket) {

collector.emit(new Values(attempt, currBucket, 1));

collector.emit(new Values(attempt, prevBucket, -1));

}

}


   Like      Feedback      org.apache.storm.trident.topology.TransactionAttempt


 Sample 398. Code Sample / Example / Snippet of org.apache.storm.kafka.Partition

    public void generateTuplesWithMessageAndMetadataScheme() {

String value = "value";

Partition mockPartition = Mockito.mock(Partition.class);

mockPartition.partition = 0;

long offset = 0L;



MessageMetadataSchemeAsMultiScheme scheme = new MessageMetadataSchemeAsMultiScheme(new StringMessageAndMetadataScheme());



createTopicAndSendMessage(null, value);

ByteBufferMessageSet messageAndOffsets = getLastMessage();

for (MessageAndOffset msg : messageAndOffsets) {

Iterable<List<Object>> lists = KafkaUtils.generateTuples(scheme, msg.message(), mockPartition, offset);

List<Object> values = lists.iterator().next();

assertEquals("Message is incorrect", value, values.get(0));

assertEquals("Partition is incorrect", mockPartition.partition, values.get(1));

assertEquals("Offset is incorrect", offset, values.get(2));

}

}


   Like      Feedback      org.apache.storm.kafka.Partition


 Sample 399. Code Sample / Example / Snippet of org.apache.storm.kafka.PartitionManager.KafkaMessageId

    public void ack(Object msgId) {

KafkaMessageId id = (KafkaMessageId) msgId;

PartitionManager m = _coordinator.getManager(id.partition);

if (m != null) {

m.ack(id.offset);

}

}


   Like      Feedback      org.apache.storm.kafka.PartitionManager.KafkaMessageId


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 400. Code Sample / Example / Snippet of org.apache.storm.trident.state.StateFactory

    protected StormTopology getTopology() throws IOException {

final TridentTopology tridentTopology = new TridentTopology();

final SolrFieldsSpout spout = new SolrFieldsSpout();

final Stream stream = tridentTopology.newStream("SolrFieldsSpout", spout);

final StateFactory solrStateFactory = new SolrStateFactory(getSolrConfig(), getSolrMapper());

stream.partitionPersist(solrStateFactory, spout.getOutputFields(), new SolrUpdater(), new Fields());

return tridentTopology.build();

}


   Like      Feedback      org.apache.storm.trident.state.StateFactory


 Sample 401. Code Sample / Example / Snippet of org.apache.storm.solr.spout.SolrFieldsSpout

    protected StormTopology getTopology() throws IOException {

final TridentTopology tridentTopology = new TridentTopology();

final SolrFieldsSpout spout = new SolrFieldsSpout();

final Stream stream = tridentTopology.newStream("SolrFieldsSpout", spout);

final StateFactory solrStateFactory = new SolrStateFactory(getSolrConfig(), getSolrMapper());

stream.partitionPersist(solrStateFactory, spout.getOutputFields(), new SolrUpdater(), new Fields());

return tridentTopology.build();

}


   Like      Feedback      org.apache.storm.solr.spout.SolrFieldsSpout


 Sample 402. Code Sample / Example / Snippet of org.apache.storm.solr.spout.SolrJsonSpout

    protected StormTopology getTopology() throws IOException {

final TridentTopology topology = new TridentTopology();

final SolrJsonSpout spout = new SolrJsonSpout();

final Stream stream = topology.newStream("SolrJsonSpout", spout);

final StateFactory solrStateFactory = new SolrStateFactory(getSolrConfig(), getSolrMapper());

stream.partitionPersist(solrStateFactory, spout.getOutputFields(), new SolrUpdater(), new Fields());

return topology.build();

}


   Like      Feedback      org.apache.storm.solr.spout.SolrJsonSpout


 Sample 403. Code Sample / Example / Snippet of org.apache.storm.generated.StormTopology

    public void run(String[] args) throws Exception {

final StormTopology topology = getTopology();

final Config config = getConfig();



if (args.length == 0) {

submitTopologyLocalCluster(topology, config);

} else {

submitTopologyRemoteCluster(args[1], topology, config);

}

}


   Like      Feedback      org.apache.storm.generated.StormTopology


 Sample 404. Code Sample / Example / Snippet of static org.apache.storm.solr.schema.SolrFieldTypeFinder.FieldTypeWrapper

    private SolrInputDocument buildDocument(ITuple tuple) {

SolrInputDocument doc = new SolrInputDocument();



for (String tupleField : tuple.getFields()) {

FieldTypeWrapper fieldTypeWrapper = typeFinder.getFieldTypeWrapper(tupleField);

if (fieldTypeWrapper != null) {

FieldType fieldType = fieldTypeWrapper.getType();

if (fieldType.isMultiValued()) {

addMultivalueFieldToDoc(doc, tupleField, tuple);

} else {

addFieldToDoc(doc, tupleField, tuple);

}

} else {

log.debug("Field [{}] does NOT match static or dynamic field declared in schema. Not added to document", tupleField);

}

}

return doc;

}


   Like      Feedback      static org.apache.storm.solr.schema.SolrFieldTypeFinder.FieldTypeWrapper


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 405. Code Sample / Example / Snippet of org.apache.storm.solr.schema.FieldType

    private SolrInputDocument buildDocument(ITuple tuple) {

SolrInputDocument doc = new SolrInputDocument();



for (String tupleField : tuple.getFields()) {

FieldTypeWrapper fieldTypeWrapper = typeFinder.getFieldTypeWrapper(tupleField);

if (fieldTypeWrapper != null) {

FieldType fieldType = fieldTypeWrapper.getType();

if (fieldType.isMultiValued()) {

addMultivalueFieldToDoc(doc, tupleField, tuple);

} else {

addFieldToDoc(doc, tupleField, tuple);

}

} else {

log.debug("Field [{}] does NOT match static or dynamic field declared in schema. Not added to document", tupleField);

}

}

return doc;

}


   Like      Feedback      org.apache.storm.solr.schema.FieldType


 Sample 406. Code Sample / Example / Snippet of org.apache.storm.blobstore.BlobStoreFile

    public void testGetFileLength() throws IOException {

FileSystem fs = dfscluster.getFileSystem();

Map conf = new HashMap();

String validKey = "validkeyBasic";

String testString = "testingblob";

TestHdfsBlobStoreImpl hbs = new TestHdfsBlobStoreImpl(blobDir, conf, hadoopConf);

BlobStoreFile pfile = hbs.write(validKey, false);

SettableBlobMeta meta = new SettableBlobMeta();

meta.set_replication_factor(1);

pfile.setMetadata(meta);

OutputStream ios = pfile.getOutputStream();

ios.write(testString.getBytes(Charset.forName("UTF-8")));

ios.close();

assertEquals(testString.getBytes(Charset.forName("UTF-8")).length, pfile.getFileLength());

}


   Like      Feedback      org.apache.storm.blobstore.BlobStoreFile


 Sample 407. Code Sample / Example / Snippet of org.apache.calcite.linq4j.tree.BlockBuilder

  public static BlockStatement optimizeStatement(Statement statement) {

BlockBuilder b = new BlockBuilder(true);

if (!(statement instanceof BlockStatement)) {

b.add(statement);

} else {

BlockStatement bs = (BlockStatement) statement;

for (Statement stmt : bs.statements) {

b.add(stmt);

}

}

BlockStatement bs = b.toBlock();

return bs;

}




   Like      Feedback      org.apache.calcite.linq4j.tree.BlockBuilder


 Sample 408. Code Sample / Example / Snippet of org.apache.calcite.linq4j.tree.Expression

  public void prepareBuilder() {

b = new BlockBuilder(true);

}



@Test public void testReuseExpressionsFromUpperLevel() {

Expression x = b.append("x", Expressions.add(ONE, TWO));

BlockBuilder nested = new BlockBuilder(true, b);

Expression y = nested.append("y", Expressions.add(ONE, TWO));

nested.add(Expressions.return_(null, Expressions.add(y, y)));

b.add(nested.toBlock());

assertEquals(

"{ "

+ " final int x = 1 + 2; "

+ " { "

+ " return x + x; "

+ " } "

+ "} ",

b.toBlock().toString());

}




   Like      Feedback      org.apache.calcite.linq4j.tree.Expression


 Sample 409. Code Sample / Example / Snippet of java.lang.reflect.Type

  public static Type stripGenerics(Type type) {

if (type instanceof GenericArrayType) {

final Type componentType =

((GenericArrayType) type).getGenericComponentType();

return new ArrayType(stripGenerics(componentType));

} else if (type instanceof ParameterizedType) {

return ((ParameterizedType) type).getRawType();

} else {

return type;

}

}


   Like      Feedback      java.lang.reflect.Type


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 410. Code Sample / Example / Snippet of org.openjdk.jmh.runner.options.Options

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

Options opt = new OptionsBuilder()

.include(PreconditionTest.class.getSimpleName())

.addProfiler(GCProfiler.class)

.detectJvmArgs()

.build();



new Runner(opt).run();

}


   Like      Feedback      org.openjdk.jmh.runner.options.Options


 Sample 411. Code Sample / Example / Snippet of java.sql.Connection

  public String prepareBindExecute(HrConnection state) throws SQLException {

Connection con = state.con;

Statement st = null;

ResultSet rs = null;

String ename = null;

try {

final PreparedStatement ps =

con.prepareStatement("select name from emps where empid = ?");

st = ps;

ps.setInt(1, state.id);

rs = ps.executeQuery();

rs.next();

ename = rs.getString(1);

} finally {

close(rs, st);

}

return ename;

}


   Like      Feedback      java.sql.Connection


 Sample 412. Code Sample / Example / Snippet of java.sql.ResultSet

  public String prepareBindExecute(HrConnection state) throws SQLException {

Connection con = state.con;

Statement st = null;

ResultSet rs = null;

String ename = null;

try {

final PreparedStatement ps =

con.prepareStatement("select name from emps where empid = ?");

st = ps;

ps.setInt(1, state.id);

rs = ps.executeQuery();

rs.next();

ename = rs.getString(1);

} finally {

close(rs, st);

}

return ename;

}


   Like      Feedback      java.sql.ResultSet


 Sample 413. Code Sample / Example / Snippet of java.sql.Statement

  public ForStatement(List<DeclarationStatement> declarations,

Expression condition, Expression post, Statement body) {

super(ExpressionType.For, Void.TYPE);

assert declarations != null;

assert body != null;

this.declarations = declarations; // may be empty, not null

this.condition = condition; // may be null

this.post = post; // may be null

this.body = body; // may be empty block, not null

}



@Override public ForStatement accept(Visitor visitor) {

visitor = visitor.preVisit(this);

List<DeclarationStatement> decls1 =

Expressions.acceptDeclarations(declarations, visitor);

final Expression condition1 =

condition == null ? null : condition.accept(visitor);

final Expression post1 = post == null ? null : post.accept(visitor);

final Statement body1 = body.accept(visitor);

return visitor.visit(this, decls1, condition1, post1, body1);

}


   Like      Feedback      java.sql.Statement


 Sample 414. Code Sample / Example / Snippet of java.sql.PreparedStatement

  public String prepareBindExecute(HrConnection state) throws SQLException {

Connection con = state.con;

Statement st = null;

ResultSet rs = null;

String ename = null;

try {

final PreparedStatement ps =

con.prepareStatement("select name from emps where empid = ?");

st = ps;

ps.setInt(1, state.id);

rs = ps.executeQuery();

rs.next();

ename = rs.getString(1);

} finally {

close(rs, st);

}

return ename;

}


   Like      Feedback      java.sql.PreparedStatement


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 415. Code Sample / Example / Snippet of com.mongodb.DBObject

  private Enumerable<Object> find(DB mongoDb, String filterJson,

String projectJson, List<Map.Entry<String, Class>> fields) {

final DBCollection collection =

mongoDb.getCollection(collectionName);

final DBObject filter =

filterJson == null ? null : (DBObject) JSON.parse(filterJson);

final DBObject project =

projectJson == null ? null : (DBObject) JSON.parse(projectJson);

final Function1<DBObject, Object> getter = MongoEnumerator.getter(fields);

return new AbstractEnumerable<Object>() {

public Enumerator<Object> enumerator() {

final DBCursor cursor = collection.find(filter, project);

return new MongoEnumerator(cursor, getter);

}

};

}


   Like      Feedback      com.mongodb.DBObject


 Sample 416. Code Sample / Example / Snippet of com.mongodb.DBCollection

  private Enumerable<Object> find(DB mongoDb, String filterJson,

String projectJson, List<Map.Entry<String, Class>> fields) {

final DBCollection collection =

mongoDb.getCollection(collectionName);

final DBObject filter =

filterJson == null ? null : (DBObject) JSON.parse(filterJson);

final DBObject project =

projectJson == null ? null : (DBObject) JSON.parse(projectJson);

final Function1<DBObject, Object> getter = MongoEnumerator.getter(fields);

return new AbstractEnumerable<Object>() {

public Enumerator<Object> enumerator() {

final DBCursor cursor = collection.find(filter, project);

return new MongoEnumerator(cursor, getter);

}

};

}


   Like      Feedback      com.mongodb.DBCollection


 Sample 417. Code Sample / Example / Snippet of org.apache.calcite.rel.type.RelDataType

  public RelDataType getRowType(RelDataTypeFactory typeFactory) {

final RelDataType mapType =

typeFactory.createMapType(

typeFactory.createSqlType(SqlTypeName.VARCHAR),

typeFactory.createTypeWithNullability(

typeFactory.createSqlType(SqlTypeName.ANY), true));

return typeFactory.builder().add("_MAP", mapType).build();

}


   Like      Feedback      org.apache.calcite.rel.type.RelDataType


 Sample 418. Code Sample / Example / Snippet of org.apache.calcite.plan.RelOptCluster

  public RelNode toRel(

RelOptTable.ToRelContext context,

RelOptTable relOptTable) {

final RelOptCluster cluster = context.getCluster();

return new MongoTableScan(cluster, cluster.traitSetOf(MongoRel.CONVENTION),

relOptTable, this, null);

}


   Like      Feedback      org.apache.calcite.plan.RelOptCluster


 Sample 419. Code Sample / Example / Snippet of java.util.Map

  public Schema create(SchemaPlus parentSchema, String name,

Map<String, Object> operand) {

Map map = (Map) operand;

String host = (String) map.get("host");

String database = (String) map.get("database");

return new MongoSchema(host, database);

}


   Like      Feedback      java.util.Map


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 420. Code Sample / Example / Snippet of org.apache.calcite.plan.RelTraitSet

    public RelNode convert(RelNode rel) {

final Sort sort = (Sort) rel;

final RelTraitSet traitSet =

sort.getTraitSet().replace(out)

.replace(sort.getCollation());

return new MongoSort(rel.getCluster(), traitSet,

convert(sort.getInput(), traitSet.replace(RelCollations.EMPTY)),

sort.getCollation(), sort.offset, sort.fetch);

}


   Like      Feedback      org.apache.calcite.plan.RelTraitSet


 Sample 421. Code Sample / Example / Snippet of org.apache.calcite.rel.logical.LogicalFilter

    public RelNode convert(RelNode rel) {

final LogicalFilter filter = (LogicalFilter) rel;

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

return new MongoFilter(

rel.getCluster(),

traitSet,

convert(filter.getInput(), out),

filter.getCondition());

}


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


 Sample 422. Code Sample / Example / Snippet of org.apache.calcite.rel.logical.LogicalAggregate

    public RelNode convert(RelNode rel) {

final LogicalAggregate agg = (LogicalAggregate) rel;

final RelTraitSet traitSet =

agg.getTraitSet().replace(out);

try {

return new MongoAggregate(

rel.getCluster(),

traitSet,

convert(agg.getInput(), traitSet.simplify()),

agg.indicator,

agg.getGroupSet(),

agg.getGroupSets(),

agg.getAggCallList());

} catch (InvalidRelException e) {

LOGGER.warn(e.toString());

return null;

}

}


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


 Sample 423. Code Sample / Example / Snippet of org.apache.calcite.rex.RexNode

  public static final RelOptRule[] RULES = {

MongoSortRule.INSTANCE,

MongoFilterRule.INSTANCE,

MongoProjectRule.INSTANCE,

MongoAggregateRule.INSTANCE,

};



static String isItem(RexCall call) {

if (call.getOperator() != SqlStdOperatorTable.ITEM) {

return null;

}

final RexNode op0 = call.operands.get(0);

final RexNode op1 = call.operands.get(1);

if (op0 instanceof RexInputRef

&& ((RexInputRef) op0).getIndex() == 0

&& op1 instanceof RexLiteral

&& ((RexLiteral) op1).getValue2() instanceof String) {

return (String) ((RexLiteral) op1).getValue2();

}

return null;

}


   Like      Feedback      org.apache.calcite.rex.RexNode


 Sample 424. Code Sample / Example / Snippet of org.apache.calcite.rel.core.Sort

    public RelNode convert(RelNode rel) {

final Sort sort = (Sort) rel;

final RelTraitSet traitSet =

sort.getTraitSet().replace(out)

.replace(sort.getCollation());

return new MongoSort(rel.getCluster(), traitSet,

convert(sort.getInput(), traitSet.replace(RelCollations.EMPTY)),

sort.getCollation(), sort.offset, sort.fetch);

}


   Like      Feedback      org.apache.calcite.rel.core.Sort


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 425. Code Sample / Example / Snippet of org.apache.calcite.linq4j.tree.Primitive

  public static Type box(Type type) {

Primitive primitive = Primitive.of(type);

if (primitive != null) {

return primitive.boxClass;

} else {

return type;

}

}


   Like      Feedback      org.apache.calcite.linq4j.tree.Primitive


 Sample 426. Code Sample / Example / Snippet of org.apache.calcite.plan.Convention

public interface MongoRel extends RelNode {

void implement(Implementor implementor);



Convention CONVENTION = new Convention.Impl("MONGO", MongoRel.class);



class Implementor {

final List<Pair<String, String>> list =

new ArrayList<Pair<String, String>>();



RelOptTable table;

MongoTable mongoTable;



public void add(String findOp, String aggOp) {

list.add(Pair.of(findOp, aggOp));

}



public void visitChild(int ordinal, RelNode input) {

assert ordinal == 0;

((MongoRel) input).implement(this);

}

}

}


   Like      Feedback      org.apache.calcite.plan.Convention


 Sample 427. Code Sample / Example / Snippet of com.mongodb.MongoClient

  public MongoSchema(String host, String database) {

super();

try {

MongoClient mongo = new MongoClient(host);

this.mongoDb = mongo.getDB(database);

} catch (Exception e) {

throw new RuntimeException(e);

}

}


   Like      Feedback      com.mongodb.MongoClient


 Sample 428. Code Sample / Example / Snippet of org.apache.calcite.rel.core.TableScan

  public RelNode toRel(RelOptTable.ToRelContext context,

RelOptTable relOptTable) {

final RelOptCluster cluster = context.getCluster();

final TableScan scan = LogicalTableScan.create(cluster, relOptTable);

return DruidQuery.create(cluster,

cluster.traitSetOf(BindableConvention.INSTANCE), relOptTable, this,

ImmutableList.<RelNode>of(scan));

}


   Like      Feedback      org.apache.calcite.rel.core.TableScan


 Sample 429. Code Sample / Example / Snippet of static org.apache.calcite.runtime.HttpUtils.post

  public ForStatement visit(ForStatement forStatement,

List<DeclarationStatement> declarations, Expression condition,

Expression post, Statement body) {

return declarations.equals(forStatement.declarations)

&& condition == forStatement.condition

&& post == forStatement.post

&& body == forStatement.body

? forStatement

: Expressions.for_(declarations, condition, post, body);

}


   Like      Feedback      static org.apache.calcite.runtime.HttpUtils.post


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 430. Code Sample / Example / Snippet of com.fasterxml.jackson.core.JsonToken

  private void expectScalarField(JsonParser parser, String name)

throws IOException {

expect(parser, JsonToken.FIELD_NAME);

if (!parser.getCurrentName().equals(name)) {

throw new RuntimeException("expected field " + name + ", got "

+ parser.getCurrentName());

}

final JsonToken t = parser.nextToken();

switch (t) {

case VALUE_NULL:

case VALUE_FALSE:

case VALUE_TRUE:

case VALUE_NUMBER_INT:

case VALUE_NUMBER_FLOAT:

case VALUE_STRING:

break;

default:

throw new RuntimeException("expected scalar field, got " + t);

}

}


   Like      Feedback      com.fasterxml.jackson.core.JsonToken


 Sample 431. Code Sample / Example / Snippet of java.util.Random

  public Enumerable<Object[]> scan(DataContext root) {

final Random random = seed >= 0 ? new Random(seed) : new Random();

final Maze maze = new Maze(width, height);

final PrintWriter pw = new PrintWriter(System.out);

maze.layout(random, pw);

if (Maze.DEBUG) {

maze.print(pw, true);

}

return new AbstractEnumerable<Object[]>() {

public Enumerator<Object[]> enumerator() {

final Set<Integer> solutionSet;

if (solution) {

solutionSet = maze.solve(0, 0);

} else {

solutionSet = null;

}

return Linq4j.transform(maze.enumerator(solutionSet),

new Function1<String, Object[]>() {

public Object[] apply(String s) {

return new Object[] {s};

}

});

}

};

}


   Like      Feedback      java.util.Random


 Sample 432. Code Sample / Example / Snippet of java.io.PrintWriter

  public Enumerable<Object[]> scan(DataContext root) {

final Random random = seed >= 0 ? new Random(seed) : new Random();

final Maze maze = new Maze(width, height);

final PrintWriter pw = new PrintWriter(System.out);

maze.layout(random, pw);

if (Maze.DEBUG) {

maze.print(pw, true);

}

return new AbstractEnumerable<Object[]>() {

public Enumerator<Object[]> enumerator() {

final Set<Integer> solutionSet;

if (solution) {

solutionSet = maze.solve(0, 0);

} else {

solutionSet = null;

}

return Linq4j.transform(maze.enumerator(solutionSet),

new Function1<String, Object[]>() {

public Object[] apply(String s) {

return new Object[] {s};

}

});

}

};

}


   Like      Feedback      java.io.PrintWriter


 Sample 433. Code Sample / Example / Snippet of java.net.URL

  private String resourcePath(String path) {

final URL url = CsvTest.class.getResource("/" + path);

String s = url.toString();

if (s.startsWith("file:")) {

s = s.substring("file:".length());

}

return s;

}


   Like      Feedback      java.net.URL


 Sample 434. Code Sample / Example / Snippet of org.apache.calcite.rel.type.RelProtoDataType

  public CsvTable create(SchemaPlus schema, String name,

Map<String, Object> operand, RelDataType rowType) {

String fileName = (String) operand.get("file");

File file = new File(fileName);

final File base =

(File) operand.get(ModelHandler.ExtraOperand.BASE_DIRECTORY.camelName);

if (base != null && !file.isAbsolute()) {

file = new File(base, fileName);

}

final RelProtoDataType protoRowType =

rowType != null ? RelDataTypeImpl.proto(rowType) : null;

return new CsvScannableTable(file, protoRowType);

}


   Like      Feedback      org.apache.calcite.rel.type.RelProtoDataType


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 435. Code Sample / Example / Snippet of org.apache.calcite.adapter.enumerable.PhysType

  public Result implement(EnumerableRelImplementor implementor, Prefer pref) {

PhysType physType =

PhysTypeImpl.of(

implementor.getTypeFactory(),

getRowType(),

pref.preferArray());



if (table instanceof JsonTable) {

return implementor.result(

physType,

Blocks.toBlock(

Expressions.call(table.getExpression(JsonTable.class),

"enumerable")));

}

return implementor.result(

physType,

Blocks.toBlock(

Expressions.call(table.getExpression(CsvTranslatableTable.class),

"project", Expressions.constant(fields))));

}


   Like      Feedback      org.apache.calcite.adapter.enumerable.PhysType


 Sample 436. Code Sample / Example / Snippet of java.util.TimeZone

  private static final FastDateFormat TIME_FORMAT_TIMESTAMP;



static {

TimeZone gmt = TimeZone.getTimeZone("GMT");

TIME_FORMAT_DATE = FastDateFormat.getInstance("yyyy-MM-dd", gmt);

TIME_FORMAT_TIME = FastDateFormat.getInstance("HH:mm:ss", gmt);

TIME_FORMAT_TIMESTAMP =

FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss", gmt);

}


   Like      Feedback      java.util.TimeZone


 Sample 437. Code Sample / Example / Snippet of org.apache.calcite.rex.RexCall

  private boolean addFilter(RexNode filter, Object[] filterValues) {

if (filter.isA(SqlKind.EQUALS)) {

final RexCall call = (RexCall) filter;

RexNode left = call.getOperands().get(0);

if (left.isA(SqlKind.CAST)) {

left = ((RexCall) left).operands.get(0);

}

final RexNode right = call.getOperands().get(1);

if (left instanceof RexInputRef

&& right instanceof RexLiteral) {

final int index = ((RexInputRef) left).getIndex();

if (filterValues[index] == null) {

filterValues[index] = ((RexLiteral) right).getValue2().toString();

return true;

}

}

}

return false;

}


   Like      Feedback      org.apache.calcite.rex.RexCall


 Sample 438. Code Sample / Example / Snippet of com.fasterxml.jackson.databind.ObjectMapper

  public JsonEnumerator(File file) {

try {

final ObjectMapper mapper = new ObjectMapper();

mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);

List<Object> list = mapper.readValue(file, List.class);

enumerator = Linq4j.enumerator(list);

} catch (IOException e) {

throw new RuntimeException(e);

}

}


   Like      Feedback      com.fasterxml.jackson.databind.ObjectMapper


 Sample 439. Code Sample / Example / Snippet of java.io.File

  public Schema create(SchemaPlus parentSchema, String name,

Map<String, Object> operand) {

final String directory = (String) operand.get("directory");

final File base =

(File) operand.get(ModelHandler.ExtraOperand.BASE_DIRECTORY.camelName);

File directoryFile = new File(directory);

if (base != null && !directoryFile.isAbsolute()) {

directoryFile = new File(base, directory);

}

String flavorName = (String) operand.get("flavor");

CsvTable.Flavor flavor;

if (flavorName == null) {

flavor = CsvTable.Flavor.SCANNABLE;

} else {

flavor = CsvTable.Flavor.valueOf(flavorName.toUpperCase());

}

return new CsvSchema(directoryFile, flavor);

}


   Like      Feedback      java.io.File


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 440. Code Sample / Example / Snippet of static org.hamcrest.CoreMatchers.not

  public ParameterExpression(int modifier, Type type, String name) {

super(ExpressionType.Parameter, type);

assert name != null : "name should not be null";

assert Character.isJavaIdentifierStart(name.charAt(0))

: "parameter name should be valid java identifier: "

+ name + ". The first character is invalid.";

this.modifier = modifier;

this.name = name;

}


   Like      Feedback      static org.hamcrest.CoreMatchers.not


 Sample 441. Code Sample / Example / Snippet of org.elasticsearch.client.transport.TransportClient

  private void open(List<InetSocketAddress> transportAddresses, Map<String, String> userConfig) {

final List<TransportAddress> transportNodes = new ArrayList<>(transportAddresses.size());

for (InetSocketAddress address : transportAddresses) {

transportNodes.add(new InetSocketTransportAddress(address));

}



Settings settings = Settings.settingsBuilder().put(userConfig).build();



final TransportClient transportClient = TransportClient.builder().settings(settings).build();

for (TransportAddress transport : transportNodes) {

transportClient.addTransportAddress(transport);

}



final List<DiscoveryNode> nodes = ImmutableList.copyOf(transportClient.connectedNodes());

if (nodes.isEmpty()) {

throw new RuntimeException("Cannot connect to any elasticsearch nodes");

}



client = transportClient;

}


   Like      Feedback      org.elasticsearch.client.transport.TransportClient


 Sample 442. Code Sample / Example / Snippet of java.util.Calendar

  private SparkHandlerImpl() {

classServer = new HttpServer(CLASS_DIR);



classServer.start();

System.setProperty("spark.repl.class.uri", classServer.uri());



final Calendar calendar = Calendar.getInstance();

classId = new AtomicInteger(

calendar.get(Calendar.HOUR_OF_DAY) * 10000

+ calendar.get(Calendar.MINUTE) * 100

+ calendar.get(Calendar.SECOND));

}


   Like      Feedback      java.util.Calendar


 Sample 443. Code Sample / Example / Snippet of org.apache.calcite.rel.logical.LogicalValues

    private MongoValuesRule(MongoConvention out) {

super(

LogicalValues.class,

Convention.NONE,

out,

"MongoValuesRule");

}



@Override public RelNode convert(RelNode rel) {

LogicalValues valuesRel = (LogicalValues) rel;

return new MongoValuesRel(

valuesRel.getCluster(),

valuesRel.getRowType(),

valuesRel.getTuples(),

valuesRel.getTraitSet().plus(out));

}


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


 Sample 444. Code Sample / Example / Snippet of org.apache.calcite.rel.logical.LogicalCalc

    public RelNode convert(RelNode rel) {

final LogicalCalc calc = (LogicalCalc) rel;



if (RexMultisetUtil.containsMultiset(calc.getProgram())) {

return null;

}



return new MongoCalcRel(

rel.getCluster(),

rel.getTraitSet().replace(out),

convert(

calc.getChild(),

calc.getTraitSet().replace(out)),

calc.getProgram(),

Project.Flags.Boxed);

}


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


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 445. Code Sample / Example / Snippet of org.apache.calcite.adapter.jdbc.JdbcImplementor

  private String generateSql(SqlDialect dialect) {

final JdbcImplementor jdbcImplementor =

new JdbcImplementor(dialect,

(JavaTypeFactory) getCluster().getTypeFactory());

final JdbcImplementor.Result result =

jdbcImplementor.visitChild(0, getInput());

return result.asQuery().toSqlString(dialect).getSql();

}


   Like      Feedback      org.apache.calcite.adapter.jdbc.JdbcImplementor


 Sample 446. Code Sample / Example / Snippet of org.apache.calcite.rex.RexInputRef

    private String compareFieldWithLiteral(RexNode left, RexNode right, List<String> fieldNames) {

if (left.isA(SqlKind.CAST)) {

left = ((RexCall) left).getOperands().get(0);

}



if (left.isA(SqlKind.INPUT_REF) && right.isA(SqlKind.LITERAL)) {

final RexInputRef left1 = (RexInputRef) left;

String name = fieldNames.get(left1.getIndex());

return name;

} else {

return null;

}

}


   Like      Feedback      org.apache.calcite.rex.RexInputRef


 Sample 447. Code Sample / Example / Snippet of org.apache.calcite.adapter.enumerable.EnumerableLimit

    public void onMatch(RelOptRuleCall call) {

final EnumerableLimit limit = call.rel(0);

final RelNode converted = convert(limit);

if (converted != null) {

call.transformTo(converted);

}

}


   Like      Feedback      org.apache.calcite.adapter.enumerable.EnumerableLimit


 Sample 448. Code Sample / Example / Snippet of org.apache.calcite.sql.type.SqlTypeName

    private String translateOp2(String op, String name, RexLiteral right) {

if (op.equals("=")) {

partitionKeys.remove(name);

if (clusteringKeys.contains(name)) {

restrictedClusteringKeys++;

}

}



Object value = literalValue(right);

String valueString = value.toString();

if (value instanceof String) {

SqlTypeName typeName = rowType.getField(name, true, false).getType().getSqlTypeName();

if (typeName != SqlTypeName.CHAR) {

valueString = "'" + valueString + "'";

}

}

return name + " " + op + " " + valueString;

}


   Like      Feedback      org.apache.calcite.sql.type.SqlTypeName


 Sample 449. Code Sample / Example / Snippet of org.apache.calcite.rex.RexLiteral

    private String translateBinary2(String op, RexNode left, RexNode right) {

switch (right.getKind()) {

case LITERAL:

break;

default:

return null;

}

final RexLiteral rightLiteral = (RexLiteral) right;

switch (left.getKind()) {

case INPUT_REF:

final RexInputRef left1 = (RexInputRef) left;

String name = fieldNames.get(left1.getIndex());

return translateOp2(op, name, rightLiteral);

case CAST:

return translateBinary2(op, ((RexCall) left).operands.get(0), right);

default:

return null;

}

}


   Like      Feedback      org.apache.calcite.rex.RexLiteral


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 450. Code Sample / Example / Snippet of com.datastax.driver.core.DataType

      public Void apply(RelNode node) {

CassandraSchema.this.addMaterializedViews();

return null;

}

});

}



RelProtoDataType getRelDataType(String columnFamily, boolean view) {

List<ColumnMetadata> columns;

if (view) {

columns = getKeyspace().getMaterializedView(columnFamily).getColumns();

} else {

columns = getKeyspace().getTable(columnFamily).getColumns();

}



final RelDataTypeFactory typeFactory =

new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);

final RelDataTypeFactory.FieldInfoBuilder fieldInfo = typeFactory.builder();

for (ColumnMetadata column : columns) {

final String columnName = column.getName();

final DataType type = column.getType();


   Like      Feedback      com.datastax.driver.core.DataType


 Sample 451. Code Sample / Example / Snippet of com.datastax.driver.core.Cluster

  public CassandraSchema(String host, String keyspace, SchemaPlus parentSchema, String name) {

super();



this.keyspace = keyspace;

try {

Cluster cluster = Cluster.builder().addContactPoint(host).build();

this.session = cluster.connect(keyspace);

} catch (Exception e) {

throw new RuntimeException(e);

}

this.parentSchema = parentSchema;

this.name = name;



Hook.TRIMMED.add(new Function<RelNode, Void>() {

public Void apply(RelNode node) {

CassandraSchema.this.addMaterializedViews();

return null;

}

});

}


   Like      Feedback      com.datastax.driver.core.Cluster


 Sample 452. Code Sample / Example / Snippet of org.apache.calcite.rel.type.RelDataTypeFactory

      public Void apply(RelNode node) {

CassandraSchema.this.addMaterializedViews();

return null;

}

});

}



RelProtoDataType getRelDataType(String columnFamily, boolean view) {

List<ColumnMetadata> columns;

if (view) {

columns = getKeyspace().getMaterializedView(columnFamily).getColumns();

} else {

columns = getKeyspace().getTable(columnFamily).getColumns();

}



final RelDataTypeFactory typeFactory =

new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);

final RelDataTypeFactory.FieldInfoBuilder fieldInfo = typeFactory.builder();

for (ColumnMetadata column : columns) {


   Like      Feedback      org.apache.calcite.rel.type.RelDataTypeFactory


 Sample 453. Code Sample / Example / Snippet of com.datastax.driver.core.ResultSet

  public String prepareBindExecute(HrConnection state) throws SQLException {

Connection con = state.con;

Statement st = null;

ResultSet rs = null;

String ename = null;

try {

final PreparedStatement ps =

con.prepareStatement("select name from emps where empid = ?");

st = ps;

ps.setInt(1, state.id);

rs = ps.executeQuery();

rs.next();

ename = rs.getString(1);

} finally {

close(rs, st);

}

return ename;

}


   Like      Feedback      com.datastax.driver.core.ResultSet


 Sample 454. Code Sample / Example / Snippet of org.apache.calcite.plan.RelOptCost

  public CassandraSort(RelOptCluster cluster, RelTraitSet traitSet,

RelNode child, RelCollation collation) {

super(cluster, traitSet, child, collation, null, null);



assert getConvention() == CassandraRel.CONVENTION;

assert getConvention() == child.getConvention();

}



@Override public RelOptCost computeSelfCost(RelOptPlanner planner,

RelMetadataQuery mq) {

RelOptCost cost = super.computeSelfCost(planner, mq);

if (!collation.getFieldCollations().isEmpty()) {

return cost.multiplyBy(0.05);

} else {

return cost;

}

}


   Like      Feedback      org.apache.calcite.plan.RelOptCost


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 455. Code Sample / Example / Snippet of java.sql.Array

  private void dumpColumn(ResultSet resultSet, int i) throws SQLException {

final int t = resultSet.getMetaData().getColumnType(i);

switch (t) {

case Types.ARRAY:

final Array array = resultSet.getArray(i);

writer.print("{");

dump(array.getResultSet(), false);

writer.print("}");

return;

case Types.REAL:

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

writer.print("F");

return;

default:

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

}

}


   Like      Feedback      java.sql.Array


 Sample 456. Code Sample / Example / Snippet of org.apache.calcite.tools.PigRelBuilder

  public Fluent explainContains(String expected) throws ParseException {

final Ast.Program program = parseProgram(pig);

final PigRelBuilder builder =

PigRelBuilder.create(PigRelBuilderTest.config().build());

new Handler(builder).handle(program);

assertThat(Util.toLinux(RelOptUtil.toString(builder.peek())), is(expected));

return this;

}


   Like      Feedback      org.apache.calcite.tools.PigRelBuilder


 Sample 457. Code Sample / Example / Snippet of java.io.StringWriter

  public Fluent returns(Function<String, Void> checker) throws ParseException {

final Ast.Program program = parseProgram(pig);

final PigRelBuilder builder =

PigRelBuilder.create(PigRelBuilderTest.config().build());

final StringWriter sw = new StringWriter();

new CalciteHandler(builder, sw).handle(program);

checker.apply(Util.toLinux(sw.toString()));

return this;

}


   Like      Feedback      java.io.StringWriter


 Sample 458. Code Sample / Example / Snippet of org.apache.calcite.rex.RexBuilder

  private RexLiteral item(Ast.Node node, RelDataType type) {

final RexBuilder rexBuilder = builder.getRexBuilder();

switch (node.op) {

case LITERAL:

final Ast.Literal literal = (Ast.Literal) node;

return (RexLiteral) rexBuilder.makeLiteral(literal.value, type, false);

case TUPLE:

final Ast.Call tuple = (Ast.Call) node;

final ImmutableList<RexLiteral> list = tuple(tuple.operands, type);

return (RexLiteral) rexBuilder.makeLiteral(list, type, false);

case BAG:

final Ast.Call bag = (Ast.Call) node;

final ImmutableList<RexLiteral> list2 = bag(bag.operands, type);

return (RexLiteral) rexBuilder.makeLiteral(list2, type, false);

default:

throw new IllegalArgumentException("not a literal: " + node);

}

}


   Like      Feedback      org.apache.calcite.rex.RexBuilder


 Sample 459. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.Spacer

    public MapType(SqlParserPos pos) {

super(pos, Op.MAP_TYPE);

this.keyType = new ScalarType(pos, "int");

this.valueType = new ScalarType(pos, "int");

}

}



static class UnParser {

final StringBuilder buf = new StringBuilder();

final Spacer spacer = new Spacer(0);


   Like      Feedback      org.apache.calcite.avatica.util.Spacer


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 460. Code Sample / Example / Snippet of org.apache.calcite.rel.externalize.RelJsonReader

              public String apply(RelOptCluster cluster,

RelOptSchema relOptSchema, SchemaPlus rootSchema) {

SchemaPlus schema =

rootSchema.add("hr",

new ReflectiveSchema(new JdbcTest.HrSchema()));

final RelJsonReader reader =

new RelJsonReader(cluster, relOptSchema, schema);

RelNode node;

try {

node = reader.read(XX);

} catch (IOException e) {

throw new RuntimeException(e);

}

return RelOptUtil.dumpPlan(

"",

node,

false,

SqlExplainLevel.EXPPLAN_ATTRIBUTES);

}


   Like      Feedback      org.apache.calcite.rel.externalize.RelJsonReader


 Sample 461. Code Sample / Example / Snippet of org.apache.calcite.plan.RelTrait

    public void registerConverterRule(

RelOptPlanner planner,

ConverterRule converterRule) {

if (!converterRule.isGuaranteed()) {

return;

}



RelTrait fromTrait = converterRule.getInTrait();

RelTrait toTrait = converterRule.getOutTrait();



conversionMap.put(fromTrait, Pair.of(toTrait, converterRule));

}


   Like      Feedback      org.apache.calcite.plan.RelTrait


 Sample 462. Code Sample / Example / Snippet of org.apache.calcite.plan.RelOptAbstractTable

        public RelDataType getRowType(RelDataTypeFactory typeFactory) {

return typeFactory.builder()

.add("s", stringType)

.add("i", integerType).build();

}



@Override public Statistic getStatistic() {

return Statistics.of(100d, ImmutableList.<ImmutableBitSet>of(),

ImmutableList.of(COLLATION));

}

};



final RelOptAbstractTable t1 = new RelOptAbstractTable(relOptSchema,

"t1", table.getRowType(typeFactory)) {


   Like      Feedback      org.apache.calcite.plan.RelOptAbstractTable


 Sample 463. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlMonotonicity

  public void checkMonotonic(String query,

SqlMonotonicity expectedMonotonicity) {

SqlValidator validator = getValidator();

SqlNode n = parseAndValidate(validator, query);

final RelDataType rowType = validator.getValidatedNodeType(n);

final SqlValidatorNamespace selectNamespace = validator.getNamespace(n);

final String field0 = rowType.getFieldList().get(0).getName();

final SqlMonotonicity monotonicity =

selectNamespace.getMonotonicity(field0);

assertThat(monotonicity, equalTo(expectedMonotonicity));

}


   Like      Feedback      org.apache.calcite.sql.validate.SqlMonotonicity


 Sample 464. Code Sample / Example / Snippet of org.apache.calcite.sql.parser.SqlParserPos

          public int compare(SqlNode o1, SqlNode o2) {

final SqlParserPos pos0 = o1.getParserPosition();

final SqlParserPos pos1 = o2.getParserPosition();

int c = -Utilities.compare(

pos0.getLineNum(), pos1.getLineNum());

if (c != 0) {

return c;

}

return -Utilities.compare(

pos0.getColumnNum(), pos1.getColumnNum());

}


   Like      Feedback      org.apache.calcite.sql.parser.SqlParserPos


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 465. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlValidatorNamespace

  public void checkMonotonic(String query,

SqlMonotonicity expectedMonotonicity) {

SqlValidator validator = getValidator();

SqlNode n = parseAndValidate(validator, query);

final RelDataType rowType = validator.getValidatedNodeType(n);

final SqlValidatorNamespace selectNamespace = validator.getNamespace(n);

final String field0 = rowType.getFieldList().get(0).getName();

final SqlMonotonicity monotonicity =

selectNamespace.getMonotonicity(field0);

assertThat(monotonicity, equalTo(expectedMonotonicity));

}


   Like      Feedback      org.apache.calcite.sql.validate.SqlValidatorNamespace


 Sample 466. Code Sample / Example / Snippet of org.apache.calcite.sql.SqlSelect

  public SqlMonotonicity getMonotonicity(String sql) {

final SqlValidator validator = getValidator();

final SqlNode node = parseAndValidate(validator, sql);

final SqlSelect select = (SqlSelect) node;

final SqlNode selectItem0 = select.getSelectList().get(0);

final SqlValidatorScope scope = validator.getSelectScope(select);

return selectItem0.getMonotonicity(scope);

}


   Like      Feedback      org.apache.calcite.sql.SqlSelect


 Sample 467. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlValidator

  public void checkFieldOrigin(String sql, String fieldOriginList) {

SqlValidator validator = getValidator();

SqlNode n = parseAndValidate(validator, sql);

final List<List<String>> list = validator.getFieldOrigins(n);

final StringBuilder buf = new StringBuilder("{");

int i = 0;

for (List<String> strings : list) {

if (i++ > 0) {

buf.append(", ");

}

if (strings == null) {

buf.append("null");

} else {

int j = 0;

for (String s : strings) {

if (j++ > 0) {

buf.append('.');

}

buf.append(s);

}

}

}

buf.append("}");

assertEquals(fieldOriginList, buf.toString());

}


   Like      Feedback      org.apache.calcite.sql.validate.SqlValidator


 Sample 468. Code Sample / Example / Snippet of org.apache.calcite.sql.SqlNode

  public RelDataType getResultType(String sql) {

SqlValidator validator = getValidator();

SqlNode n = parseAndValidate(validator, sql);



return validator.getValidatedNodeType(n);

}




   Like      Feedback      org.apache.calcite.sql.SqlNode


 Sample 469. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlValidatorScope

  public SqlMonotonicity getMonotonicity(String sql) {

final SqlValidator validator = getValidator();

final SqlNode node = parseAndValidate(validator, sql);

final SqlSelect select = (SqlSelect) node;

final SqlNode selectItem0 = select.getSelectList().get(0);

final SqlValidatorScope scope = validator.getSelectScope(select);

return selectItem0.getMonotonicity(scope);

}


   Like      Feedback      org.apache.calcite.sql.validate.SqlValidatorScope


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 470. Code Sample / Example / Snippet of org.apache.calcite.sql.SqlCall

  public void checkIntervalConv(String sql, String expected) {

SqlValidator validator = getValidator();

final SqlCall n = (SqlCall) parseAndValidate(validator, sql);



SqlNode node = null;

for (int i = 0; i < n.operandCount(); i++) {

node = stripAs(n.operand(i));

if (node instanceof SqlCall) {

node = ((SqlCall) node).operand(0);

break;

}

}



assertNotNull(node);

SqlIntervalLiteral intervalLiteral = (SqlIntervalLiteral) node;

SqlIntervalLiteral.IntervalValue interval =

(SqlIntervalLiteral.IntervalValue) intervalLiteral.getValue();

long l =

interval.getIntervalQualifier().isYearMonth()

? SqlParserUtil.intervalToMonths(interval)

: SqlParserUtil.intervalToMillis(interval);

String actual = l + "";

assertEquals(expected, actual);

}


   Like      Feedback      org.apache.calcite.sql.SqlCall


 Sample 471. Code Sample / Example / Snippet of org.apache.calcite.sql.pretty.SqlPrettyWriter

  protected void assertPrintsTo(

boolean newlines,

final String sql,

String expected) {

final SqlNode node = parseQuery(sql);

final SqlPrettyWriter prettyWriter =

new SqlPrettyWriter(SqlDialect.DUMMY);

prettyWriter.setAlwaysUseParentheses(false);

if (newlines) {

prettyWriter.setCaseClausesOnNewLines(true);

}

String actual = prettyWriter.format(node);

getDiffRepos().assertEquals("formatted", expected, actual);



final String actual2 = actual.replaceAll("`", """);

final SqlNode node2 = parseQuery(actual2);

assertTrue(node.equalsDeep(node2, Litmus.THROW));

}


   Like      Feedback      org.apache.calcite.sql.pretty.SqlPrettyWriter


 Sample 472. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlConformance

    public AdvisorTesterFactory() {

super(DefaultSqlTestFactory.INSTANCE);

}



@Override public SqlValidator getValidator(SqlTestFactory factory) {

final RelDataTypeFactory typeFactory =

new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);

final SqlConformance conformance = (SqlConformance) get("conformance");

final boolean caseSensitive = (Boolean) factory.get("caseSensitive");

return new SqlAdvisorValidator(

SqlStdOperatorTable.instance(),

new MockCatalogReader(typeFactory, caseSensitive).init(),

typeFactory,

conformance);

}


   Like      Feedback      org.apache.calcite.sql.validate.SqlConformance


 Sample 473. Code Sample / Example / Snippet of org.apache.calcite.sql.advise.SqlAdvisor

  protected void assertHint(

String sql,

String expectedResults) throws Exception {

SqlValidatorWithHints validator =

(SqlValidatorWithHints) tester.getValidator();

SqlAdvisor advisor = tester.getFactory().createAdvisor(validator);



SqlParserUtil.StringAndPos sap = SqlParserUtil.findPos(sql);



List<SqlMoniker> results =

advisor.getCompletionHints(

sap.sql,

sap.pos);

Assert.assertEquals(

expectedResults, convertCompletionHints(results));

}


   Like      Feedback      org.apache.calcite.sql.advise.SqlAdvisor


 Sample 474. Code Sample / Example / Snippet of org.apache.calcite.sql.SqlOperatorTable

  public SqlOperatorTable createOperatorTable(SqlTestFactory factory) {

final SqlOperatorTable opTab0 =

(SqlOperatorTable) factory.get("operatorTable");

MockSqlOperatorTable opTab = new MockSqlOperatorTable(opTab0);

MockSqlOperatorTable.addRamp(opTab);

return opTab;

}


   Like      Feedback      org.apache.calcite.sql.SqlOperatorTable


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 475. Code Sample / Example / Snippet of static org.apache.calcite.sql.test.SqlTester.TypeChecker

  public void checkScalarExact(

String expression,

String expectedType,

String result) {

for (String sql : buildQueries(expression)) {

TypeChecker typeChecker =

new SqlTests.StringTypeChecker(expectedType);

check(sql, typeChecker, result, 0);

}

}


   Like      Feedback      static org.apache.calcite.sql.test.SqlTester.TypeChecker


 Sample 476. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.Quoting

  private static final ThreadLocal<boolean[]> LINUXIFY =

new ThreadLocal<boolean[]>() {

@Override protected boolean[] initialValue() {

return new boolean[] {true};

}

};



Quoting quoting = Quoting.DOUBLE_QUOTE;


   Like      Feedback      org.apache.calcite.avatica.util.Quoting


 Sample 477. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.Casing

  private static final ThreadLocal<boolean[]> LINUXIFY =

new ThreadLocal<boolean[]>() {

@Override protected boolean[] initialValue() {

return new boolean[] {true};

}

};



Quoting quoting = Quoting.DOUBLE_QUOTE;

Casing unquotedCasing = Casing.TO_UPPER;


   Like      Feedback      org.apache.calcite.avatica.util.Casing


 Sample 478. Code Sample / Example / Snippet of org.apache.calcite.sql.SqlSetOption

  private static void checkSqlSetOptionSame(SqlNode node) {

SqlSetOption opt = (SqlSetOption) node;

SqlNode[] sqlNodes = new SqlNode[opt.getOperandList().size()];

SqlCall returned = opt.getOperator().createCall(

opt.getFunctionQuantifier(),

opt.getParserPosition(),

opt.getOperandList().toArray(sqlNodes));

assertThat((Class) opt.getClass(), equalTo((Class) returned.getClass()));

SqlSetOption optRet = (SqlSetOption) returned;

assertThat(optRet.getScope(), is(opt.getScope()));

assertThat(optRet.getName(), is(opt.getName()));

assertThat(optRet.getFunctionQuantifier(), is(opt.getFunctionQuantifier()));

assertThat(optRet.getParserPosition(), is(opt.getParserPosition()));

assertThat(optRet.getValue(), is(opt.getValue()));

assertThat(optRet.toString(), is(opt.toString()));

}


   Like      Feedback      org.apache.calcite.sql.SqlSetOption


 Sample 479. Code Sample / Example / Snippet of org.apache.calcite.tools.FrameworkConfig

    public Object get(String name) {

return null;

}

}



@Before public void setUp() {

rootSchema = Frameworks.createRootSchema(true);

final FrameworkConfig config = Frameworks.newConfigBuilder()


   Like      Feedback      org.apache.calcite.tools.FrameworkConfig


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 480. Code Sample / Example / Snippet of sqlline.SqlLine

  private static Pair<SqlLine.Status, String> run(String... args)

throws Throwable {

SqlLine sqlline = new SqlLine();

ByteArrayOutputStream os = new ByteArrayOutputStream();

PrintStream sqllineOutputStream = new PrintStream(os);

sqlline.setOutputStream(sqllineOutputStream);

sqlline.setErrorStream(sqllineOutputStream);

SqlLine.Status status = SqlLine.Status.OK;



Bug.upgrade("[sqlline-35] Make Sqlline.begin public");



return Pair.of(status, os.toString("UTF8"));

}


   Like      Feedback      sqlline.SqlLine


 Sample 481. Code Sample / Example / Snippet of java.io.ByteArrayOutputStream

  private static Pair<SqlLine.Status, String> run(String... args)

throws Throwable {

SqlLine sqlline = new SqlLine();

ByteArrayOutputStream os = new ByteArrayOutputStream();

PrintStream sqllineOutputStream = new PrintStream(os);

sqlline.setOutputStream(sqllineOutputStream);

sqlline.setErrorStream(sqllineOutputStream);

SqlLine.Status status = SqlLine.Status.OK;



Bug.upgrade("[sqlline-35] Make Sqlline.begin public");



return Pair.of(status, os.toString("UTF8"));

}


   Like      Feedback      java.io.ByteArrayOutputStream


 Sample 482. Code Sample / Example / Snippet of org.apache.calcite.sql.type.SqlTypeFactoryImpl

  public void testLeastRestrictiveWithAny() {

SqlTypeFactoryImpl typeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);

final RelDataType sqlBigInt = typeFactory.createSqlType(SqlTypeName.BIGINT);

final RelDataType sqlAny = typeFactory.createSqlType(SqlTypeName.ANY);



RelDataType leastRestrictive =

typeFactory.leastRestrictive(Lists.newArrayList(sqlBigInt, sqlAny));

assertEquals(leastRestrictive.getSqlTypeName(), SqlTypeName.ANY);

}


   Like      Feedback      org.apache.calcite.sql.type.SqlTypeFactoryImpl


 Sample 483. Code Sample / Example / Snippet of org.apache.calcite.plan.RelOptTable

    public RelOptTable getTableForMember(

List<String> names,

final String datasetName,

boolean[] usedDataset) {

final RelOptTable table = getTableForMember(names);



RelOptTable datasetTable =

new DelegatingRelOptTable(table) {

public List<String> getQualifiedName() {

final List<String> list =

new ArrayList<>(super.getQualifiedName());

list.set(

list.size() - 1,

list.get(list.size() - 1) + ":" + datasetName);

return ImmutableList.copyOf(list);

}

};

if (usedDataset != null) {

assert usedDataset.length == 1;

usedDataset[0] = true;

}

return datasetTable;

}


   Like      Feedback      org.apache.calcite.plan.RelOptTable


 Sample 484. Code Sample / Example / Snippet of org.apache.calcite.sql2rel.RelFieldTrimmer

    public void assertConvertsTo(

String sql,

String plan,

boolean trim) {

String sql2 = getDiffRepos().expand("sql", sql);

RelNode rel = convertSqlToRel(sql2).project();



assertTrue(rel != null);

assertValid(rel);



if (trim) {

final RelBuilder relBuilder =

RelFactories.LOGICAL_BUILDER.create(rel.getCluster(), null);

final RelFieldTrimmer trimmer = createFieldTrimmer(relBuilder);

rel = trimmer.trim(rel);

assertTrue(rel != null);

assertValid(rel);

}



String actual = NL + RelOptUtil.toString(rel);

diffRepos.assertEquals("plan", plan, actual);

}


   Like      Feedback      org.apache.calcite.sql2rel.RelFieldTrimmer


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 485. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlValidatorTable

    public RelOptTable getTableForMember(List<String> names) {

final SqlValidatorTable table = catalogReader.getTable(names);

final RelDataType rowType = table.getRowType();

final List<RelCollation> collationList = deduceMonotonicity(table);

if (names.size() < 3) {

String[] newNames2 = {"CATALOG", "SALES", ""};

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

int i = 0;

while (newNames.size() < newNames2.length) {

newNames.add(i, newNames2[i]);

++i;

}

names = newNames;

}

return createColumnSet(table, names, rowType, collationList);

}


   Like      Feedback      org.apache.calcite.sql.validate.SqlValidatorTable


 Sample 486. Code Sample / Example / Snippet of org.apache.calcite.tools.RelBuilder

    public void assertConvertsTo(

String sql,

String plan,

boolean trim) {

String sql2 = getDiffRepos().expand("sql", sql);

RelNode rel = convertSqlToRel(sql2).project();



assertTrue(rel != null);

assertValid(rel);



if (trim) {

final RelBuilder relBuilder =

RelFactories.LOGICAL_BUILDER.create(rel.getCluster(), null);

final RelFieldTrimmer trimmer = createFieldTrimmer(relBuilder);

rel = trimmer.trim(rel);

assertTrue(rel != null);

assertValid(rel);

}



String actual = NL + RelOptUtil.toString(rel);

diffRepos.assertEquals("plan", plan, actual);

}


   Like      Feedback      org.apache.calcite.tools.RelBuilder


 Sample 487. Code Sample / Example / Snippet of java.io.BufferedWriter

  private void addThreadWriters(Integer threadId) {

StringWriter w = new StringWriter();

BufferedWriter bw = new BufferedWriter(w);

threadStringWriters.put(threadId, w);

threadBufferedWriters.put(threadId, bw);

threadResultsReaders.put(threadId, new ResultsReader(bw));

}


   Like      Feedback      java.io.BufferedWriter


 Sample 488. Code Sample / Example / Snippet of java.util.regex.Matcher

    private void defineVariables(String line) {

Matcher varDefn = matchesVarDefn.matcher(line);

if (varDefn.lookingAt()) {

String var = varDefn.group(1);

String val = varDefn.group(2);

vars.define(var, val);

} else {

String[] words = splitWords.split(line);

for (String var : words) {

String value = System.getenv(var);

vars.define(var, value);

}

}

}


   Like      Feedback      java.util.regex.Matcher


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

    private List<String> tokenize(String s) {

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

StringTokenizer tokenizer = new StringTokenizer(s);

while (tokenizer.hasMoreTokens()) {

result.add(tokenizer.nextToken());

}

return result;

}


   Like      Feedback      java.util.StringTokenizer


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 490. Code Sample / Example / Snippet of org.hamcrest.Matcher

    private void defineVariables(String line) {

Matcher varDefn = matchesVarDefn.matcher(line);

if (varDefn.lookingAt()) {

String var = varDefn.group(1);

String val = varDefn.group(2);

vars.define(var, val);

} else {

String[] words = splitWords.split(line);

for (String var : words) {

String value = System.getenv(var);

vars.define(var, value);

}

}

}


   Like      Feedback      org.hamcrest.Matcher


 Sample 491. Code Sample / Example / Snippet of org.apache.calcite.rel.metadata.RelColumnOrigin

  private void checkSingleColumnOrigin(

String sql,

String expectedTableName,

String expectedColumnName,

boolean expectedDerived) {

Set<RelColumnOrigin> result = checkColumnOrigin(sql);

assertTrue(result != null);

assertEquals(

1,

result.size());

RelColumnOrigin rco = result.iterator().next();

checkColumnOrigin(

rco, expectedTableName, expectedColumnName, expectedDerived);

}


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


 Sample 492. Code Sample / Example / Snippet of org.apache.calcite.util.JsonBuilder

    public final AssertThat withMaterializations(String model,

Function<JsonBuilder, List<Object>> materializations) {

final JsonBuilder builder = new JsonBuilder();

final List<Object> list = materializations.apply(builder);

final String buf =

"materializations: " + builder.toJsonString(list);

final String model2;

if (model.contains("defaultSchema: 'foodmart'")) {

model2 = model.replace("]",

", { name: 'mat', "

+ buf

+ "} "

+ "]");

} else if (model.contains("type: ")) {

model2 = model.replace("type: ",

buf + ", "

+ "type: ");

} else {

throw new AssertionError("do not know where to splice");

}

return withModel(model2);

}


   Like      Feedback      org.apache.calcite.util.JsonBuilder


 Sample 493. Code Sample / Example / Snippet of org.apache.calcite.schema.SchemaPlus

    public Connection apply(Connection connection) throws SQLException {

if (schema != null) {

CalciteConnection con = connection.unwrap(CalciteConnection.class);

SchemaPlus rootSchema = con.getRootSchema();

rootSchema.add(name, schema);

}

connection.setSchema(name);

return connection;

}


   Like      Feedback      org.apache.calcite.schema.SchemaPlus


 Sample 494. Code Sample / Example / Snippet of java.util.Collection

      public Void apply(ResultSet resultSet) {

++executeCount;

try {

final Collection result =

CalciteAssert.toStringList(resultSet,

ordered ? new ArrayList<String>() : new TreeSet<String>());

if (executeCount == 1) {

expected = result;

} else {

if (!expected.equals(result)) {

assertThat(newlineList(result), equalTo(newlineList(expected)));

fail("oops");

}

}

return null;

} catch (SQLException e) {

throw new RuntimeException(e);

}

}


   Like      Feedback      java.util.Collection


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 495. Code Sample / Example / Snippet of org.apache.calcite.jdbc.CalciteConnection

    public Connection apply(Connection connection) throws SQLException {

if (schema != null) {

CalciteConnection con = connection.unwrap(CalciteConnection.class);

SchemaPlus rootSchema = con.getRootSchema();

rootSchema.add(name, schema);

}

connection.setSchema(name);

return connection;

}


   Like      Feedback      org.apache.calcite.jdbc.CalciteConnection


 Sample 496. Code Sample / Example / Snippet of org.apache.calcite.DataContext

    public <T> AssertThat doWithDataContext(Function<DataContext, T> fn)

throws Exception {

CalciteConnection connection =

(CalciteConnection) connectionFactory.createConnection();

final DataContext dataContext = CalciteMetaImpl.createDataContext(

connection);

try {

T t = fn.apply(dataContext);

Util.discard(t);

return AssertThat.this;

} finally {

connection.close();

}

}


   Like      Feedback      org.apache.calcite.DataContext


 Sample 497. Code Sample / Example / Snippet of org.apache.calcite.plan.hep.HepProgram

  protected DiffRepository getDiffRepos() {

return DiffRepository.lookup(RelOptRulesTest.class);

}



@Test public void testReduceNestedCaseWhen() {

HepProgram preProgram = new HepProgramBuilder()

.build();



HepProgramBuilder builder = new HepProgramBuilder();

builder.addRuleClass(ReduceExpressionsRule.class);

HepPlanner hepPlanner = new HepPlanner(builder.build());

hepPlanner.addRule(ReduceExpressionsRule.FILTER_INSTANCE);



final String sql = "select sal "

+ "from emp "

+ "where case when (sal = 1000) then "

+ "(case when sal = 1000 then null else 1 end is null) else "

+ "(case when sal = 2000 then null else 1 end is null) end is true";

checkPlanning(tester, preProgram, hepPlanner, sql);

}


   Like      Feedback      org.apache.calcite.plan.hep.HepProgram


 Sample 498. Code Sample / Example / Snippet of org.apache.calcite.plan.hep.HepPlanner

  protected DiffRepository getDiffRepos() {

return DiffRepository.lookup(RelOptRulesTest.class);

}



@Test public void testReduceNestedCaseWhen() {

HepProgram preProgram = new HepProgramBuilder()

.build();



HepProgramBuilder builder = new HepProgramBuilder();

builder.addRuleClass(ReduceExpressionsRule.class);

HepPlanner hepPlanner = new HepPlanner(builder.build());

hepPlanner.addRule(ReduceExpressionsRule.FILTER_INSTANCE);



final String sql = "select sal "

+ "from emp "

+ "where case when (sal = 1000) then "

+ "(case when sal = 1000 then null else 1 end is null) else "

+ "(case when sal = 2000 then null else 1 end is null) end is true";

checkPlanning(tester, preProgram, hepPlanner, sql);

}


   Like      Feedback      org.apache.calcite.plan.hep.HepPlanner


 Sample 499. Code Sample / Example / Snippet of org.apache.calcite.plan.hep.HepProgramBuilder

  protected DiffRepository getDiffRepos() {

return DiffRepository.lookup(RelOptRulesTest.class);

}



@Test public void testReduceNestedCaseWhen() {

HepProgram preProgram = new HepProgramBuilder()

.build();



HepProgramBuilder builder = new HepProgramBuilder();

builder.addRuleClass(ReduceExpressionsRule.class);

HepPlanner hepPlanner = new HepPlanner(builder.build());

hepPlanner.addRule(ReduceExpressionsRule.FILTER_INSTANCE);



final String sql = "select sal "

+ "from emp "

+ "where case when (sal = 1000) then "

+ "(case when sal = 1000 then null else 1 end is null) else "

+ "(case when sal = 2000 then null else 1 end is null) end is true";

checkPlanning(tester, preProgram, hepPlanner, sql);

}


   Like      Feedback      org.apache.calcite.plan.hep.HepProgramBuilder


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 500. Code Sample / Example / Snippet of java.math.BigDecimal

              public Void apply(ResultSet a0) {

try {

final BigDecimal bigDecimal = a0.getBigDecimal(1);

fail("expected error, got " + bigDecimal);

} catch (SQLException e) {

throw new RuntimeException(e);

} catch (NoSuchElementException e) {

}

try {

assertTrue(a0.next());

final BigDecimal bigDecimal = a0.getBigDecimal(1);

assertThat(bigDecimal, equalTo(BigDecimal.valueOf(2008)));

} catch (SQLException e) {

throw new RuntimeException(e);

}

return null;

}


   Like      Feedback      java.math.BigDecimal


 Sample 501. Code Sample / Example / Snippet of static org.hamcrest.CoreMatchers.is

  public static final List<Pair<String, String>> FOODMART_QUERIES =

querify(QUERIES);



@Test public void testJanino169() {

CalciteAssert.that()

.with(CalciteAssert.Config.JDBC_FOODMART)

.query(

"select "time_id" from "foodmart"."time_by_day" as "t" ")

.returnsCount(730);

}




   Like      Feedback      static org.hamcrest.CoreMatchers.is


 Sample 502. Code Sample / Example / Snippet of java.sql.DatabaseMetaData

  private String mm(int majorVersion, int minorVersion) {

return majorVersion + "." + minorVersion;

}



@Test public void testMetaDataColumns()

throws ClassNotFoundException, SQLException {

Connection connection = CalciteAssert

.that(CalciteAssert.Config.REGULAR).connect();

DatabaseMetaData metaData = connection.getMetaData();

ResultSet resultSet = metaData.getColumns(null, null, null, null);

assertTrue(resultSet.next()); // there's something

String name = resultSet.getString(4);

int type = resultSet.getInt(5);

String typeName = resultSet.getString(6);

int columnSize = resultSet.getInt(7);

int decimalDigits = resultSet.getInt(9);

int numPrecRadix = resultSet.getInt(10);

int charOctetLength = resultSet.getInt(16);

String isNullable = resultSet.getString(18);

resultSet.close();

connection.close();

}


   Like      Feedback      java.sql.DatabaseMetaData


 Sample 503. Code Sample / Example / Snippet of org.apache.calcite.schema.TableFunction

  private Connection getConnectionWithMultiplyFunction()

throws ClassNotFoundException, SQLException {

Connection connection =

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

CalciteConnection calciteConnection =

connection.unwrap(CalciteConnection.class);

SchemaPlus rootSchema = calciteConnection.getRootSchema();

SchemaPlus schema = rootSchema.add("s", new AbstractSchema());

final TableFunction table =

TableFunctionImpl.create(Smalls.MULTIPLICATION_TABLE_METHOD);

schema.add("multiplication", table);

return connection;

}


   Like      Feedback      org.apache.calcite.schema.TableFunction


 Sample 504. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.TimeUnitRange

  private void checkTimestampString(String s, long d) {

assertThat(unixTimestampToString(d), equalTo(s));

assertThat(timestampStringToUnixDate(s), equalTo(d));

}



@Test public void testIntervalYearMonthToString() {

TimeUnitRange range = TimeUnitRange.YEAR_TO_MONTH;

assertEquals("+0-00", intervalYearMonthToString(0, range));

assertEquals("+1-00", intervalYearMonthToString(12, range));

assertEquals("+1-01", intervalYearMonthToString(13, range));

assertEquals("-1-01", intervalYearMonthToString(-13, range));

}


   Like      Feedback      org.apache.calcite.avatica.util.TimeUnitRange


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 505. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.ByteString

  private void thereAndBack(byte[] bytes) {

final ByteString byteString = new ByteString(bytes);

final byte[] bytes2 = byteString.getBytes();

assertThat(bytes, equalTo(bytes2));



final String base64String = byteString.toBase64String();

final ByteString byteString1 = ByteString.ofBase64(base64String);

assertThat(byteString, equalTo(byteString1));

}


   Like      Feedback      org.apache.calcite.avatica.util.ByteString


 Sample 506. Code Sample / Example / Snippet of org.apache.hc.core5.http.bootstrap.io.HttpServer

    public ListenerEndpoint getListenerEndpoint() {

final HttpServer local = this.server;

if (local != null) {

return this.server.getEndpoint();

}

throw new IllegalStateException("Server not running");

}


   Like      Feedback      org.apache.hc.core5.http.bootstrap.io.HttpServer


 Sample 507. Code Sample / Example / Snippet of org.apache.hc.core5.http.impl.io.HttpService

    public void testBasicProtocolDowngrade() throws Exception {

final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class);

final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class);

final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class);

final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class);



final HttpService httpservice = new HttpService(

httprocessor,

connReuseStrategy,

responseFactory,

handlerResolver);

final HttpCoreContext context = HttpCoreContext.create();

final HttpServerConnection conn = Mockito.mock(HttpServerConnection.class);

final HttpRequest request = new BasicHttpRequest("GET", "/", new HttpVersion(20, 45));

Mockito.when(conn.receiveRequestHeader()).thenReturn(request);

final HttpResponse response = new BasicHttpResponse(200, "OK");

Mockito.when(responseFactory.newHttpResponse(200, context)).thenReturn(response);

Mockito.when(connReuseStrategy.keepAlive(request, response, context)).thenReturn(Boolean.FALSE);



httpservice.handleRequest(conn, context);



Mockito.verify(responseFactory).newHttpResponse(200, context);

}


   Like      Feedback      org.apache.hc.core5.http.impl.io.HttpService


 Sample 508. Code Sample / Example / Snippet of org.apache.hc.core5.http.impl.nio.UriHttpAsyncRequestHandlerMapper

    public void testRegisterUnregister() throws Exception {

final HttpAsyncRequestHandler<?> h = Mockito.mock(HttpAsyncRequestHandler.class);



final UriPatternMatcher<HttpAsyncRequestHandler<?>> matcher = Mockito.spy(

new UriPatternMatcher<HttpAsyncRequestHandler<?>>());

final UriHttpAsyncRequestHandlerMapper registry = new UriHttpAsyncRequestHandlerMapper(matcher);



registry.register("/h1", h);

registry.unregister("/h1");



Mockito.verify(matcher).register("/h1", h);

Mockito.verify(matcher).unregister("/h1");

}


   Like      Feedback      org.apache.hc.core5.http.impl.nio.UriHttpAsyncRequestHandlerMapper


 Sample 509. Code Sample / Example / Snippet of javax.net.ssl.TrustManager

    public SSLContextBuilder loadTrustMaterial(

final KeyStore truststore,

final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {

final TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(

TrustManagerFactory.getDefaultAlgorithm());

tmfactory.init(truststore);

final TrustManager[] tms = tmfactory.getTrustManagers();

if (tms != null) {

if (trustStrategy != null) {

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

final TrustManager tm = tms[i];

if (tm instanceof X509TrustManager) {

tms[i] = new TrustManagerDelegate(

(X509TrustManager) tm, trustStrategy);

}

}

}

for (final TrustManager tm : tms) {

this.trustmanagers.add(tm);

}

}

return this;

}


   Like      Feedback      javax.net.ssl.TrustManager


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 510. Code Sample / Example / Snippet of javax.net.ssl.KeyManagerFactory

    public SSLContextBuilder loadKeyMaterial(

final KeyStore keystore,

final char[] keyPassword,

final PrivateKeyStrategy aliasStrategy)

throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {

final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(

KeyManagerFactory.getDefaultAlgorithm());

kmfactory.init(keystore, keyPassword);

final KeyManager[] kms = kmfactory.getKeyManagers();

if (kms != null) {

if (aliasStrategy != null) {

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

final KeyManager km = kms[i];

if (km instanceof X509ExtendedKeyManager) {

kms[i] = new KeyManagerDelegate((X509ExtendedKeyManager) km, aliasStrategy);

}

}

}

for (final KeyManager km : kms) {

keymanagers.add(km);

}

}

return this;

}


   Like      Feedback      javax.net.ssl.KeyManagerFactory


 Sample 511. Code Sample / Example / Snippet of javax.net.ssl.KeyManager

    public SSLContextBuilder loadKeyMaterial(

final KeyStore keystore,

final char[] keyPassword,

final PrivateKeyStrategy aliasStrategy)

throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {

final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(

KeyManagerFactory.getDefaultAlgorithm());

kmfactory.init(keystore, keyPassword);

final KeyManager[] kms = kmfactory.getKeyManagers();

if (kms != null) {

if (aliasStrategy != null) {

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

final KeyManager km = kms[i];

if (km instanceof X509ExtendedKeyManager) {

kms[i] = new KeyManagerDelegate((X509ExtendedKeyManager) km, aliasStrategy);

}

}

}

for (final KeyManager km : kms) {

keymanagers.add(km);

}

}

return this;

}


   Like      Feedback      javax.net.ssl.KeyManager


 Sample 512. Code Sample / Example / Snippet of javax.net.ssl.TrustManagerFactory

    public SSLContextBuilder loadTrustMaterial(

final KeyStore truststore,

final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {

final TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(

TrustManagerFactory.getDefaultAlgorithm());

tmfactory.init(truststore);

final TrustManager[] tms = tmfactory.getTrustManagers();

if (tms != null) {

if (trustStrategy != null) {

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

final TrustManager tm = tms[i];

if (tm instanceof X509TrustManager) {

tms[i] = new TrustManagerDelegate(

(X509TrustManager) tm, trustStrategy);

}

}

}

for (final TrustManager tm : tms) {

this.trustmanagers.add(tm);

}

}

return this;

}


   Like      Feedback      javax.net.ssl.TrustManagerFactory


 Sample 513. Code Sample / Example / Snippet of org.apache.hc.core5.http.protocol.BasicHttpContext

    public void run() {

try {

final BasicHttpContext localContext = new BasicHttpContext();

final HttpCoreContext context = HttpCoreContext.adapt(localContext);

while (!Thread.interrupted() && this.conn.isOpen()) {

this.httpservice.handleRequest(this.conn, context);

localContext.clear();

}

this.conn.close();

} catch (final Exception ex) {

this.exceptionLogger.log(ex);

} finally {

try {

this.conn.shutdown();

} catch (final IOException ex) {

this.exceptionLogger.log(ex);

}

}

}


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


 Sample 514. Code Sample / Example / Snippet of org.apache.hc.core5.http.message.BufferedHeader

    public void testBasicConstructor() throws Exception {

final CharArrayBuffer buf = new CharArrayBuffer(32);

buf.append("name: value");

final BufferedHeader header = new BufferedHeader(buf, false);

Assert.assertEquals("name", header.getName());

Assert.assertEquals("value", header.getValue());

Assert.assertSame(buf, header.getBuffer());

Assert.assertEquals(5, header.getValuePos());

}


   Like      Feedback      org.apache.hc.core5.http.message.BufferedHeader


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 515. Code Sample / Example / Snippet of org.apache.hc.core5.util.ByteArrayBuffer

    public void testConstructor() throws Exception {

final ByteArrayBuffer buffer = new ByteArrayBuffer(16);

Assert.assertEquals(16, buffer.capacity());

Assert.assertEquals(0, buffer.length());

Assert.assertNotNull(buffer.buffer());

Assert.assertEquals(16, buffer.buffer().length);

try {

new ByteArrayBuffer(-1);

Assert.fail("IllegalArgumentException should have been thrown");

} catch (final IllegalArgumentException ex) {

}

}


   Like      Feedback      org.apache.hc.core5.util.ByteArrayBuffer


 Sample 516. Code Sample / Example / Snippet of org.apache.hc.core5.http.message.ParserCursor

    public void testParamByName() throws Exception {

final String s = "name = value; param1 = value1; param2 = value2";

final CharArrayBuffer buf = new CharArrayBuffer(64);

buf.append(s);

final ParserCursor cursor = new ParserCursor(0, buf.length());

final HeaderElement element = BasicHeaderValueParser.INSTANCE.parseHeaderElement(buf, cursor);

Assert.assertEquals("value1", element.getParameterByName("param1").getValue());

Assert.assertEquals("value2", element.getParameterByName("param2").getValue());

Assert.assertNull(element.getParameterByName("param3"));

try {

element.getParameterByName(null);

Assert.fail("IllegalArgumentException should have been thrown");

} catch (final IllegalArgumentException ex) {

}

}


   Like      Feedback      org.apache.hc.core5.http.message.ParserCursor


 Sample 517. Code Sample / Example / Snippet of java.util.BitSet

    public static BitSet INIT_BITSET(final int ... b) {

final BitSet bitset = new BitSet();

for (final int aB : b) {

bitset.set(aB);

}

return bitset;

}


   Like      Feedback      java.util.BitSet


 Sample 518. Code Sample / Example / Snippet of org.apache.hc.core5.http.message.BasicStatusLine

    public void testSerialization() throws Exception {

final BasicStatusLine orig = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");

final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream();

final ObjectOutputStream outstream = new ObjectOutputStream(outbuffer);

outstream.writeObject(orig);

outstream.close();

final byte[] raw = outbuffer.toByteArray();

final ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw);

final ObjectInputStream instream = new ObjectInputStream(inbuffer);

final BasicStatusLine clone = (BasicStatusLine) instream.readObject();

Assert.assertEquals(orig.getReasonPhrase(), clone.getReasonPhrase());

Assert.assertEquals(orig.getStatusCode(), clone.getStatusCode());

Assert.assertEquals(orig.getProtocolVersion(), clone.getProtocolVersion());

}


   Like      Feedback      org.apache.hc.core5.http.message.BasicStatusLine


 Sample 519. Code Sample / Example / Snippet of java.net.SocketAddress

    public String toString() {

final SocketAddress remoteAddress = this.session.getRemoteAddress();

final SocketAddress localAddress = this.session.getLocalAddress();

if (remoteAddress != null && localAddress != null) {

final StringBuilder buffer = new StringBuilder();

NetUtils.formatAddress(buffer, localAddress);

buffer.append("<->");

NetUtils.formatAddress(buffer, remoteAddress);

return buffer.toString();

}

return "[Not bound]";

}


   Like      Feedback      java.net.SocketAddress


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 520. Code Sample / Example / Snippet of org.apache.hc.core5.http.nio.HttpAsyncResponseProducer

    public void outputReady(

final NHttpServerConnection conn,

final ContentEncoder encoder) throws HttpException, IOException {

final State state = getState(conn);

Asserts.notNull(state, "Connection state");

Asserts.check(state.getResponseState() == MessageState.BODY_STREAM,

"Unexpected response state %s", state.getResponseState());



final Outgoing outgoing = state.getOutgoing();

Asserts.notNull(outgoing, "Outgoing response");

final HttpAsyncResponseProducer responseProducer = outgoing.getProducer();



responseProducer.produceContent(encoder, conn);



if (encoder.isCompleted()) {

completeResponse(outgoing, conn, state);

}

}


   Like      Feedback      org.apache.hc.core5.http.nio.HttpAsyncResponseProducer


 Sample 521. Get First Row values from a XLS Sheet using Apache POI ?

private String[] getFirstRow(Sheet sheet) {
Row firstRow = sheet.getRow(0);
int totalColumns = headerRow.getPhysicalNumberOfCells();
if (totalColumns > 0){
String[] columnHeaders = new String[totalColumns];
for (int count=0; count<columnHeaders.length; count++){
columnHeaders[count] = getValue(headerRow.getCell(count));
}
return columnHeaders;
}

return null;
}

   Like      Feedback     Apache POI   get first row of xls


 Sample 522. Usage of org.springframework.security.web.util.matcher.RequestMatcher

RequestMatcher matcher = new RegexRequestMatcher("(.*/(html|php|htm)/.*)", RequestMethod.GET.name());
registry.addInterceptor(new MyInterceptor(matcher));

   Like      Feedback     rg.springframework.security.web.util.matcher.RequestMatche


 Sample 523. Usage of javax.servlet.http.Cookie

String password = "xyz";   
Cookie cookie = new Cookie("AuthPassword", password);
cookie.setMaxAge(cookieAge);
cookie.setPath("/");

   Like      Feedback     javax.servlet.http.Cookie


 Sample 524. Implementation of com.sun.jersey.api.core.DefaultResourceConfig

public class MyConfig extends DefaultResourceConfig {

private final Set<Class<?>> classes =
ImmutableSet.<Class<?>>of(SampleResource1.class, SampleResource2.class);

private final Set<Object> singletons =
ImmutableSet.<Object>of(
new JacksonJaxbJsonProvider().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true), new KryoProvider<Object>()
);

private final Map<String, MediaType> mediaTypeMapppings = ImmutableMap.of("json", MediaType.APPLICATION_JSON_TYPE);

public MyConfig() {
super();
}

@Override
public Set<Class<?>> getClasses() {
return classes;
}

@Override
public Set<Object> getSingletons() {
return singletons;
}

@Override
public Map<String, MediaType> getMediaTypeMappings() {
return mediaTypeMapppings;
}
}

   Like      Feedback     Implementation of DefaultResourceConfig   jersey


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 525. Print Marshaled XML for the Entity object

Employee employee = new Employee()
    .withEmployeeId(123)
    .withDeptId(456)
    .build();

JAXBContext context = JAXBContext.newInstance(Employee.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(employee, System.out); // prints XML for the object

   Like      Feedback     Marshalling  Marshal Object to XML   Object to XML


 Sample 526. Mark a method as deprecated

@Deprecated
public Employee getEmployee(int employeeId){

}

   Like      Feedback     deprecate   deprecated annotation


 Sample 527. Write a program / method that takes an array of integer and return the difference between the smallest and largest element ?


static int diff(int[] x){
   int smallest = x[0];
   int largest = x[0];
   for(int element: x){
      if(element < smallest){
         smallest = element;
      } else if(element > largest){
         largest = element;
      } else {
         continue;
      }
   }
   return largest-smallest;
}

   Like      Feedback     difference between the smallest and largest element   array


 Sample 528. Printing Stack trace using Apache Commons ExceptionUtils

try {

} catch (Exception ex){
   System.out.println(ExceptionUtils.getFullStackTrace(ex));
}

   Like      Feedback     Apache Commons ExceptionUtils  Apache commons


 Sample 529. Drools - Load Resource into KnowledgeBase

KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
knowledgeBuilder.add(ruleResource, ResourceType.DRL);
KnowledgeBuilderErrors knowledgeBuilderErrors = knowledgeBuilder.getErrors();
if (errors.size() > 0) {
   for (KnowledgeBuilderError knowledgeBuilderError : knowledgeBuilderErrors) {
      System.out.println(knowledgeBuilderError);
   }
} else {
   knowledgeBase.addKnowledgePackages(knowledgeBuilder.getKnowledgePackages());
}

   Like      Feedback     Load org.drools.io.Resource into org.drools.KnowledgeBase  Drools  Drools Engine


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 530. Code Sample / Example / Snippet of javax.servlet.ServletOutputStream

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {

ServletOutputStream output = null;

try {

output = response.getOutputStream();

output.println(request.getQueryString());

}

catch (IOException e) {

} finally {

if (output != null) {

try {

output.close();

}

catch (IOException e) {

}

}

}

}


   Like      Feedback      javax.servlet.ServletOutputStream


 Sample 531. Code Sample / Example / Snippet of org.osgi.service.useradmin.User

    private boolean authenticate(HttpServletRequest request) {

if (m_useAuth) {

User user = m_authService.authenticate(request);

if (user == null) {

m_logger.log(LogService.LOG_INFO, "Authentication failure!");

}

return (user != null);

}

return true;

}


   Like      Feedback      org.osgi.service.useradmin.User


 Sample 532. Code Sample / Example / Snippet of org.apache.felix.service.command.CommandSession

    private void executeScript(Dictionary<String, String> scriptDefinition) throws Exception {

String script = scriptDefinition.get(SCRIPT_KEY);

if (script == null) {

throw new IllegalArgumentException("Script definition *must* define at least a 'script' property!");

}



CommandSession session = m_processor.createSession(System.in, System.out, System.err);

try {

Object scriptResult = session.execute(script);

m_logger.log(LogService.LOG_DEBUG, "Script output: " + scriptResult);

}

finally {

session.close();

}

}


   Like      Feedback      org.apache.felix.service.command.CommandSession


 Sample 533. Code Sample / Example / Snippet of com.google.gson.JsonArray

    private void listRepositoryObjects(Workspace workspace, String entityType, HttpServletResponse resp) throws IOException {

List<RepositoryObject> objects = workspace.getRepositoryObjects(entityType);



JsonArray result = new JsonArray();

for (RepositoryObject ro : objects) {

String identity = ro.getDefinition();

if (identity != null) {

result.add(new JsonPrimitive(urlEncode(identity)));

}

}



resp.getWriter().println(m_gson.toJson(result));

}


   Like      Feedback      com.google.gson.JsonArray


 Sample 534. Code Sample / Example / Snippet of java.util.List

    private static List convertArrayToList(Object array)

{

int len = Array.getLength(array);

List list = new ArrayList(len);

for (int i = 0; i < len; i++)

{

list.add(Array.get(array, i));

}

return list;

}


   Like      Feedback      java.util.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 535. Code Sample / Example / Snippet of org.osgi.framework.wiring.BundleCapability

    private static Set<BundleCapability> matchMandatory(

Set<BundleCapability> caps, SimpleFilter sf)

{

for (Iterator<BundleCapability> it = caps.iterator(); it.hasNext(); )

{

BundleCapability cap = it.next();

if (!matchMandatory(cap, sf))

{

it.remove();

}

}

return caps;

}


   Like      Feedback      org.osgi.framework.wiring.BundleCapability


 Sample 536. Code Sample / Example / Snippet of org.osgi.service.http.HttpService

    public synchronized void addServlet(ServiceReference<Servlet> ref) {

String endpoint = (String) ref.getProperty(HttpConstants.ENDPOINT);

m_servlets.put(ref, endpoint);



Servlet servlet = m_context.getService(ref);

Dictionary<String, Object> initParams = getInitParams(ref);



for (ServiceReference<HttpService> reference : m_httpServices) {

HttpService httpService = m_context.getService(reference);

try {

if ((httpService != null) && (endpoint != null) && (servlet != null)) {

httpService.registerServlet(endpoint, servlet, initParams, null);

}

else {

m_log.log(LogService.LOG_WARNING, "Unable to register servlet with endpoint '" + endpoint + "'");

}

}

catch (Exception e) {

m_log.log(LogService.LOG_WARNING, "Already registered under existing endpoint", e);

}

}

}


   Like      Feedback      org.osgi.service.http.HttpService


 Sample 537. Code Sample / Example / Snippet of javax.servlet.Servlet

    public synchronized void addServlet(ServiceReference<Servlet> ref) {

String endpoint = (String) ref.getProperty(HttpConstants.ENDPOINT);

m_servlets.put(ref, endpoint);



Servlet servlet = m_context.getService(ref);

Dictionary<String, Object> initParams = getInitParams(ref);



for (ServiceReference<HttpService> reference : m_httpServices) {

HttpService httpService = m_context.getService(reference);

try {

if ((httpService != null) && (endpoint != null) && (servlet != null)) {

httpService.registerServlet(endpoint, servlet, initParams, null);

}

else {

m_log.log(LogService.LOG_WARNING, "Unable to register servlet with endpoint '" + endpoint + "'");

}

}

catch (Exception e) {

m_log.log(LogService.LOG_WARNING, "Already registered under existing endpoint", e);

}

}

}


   Like      Feedback      javax.servlet.Servlet


 Sample 538. Code Sample / Example / Snippet of com.vaadin.ui.TextField

    private TextField makeTextField(final String colType) {

TextField t = new TextField(colType);



t.addListener(new TextChangeListener() {

SimpleStringFilter filter = null;



public void textChange(TextChangeEvent event) {

Filterable f = (Filterable) m_table.getContainerDataSource();



if (filter != null) {

f.removeContainerFilter(filter);

}

filter = new SimpleStringFilter(colType, event.getText(), true /* ignoreCase */, false /* onlyMatchPrefix */);



f.addContainerFilter(filter);

}

});



return t;

}




   Like      Feedback      com.vaadin.ui.TextField


 Sample 539. Code Sample / Example / Snippet of javax.net.ssl.TrustManagerFactory

    private TrustManager[] getTrustManagerFactory(String truststoreFile, String storePass) throws IOException, GeneralSecurityException {

TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());



InputStream is = null;

try {

is = new FileInputStream(truststoreFile);



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

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



tmf.init(ks);



return tmf.getTrustManagers();

}

finally {

try {

if (is != null) {

is.close();

}

}

catch (IOException e) {

}

}

}


   Like      Feedback      javax.net.ssl.TrustManagerFactory


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 540. Code Sample / Example / Snippet of java.util.regex.Pattern

    private long getStoreId(File storeFile) {

Pattern p = Pattern.compile(m_name + "-(\d+)");

Matcher m = p.matcher(storeFile.getName());

if (m.find()) {

return Long.parseLong(m.group(1));

}

throw new RuntimeException("Invalid store file name: " + storeFile.getName());

}




   Like      Feedback      java.util.regex.Pattern


 Sample 541. Code Sample / Example / Snippet of javax.net.ssl.KeyManagerFactory

    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      javax.net.ssl.KeyManagerFactory


 Sample 542. Code Sample / Example / Snippet of org.apache.ace.agent.EventsHandler

    protected void onStop() throws Exception {

EventsHandler eventsHandler = getEventsHandler();

if (eventsHandler != null) {

eventsHandler.removeListener(this);

}

if (m_updateInstaller != null) {

m_updateInstaller.reset();

m_updateInstaller = null;

}

}


   Like      Feedback      org.apache.ace.agent.EventsHandler


 Sample 543. Code Sample / Example / Snippet of java.util.concurrent.ScheduledExecutorService

    public void postEvent(final String topic, Map<String, String> payload) {

final Map<String, String> eventPayload = new HashMap<>(payload);

for (final EventListener listener : m_listeners) {

ScheduledExecutorService executor = getExecutorService();

if (executor.isShutdown()) {

logWarning("Cannot post event, executor is shut down!");

return;

}

executor.submit(new Runnable() {

@Override

public void run() {

try {

listener.handle(topic, eventPayload);

}

catch (Exception e) {

logWarning("Exception while posting event", e);

}

}

});

}

}


   Like      Feedback      java.util.concurrent.ScheduledExecutorService


 Sample 544. Code Sample / Example / Snippet of org.osgi.framework.FrameworkEvent

    public void testWriteEvent() throws Exception {

FrameworkEvent event = new FrameworkEvent(32, new Object());

m_eventLogger.frameworkEvent(event);



FeedbackHandler feedbackHandler = m_agentContext.getHandler(FeedbackHandler.class);

TestFeedbackChannel channel = (TestFeedbackChannel) feedbackHandler.getChannel("auditlog");

assertEquals(channel.getLastTtype(), 1001);



}


   Like      Feedback      org.osgi.framework.FrameworkEvent


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 545. Code Sample / Example / Snippet of org.apache.ace.agent.DeploymentHandler

    public void testAvailableVersions() throws Exception {

DeploymentHandler deploymentHandler = m_agentContext.getHandler(DeploymentHandler.class);

SortedSet<Version> expected = new TreeSet<>();

expected.add(m_version1);

expected.add(m_version2);

expected.add(m_version3);

SortedSet<Version> available = deploymentHandler.getAvailableVersions();

assertNotNull(available);

assertFalse(available.isEmpty());

assertEquals(available, expected);

}


   Like      Feedback      org.apache.ace.agent.DeploymentHandler


 Sample 546. Code Sample / Example / Snippet of java.security.DigestOutputStream

    public void setUpTestCase() throws Exception {

File file = File.createTempFile("test", ".bin", new File("generated"));

file.deleteOnExit();



DigestOutputStream dos = null;

try {

dos = new DigestOutputStream(new FileOutputStream(file), MessageDigest.getInstance("MD5"));



for (int i = 0; i < 10000; i++) {

dos.write(String.valueOf(System.currentTimeMillis()).getBytes());

dos.write(" Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum ".getBytes());

}

dos.flush();

}

finally {

if (dos != null) {

dos.close();

}

}



m_testContentURL = file.toURI().toURL();

m_contentLength = file.length();

m_digest = new String(dos.getMessageDigest().digest());

}


   Like      Feedback      java.security.DigestOutputStream


 Sample 547. Code Sample / Example / Snippet of org.apache.ace.agent.DiscoveryHandler

    public void testAvailableURL() throws Exception {

ConfigurationHandler configurationHandler = m_agentContext.getHandler(ConfigurationHandler.class);



configureAgent(configurationHandler,

AgentConstants.CONFIG_DISCOVERY_SERVERURLS, concat(m_availableURL1, m_availableURL2),

AgentConstants.CONFIG_DISCOVERY_CHECKING, "true");



DiscoveryHandler discoveryHandler = m_agentContext.getHandler(DiscoveryHandler.class);

assertEquals(discoveryHandler.getServerUrl(), m_availableURL1);

}


   Like      Feedback      org.apache.ace.agent.DiscoveryHandler


 Sample 548. Code Sample / Example / Snippet of org.apache.ace.agent.ConnectionHandler

    public void testDoubleClosedStreamOk() throws Exception {

ConnectionHandler handler = new TestConnectionHandler(new CompleteContentConnection(m_content, true));



ContentRangeInputStream is = new ContentRangeInputStream(handler, m_testURL);

is.close(); // simulate an early close...

is.close(); // not a problem...

}


   Like      Feedback      org.apache.ace.agent.ConnectionHandler


 Sample 549. Code Sample / Example / Snippet of org.apache.ace.agent.DownloadHandle

    public void testFailed404_noresume_result() throws Exception {

DownloadHandler downloadHandler = m_agentContext.getHandler(DownloadHandler.class);



DownloadHandle handle = downloadHandler.getHandle(m_404url);

Future<DownloadResult> future = handle.start(null);



assertIOException(future);

}


   Like      Feedback      org.apache.ace.agent.DownloadHandle


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 550. Code Sample / Example / Snippet of org.apache.ace.agent.ConfigurationHandler

    public void testSingleFeedbackChannelConfig() throws Exception {

ConfigurationHandler configurationHandler = m_agentContextImpl.getHandler(ConfigurationHandler.class);



configureAgent(configurationHandler, CONFIG_FEEDBACK_CHANNELS, AUDITLOG);



FeedbackHandler feedbackHandler = m_agentContextImpl.getHandler(FeedbackHandler.class);



assertFeedbackChannelNames(feedbackHandler, AUDITLOG);

assertFeedbackChannelsPresent(feedbackHandler, AUDITLOG);

}


   Like      Feedback      org.apache.ace.agent.ConfigurationHandler


 Sample 551. Code Sample / Example / Snippet of org.apache.ace.agent.DownloadHandler

    public void testFailed404_noresume_result() throws Exception {

DownloadHandler downloadHandler = m_agentContext.getHandler(DownloadHandler.class);



DownloadHandle handle = downloadHandler.getHandle(m_404url);

Future<DownloadResult> future = handle.start(null);



assertIOException(future);

}


   Like      Feedback      org.apache.ace.agent.DownloadHandler


 Sample 552. Code Sample / Example / Snippet of java.security.DigestInputStream

    private String getDigest(InputStream is) throws Exception {

DigestInputStream dis = new DigestInputStream(is, MessageDigest.getInstance("MD5"));

while (dis.read() != -1) {

}

dis.close();

return new String(dis.getMessageDigest().digest());

}


   Like      Feedback      java.security.DigestInputStream


 Sample 553. Code Sample / Example / Snippet of org.apache.ace.agent.IdentificationHandler

    public void testAvailableIdentification() throws Exception {

ConfigurationHandler configurationHandler = m_agentContext.getHandler(ConfigurationHandler.class);

reset(configurationHandler);

expect(configurationHandler.get(eq(AgentConstants.CONFIG_IDENTIFICATION_AGENTID), anyObject(String.class)))

.andReturn("qqq").once();

replay(configurationHandler);

IdentificationHandler identificationHandler = m_agentContext.getHandler(IdentificationHandler.class);

assertEquals(identificationHandler.getAgentId(), "qqq");

}


   Like      Feedback      org.apache.ace.agent.IdentificationHandler


 Sample 554. Code Sample / Example / Snippet of org.eclipse.jetty.servlet.ServletHolder

    public TestWebServer(int port, String contextPath, String basePath) throws Exception {

m_server = new Server(port);



m_contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);

m_contextHandler.setContextPath("/");



ServletHolder holder = new ServletHolder(new DefaultServlet());

holder.setInitParameter("resourceBase", basePath);

holder.setInitParameter("pathInfoOnly", "true");

holder.setInitParameter("acceptRanges", "true");

holder.setInitParameter("dirAllowed", "true");



m_contextHandler.addFilter(new FilterHolder(new HttpDumpFilter()), "/*", null);

m_contextHandler.addServlet(holder, contextPath.concat(contextPath.endsWith("/") ? "*" : "/*"));

m_server.setHandler(m_contextHandler);

}


   Like      Feedback      org.eclipse.jetty.servlet.ServletHolder


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 555. Code Sample / Example / Snippet of static org.easymock.EasyMock.expect

    public void testAuthenticateKnownUserWithExpiredCertificateYieldsNull() {

X509Certificate[] certificateChain = createExpiredCertificateChain("bob");

PublicKey publickey = certificateChain[0].getPublicKey();



when(m_servletRequest.getAttribute(ATTRIBUTE_X509_CERTIFICATE)).thenReturn(certificateChain);



User user = mock(User.class);

when(user.getName()).thenReturn("bob");

when(user.hasCredential(eq("publickey"), eq(publickey.getEncoded()))).thenReturn(Boolean.TRUE);



when(m_userAdmin.getUser(eq("username"), eq("bob"))).thenReturn(user);



User result = createAuthorizationProcessor().authenticate(m_userAdmin, m_servletRequest);

assert result == null : "Did not expect a valid user to be returned!";

}


   Like      Feedback      static org.easymock.EasyMock.expect


 Sample 556. Code Sample / Example / Snippet of org.apache.ace.agent.impl.AgentContextImpl

    protected AgentContextImpl mockAgentContext(String subDir) throws Exception {

if (m_contextDir != null) {

cleanDir(m_contextDir);

m_contextDir.delete();

}

m_contextDir = new File(getWorkDir(), subDir);

m_contextDir.mkdirs();

cleanDir(m_contextDir);



AgentContextImpl context = new AgentContextImpl(m_contextDir);

for (Class<?> handlerClass : AgentContextImpl.KNOWN_HANDLERS) {

if (ScheduledExecutorService.class.equals(handlerClass)) {

context.setHandler(ScheduledExecutorService.class, new SynchronousExecutorService());

}

else {

setMockedHandler(context, handlerClass);

}

}

return context;

}


   Like      Feedback      org.apache.ace.agent.impl.AgentContextImpl


 Sample 557. Code Sample / Example / Snippet of org.apache.ace.client.repository.helper.ArtifactHelper

    public List<ArtifactObject> get() {

try {

return super.get(createFilter("(!(" + RepositoryUtil.escapeFilterValue(BundleHelper.KEY_RESOURCE_PROCESSOR_PID) + "=*))"));

}

catch (InvalidSyntaxException e) {

m_log.log(LogService.LOG_ERROR, "get's filter returned an InvalidSyntaxException.", e);

}

return new ArrayList<>();

}



@Override

ArtifactObjectImpl createNewInhabitant(Map<String, String> attributes, Map<String, String> tags) {

ArtifactHelper helper = getHelper(attributes.get(ArtifactObject.KEY_MIMETYPE));

ArtifactObjectImpl ao = new ArtifactObjectImpl(helper.checkAttributes(attributes), helper.getMandatoryAttributes(), tags, this, this);

return ao;

}


   Like      Feedback      org.apache.ace.client.repository.helper.ArtifactHelper


 Sample 558. Code Sample / Example / Snippet of org.apache.ace.client.repository.helper.ArtifactPreprocessor

    public String preprocessArtifact(ArtifactObject artifact, TargetObject target, String targetID, String version) throws IOException {

ArtifactPreprocessor preprocessor = getHelper(artifact.getMimetype()).getPreprocessor();

if (preprocessor == null) {

return artifact.getURL();

}

else {

return preprocessor.preprocess(artifact.getURL(), new TargetPropertyResolver(target), targetID, version, getObrBase());

}

}


   Like      Feedback      org.apache.ace.client.repository.helper.ArtifactPreprocessor


 Sample 559. Code Sample / Example / Snippet of org.osgi.service.prefs.Preferences

    private Preferences getRepositoryPrefs(Preferences userPrefs, URL location, String customer, String name) {

Preferences repoPref = userPrefs.node(location.getAuthority() + location.getPath());

Preferences customerPref = repoPref.node(customer);

return customerPref.node(name);

}


   Like      Feedback      org.osgi.service.prefs.Preferences


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 560. Code Sample / Example / Snippet of org.apache.ace.client.repository.RepositoryObject.WorkingState

public WorkingState getWorkingState(RepositoryObject object) {
WorkingState result = null;
synchronized(m_lock) {
for (RepositorySet set: m_repositorySets) {
result = set.getWorkingState(object);
if (result != null) {
break;
}
}
}
return (result == null) ? WorkingState.Unchanged : result;
}

   Like      Feedback      org.apache.ace.client.repository.RepositoryObject.WorkingState   synchronized


 Sample 561. Code Sample / Example / Snippet of static org.apache.ace.client.repository.repository.RepositoryConstants.KEY_OBR_LOCATION

public interface RepositoryConstants {

String KEY_SHOW_UNREGISTERED_TARGETS = "showunregisteredtargets";



String KEY_DEPLOYMENT_VERSION_LIMITS = "deploymentversionlimit";



String KEY_OBR_LOCATION = "obrlocation";



}


   Like      Feedback      static org.apache.ace.client.repository.repository.RepositoryConstants.KEY_OBR_LOCATION


 Sample 562. Code Sample / Example / Snippet of static org.apache.ace.client.repository.repository.RepositoryConstants.KEY_DEPLOYMENT_VERSION_LIMITS

public interface RepositoryConstants {

String KEY_SHOW_UNREGISTERED_TARGETS = "showunregisteredtargets";



String KEY_DEPLOYMENT_VERSION_LIMITS = "deploymentversionlimit";



String KEY_OBR_LOCATION = "obrlocation";



}


   Like      Feedback      static org.apache.ace.client.repository.repository.RepositoryConstants.KEY_DEPLOYMENT_VERSION_LIMITS


 Sample 563. Code Sample / Example / Snippet of java.util.concurrent.locks.Lock

    public int getDeploymentVersionLimit() {

Lock lock = m_lock.readLock();

lock.lock();

try {

return m_deploymentVersionLimit;

}

finally {

lock.unlock();

}

}


   Like      Feedback      java.util.concurrent.locks.Lock


 Sample 564. Code Sample / Example / Snippet of static org.apache.ace.client.repository.repository.RepositoryConstants.KEY_SHOW_UNREGISTERED_TARGETS

public interface RepositoryConstants {

String KEY_SHOW_UNREGISTERED_TARGETS = "showunregisteredtargets";



String KEY_DEPLOYMENT_VERSION_LIMITS = "deploymentversionlimit";



String KEY_OBR_LOCATION = "obrlocation";



}


   Like      Feedback      static org.apache.ace.client.repository.repository.RepositoryConstants.KEY_SHOW_UNREGISTERED_TARGETS


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

    private byte[] process(byte[] input, PropertyResolver props) throws IOException {

VelocityContext context = new VelocityContext();

context.put("context", props);

try {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

Writer writer = new OutputStreamWriter(baos);

Velocity.evaluate(context, writer, "", new InputStreamReader(new ByteArrayInputStream(input)));

writer.flush();

return baos.toByteArray();

}

catch (IOException ioe) {

throw new IOException("Error processing the artifact: " + ioe.getMessage());

}

}


   Like      Feedback      org.apache.velocity.VelocityContext


 Sample 566. Code Sample / Example / Snippet of org.xml.sax.Attributes

    public InputStream getDeploymentPackage(String id, String version) throws OverloadedException, IOException {

List<ArtifactData> data = m_provider.getBundleData(id, version);

Manifest manifest = new Manifest();

Attributes main = manifest.getMainAttributes();



main.putValue("Manifest-Version", "1.0");

main.putValue("DeploymentPackage-SymbolicName", id);

main.putValue("DeploymentPackage-Version", version);



for (ArtifactData bd : data) {

manifest.getEntries().put(bd.getFilename(), bd.getManifestAttributes(false));

}



return DeploymentPackageStream.createStreamForThread(m_connectionFactory, manifest, data.iterator(), false);

}


   Like      Feedback      org.xml.sax.Attributes


 Sample 567. Code Sample / Example / Snippet of org.apache.ace.client.repository.helper.base.VelocityArtifactPreprocessor

    public void testNeedsNewVersionChangedTemplateOk() throws Exception {

final VelocityArtifactPreprocessor vap = createProcessor();



String url = createArtifact("Message: [$context.msg]");



vap.preprocess(url, m_resolver, TARGET, VERSION1, m_obrUrl);



boolean result = vap.needsNewVersion(url, m_resolver, TARGET, VERSION1);

assertFalse(result); // no new version is needed...



updateArtifact(url, "Another message: [$context.msg2]");



result = vap.needsNewVersion(url, m_resolver, TARGET, VERSION1);

assertFalse(result); // no new version is needed; original artifact is cached indefinitely...

}


   Like      Feedback      org.apache.ace.client.repository.helper.base.VelocityArtifactPreprocessor


 Sample 568. Code Sample / Example / Snippet of org.apache.ace.repository.ext.BackupRepository

    public void testInitialCheckout() throws IllegalArgumentException, IOException {

Repository m_repository = new MockRepository();

byte[] testContent = new byte[] {'i', 'n', 'i', 't', 'i', 'a', 'l'};

m_repository.commit(new ByteArrayInputStream(testContent), 0);

BackupRepository m_backupRepository = new MockBackupRepository();



CachedRepository m_cachedRepository = new CachedRepositoryImpl(m_repository, m_backupRepository, 0);



InputStream input = m_cachedRepository.checkout(1);

byte[] inputBytes = AdminTestUtil.copy(input);

assert AdminTestUtil.byteArraysEqual(inputBytes, testContent) : "We got something different than 'initial' from checkout: " + new String(inputBytes);

input = m_cachedRepository.getLocal(false);

inputBytes = AdminTestUtil.copy(input);

assert AdminTestUtil.byteArraysEqual(inputBytes, testContent) : "We got something different than 'initial' from getLocal: " + new String(inputBytes);

input = m_backupRepository.read();

inputBytes = AdminTestUtil.copy(input);

assert AdminTestUtil.byteArraysEqual(inputBytes, testContent) : "We got something different than 'initial' from the backup repository: " + new String(inputBytes);

}


   Like      Feedback      org.apache.ace.repository.ext.BackupRepository


 Sample 569. Code Sample / Example / Snippet of org.apache.ace.client.repository.object.TargetObject

    public void testDistribution2TargetAssociations() {

initializeRepositoryAdmin();

DistributionObject d1 = createBasicDistributionObject("distribution1");

TargetObject t1 = createBasicTargetObject("target1");

m_distribution2TargetRepository.create(d1, t1);



assert d1.getFeatures().size() == 0 : "Distribution 1 should not be associated with any features; it is associated with " + d1.getFeatures().size() + ".";

assert d1.getTargets().size() == 1 : "Distribution 1 should be associated with exactly one target; it is associated with " + d1.getTargets().size() + ".";



assert t1.getDistributions().size() == 1 : "Target 1 should be associated with exactly one distribution; it is associated with " + t1.getDistributions().size() + ".";

}


   Like      Feedback      org.apache.ace.client.repository.object.TargetObject


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 570. Code Sample / Example / Snippet of org.osgi.framework.BundleContext

    public void init() {

BundleContext bc = TestUtils.createMockObjectAdapter(BundleContext.class, new Object() {

@SuppressWarnings("unused")

public Filter createFilter(String filter) throws InvalidSyntaxException {

return FrameworkUtil.createFilter(filter);

}

});



m_artifactRepository = new ArtifactRepositoryImpl(TestUtils.createNullObject(ChangeNotifier.class), new RepositoryConfigurationImpl());

TestUtils.configureObject(m_artifactRepository, LogService.class);

TestUtils.configureObject(m_artifactRepository, BundleContext.class, bc);

}


   Like      Feedback      org.osgi.framework.BundleContext


 Sample 571. Code Sample / Example / Snippet of org.apache.ace.client.repository.object.Feature2DistributionAssociation

    public void TestFeature2DistributionAssociations() {

initializeRepositoryAdmin();

FeatureObject f1 = createBasicFeatureObject("feature1");

DistributionObject d1 = createBasicDistributionObject("distribution1");

Feature2DistributionAssociation f2d1 = m_feature2DistributionRepository.create(f1, d1);



assert (f2d1.getLeft().size() == 1) && f2d1.getLeft().contains(f1) : "Left side of the association should be our feature.";

assert (f2d1.getRight().size() == 1) && f2d1.getRight().contains(d1) : "Right side of the association should be our distribution.";



assert f1.getArtifacts().size() == 0 : "Feature 1 should not be associated with any artifacts; it is associated with " + f1.getArtifacts().size() + ".";

assert f1.getDistributions().size() == 1 : "Feature 1 should be associated with exactly one distribution; it is associated with " + f1.getDistributions().size() + ".";



assert d1.getFeatures().size() == 1 : "Distribution 1 should be associated with exactly one feature; it is associated with " + d1.getFeatures().size() + ".";

assert d1.getTargets().size() == 0 : "Distribution 1 should not be associated with any targets; it is associated with " + d1.getTargets().size() + ".";

}


   Like      Feedback      org.apache.ace.client.repository.object.Feature2DistributionAssociation


 Sample 572. Code Sample / Example / Snippet of org.apache.ace.client.repository.object.DeploymentVersionObject

    public void testDeploymentRepository() {

DeploymentVersionObject version11 = createBasicDeploymentVersionObject("target1", "1", new String[] { "artifact1", "artifact2" });

DeploymentVersionObject version12 = createBasicDeploymentVersionObject("target1", "2", new String[] { "artifact3", "artifact4" });

DeploymentVersionObject version22 = createBasicDeploymentVersionObject("target2", "2", new String[] { "artifactC", "artifactD" });

DeploymentVersionObject version21 = createBasicDeploymentVersionObject("target2", "1", new String[] { "artifactA", "artifactB" });



assert m_deploymentVersionRepository.getDeploymentVersions("NotMyTarget").size() == 0 : "The deployment repository should not return" +

"any versions when we ask for a target that does not exist, but it returns " + m_deploymentVersionRepository.getDeploymentVersions("NotMyTarget").size();



List<DeploymentVersionObject> for1 = m_deploymentVersionRepository.getDeploymentVersions("target1");

assert for1.size() == 2 : "We expect two versions for target1, but we find " + for1.size();

assert for1.get(0) == version11 : "The first version for target1 should be version11";

assert for1.get(1) == version12 : "The second version for target1 should be version12";



List<DeploymentVersionObject> for2 = m_deploymentVersionRepository.getDeploymentVersions("target2");

assert for2.size() == 2 : "We expect two versions for target2, but we find " + for2.size();

assert for2.get(0) == version21 : "The first version for target2 should be version21";

assert for2.get(1) == version22 : "The second version for target2 should be version22";



assert m_deploymentVersionRepository.getMostRecentDeploymentVersion("NotMyTarget") == null : "The most recent version for a non-existent target should not exist.";

assert m_deploymentVersionRepository.getMostRecentDeploymentVersion("target1") == version12 : "The most recent version for target1 should be version12";

assert m_deploymentVersionRepository.getMostRecentDeploymentVersion("target2") == version22 : "The most recent version for target2 should be version22";

}


   Like      Feedback      org.apache.ace.client.repository.object.DeploymentVersionObject


 Sample 573. Code Sample / Example / Snippet of org.apache.ace.client.repository.object.Artifact2FeatureAssociation

    public void testGetAssociationsWith() {

initializeRepositoryAdmin();

ArtifactObject a1 = createBasicArtifactObject("artifact1");

FeatureObject f1 = createBasicFeatureObject("feature1");

Artifact2FeatureAssociation a2f1 = m_artifact2FeatureRepository.create(a1, f1);



List<Artifact2FeatureAssociation> b1Associations = a1.getAssociationsWith(f1);

List<Artifact2FeatureAssociation> g1Associations = f1.getAssociationsWith(a1);



assert b1Associations.size() == 1 : "The artifact has exactly one association to the feature, but it shows " + b1Associations.size() + ".";

assert b1Associations.get(0) == a2f1 : "The artifact's association should be the one we created.";



assert g1Associations.size() == 1 : "The feature has exactly one association to the artifact.";

assert g1Associations.get(0) == a2f1 : "The feature's association should be the one we created.";

}


   Like      Feedback      org.apache.ace.client.repository.object.Artifact2FeatureAssociation


 Sample 574. Code Sample / Example / Snippet of java.io.FileWriter

    private String createArtifact(String string) throws IOException {

File tmpFile = File.createTempFile("vap", "vm");

tmpFile.delete();

tmpFile.deleteOnExit();



FileWriter writer = new FileWriter(tmpFile);

writer.write(string);

writer.flush();

writer.close();



return tmpFile.toURI().toURL().toExternalForm();

}


   Like      Feedback      java.io.FileWriter


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 575. Code Sample / Example / Snippet of java.util.Iterator

    public void validateRangeIterators() {

SortedRangeSet srs1 = new SortedRangeSet("1-10");

Iterator i1 = srs1.rangeIterator();

assert i1.hasNext() : "We should have one Range instance in our iterator.";

assert ((Range) i1.next()).toRepresentation().equals("1-10");

assert !i1.hasNext() : "There should be only one instance in our iterator.";

SortedRangeSet srs2 = new SortedRangeSet("1-5,8,10-15");

Iterator i2 = srs2.rangeIterator();

assert i2.hasNext() && i2.next() instanceof Range

&& i2.hasNext() && i2.next() instanceof Range

&& i2.hasNext() && i2.next() instanceof Range

&& !i2.hasNext() : "There should be exactly three Range instances in our iterator.";

SortedRangeSet srs3 = new SortedRangeSet("");

assert !srs3.iterator().hasNext() : "Iterator should be empty.";

}


   Like      Feedback      java.util.Iterator


 Sample 576. Code Sample / Example / Snippet of java.io.ByteArrayOutputStream

            public int compare(ResourceImpl r1, ResourceImpl r2) {

String s1 = getName(r1);

String s2 = getName(r2);

return s1.compareTo(s2);

}

});



Tag tag = doIndex(sorted);

if (repositoryFileName != null) {

ByteArrayOutputStream out = new ByteArrayOutputStream();


   Like      Feedback      java.io.ByteArrayOutputStream


 Sample 577. Code Sample / Example / Snippet of java.util.Set

    public Set getExtendList() {

Set set = new HashSet();

for (Iterator i = requirements.iterator(); i.hasNext();) {

RequirementImpl impl = (RequirementImpl) i.next();

if (impl.isExtend())

set.add(impl);

}

return set;

}


   Like      Feedback      java.util.Set


 Sample 578. Code Sample / Example / Snippet of org.osgi.impl.bundle.obr.resource.ResourceImpl

    public boolean equals(Object o) {

try {

ResourceImpl other = (ResourceImpl) o;

return symbolicName.equals(other.symbolicName)

&& version.equals(other.version);

}

catch (ClassCastException e) {

return false;

}

}


   Like      Feedback      org.osgi.impl.bundle.obr.resource.ResourceImpl


 Sample 579. Code Sample / Example / Snippet of org.osgi.impl.bundle.obr.resource.RepositoryImpl

    public void testCheckoutAndCommitWithChangeDoesChangeVersion() throws Exception {

SortedRangeSet range;

RepositoryImpl repo = new RepositoryImpl(new File(m_baseDir, "data"), new File(m_baseDir, "tmp"), true);

InputStream data = new ByteArrayInputStream("abc".getBytes());



assertTrue(repo.put(data, 1), "Put should have succeeded");



range = repo.getRange();

assertEquals(1, range.getHigh(), "Version 1 should be the most recent one");



InputStream is = repo.checkout(1);

assertNotNull(is, "Nothing checked out?!");



data = new ByteArrayInputStream("def".getBytes());



assertTrue(repo.commit(data, 1), "Commit should NOT be ignored");



range = repo.getRange();

assertEquals(2, range.getHigh());

}


   Like      Feedback      org.osgi.impl.bundle.obr.resource.RepositoryImpl


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 580. Code Sample / Example / Snippet of org.apache.ace.obr.metadata.MetadataGenerator

    public void generateMetaData() throws Exception {

File dir = File.createTempFile("meta", "");

dir.delete();

dir.mkdir();

generateBundle(File.createTempFile("bundle", ".jar", dir), "bundle.symbolicname.1", "1.0.0");

generateBundle(File.createTempFile("bundle", ".jar", dir), "bundle.symbolicname.2", "1.0.0");

generateBundle(File.createTempFile("bundle", ".jar", dir), "bundle.symbolicname.3", "1.0.0");

MetadataGenerator meta = new BIndexMetadataGenerator();

meta.generateMetadata(dir);

File index = new File(dir, "repository.xml");

assert index.exists() : "No repository index was generated";

assert index.length() > 0 : "Repository index can not be size 0";

int count = 0;

String line;

BufferedReader in = new BufferedReader(new FileReader(index));

while ((line = in.readLine()) != null) {

if (line.contains("<resource")) {

count++;

}

}

in.close();

assert count == 3 : "Expected 3 resources in the repository index, found " + count + ".";

}


   Like      Feedback      org.apache.ace.obr.metadata.MetadataGenerator


 Sample 581. Code Sample / Example / Snippet of java.util.Random

    private File createRandomFileWithContent() throws IOException {

OutputStream fileOut = null;

File file = null;

try {

file = FileUtils.createTempFile(null);

fileOut = new FileOutputStream(file);

byte[] byteArray = new byte[12345];

Random randomContentCreator = new Random();

randomContentCreator.nextBytes(byteArray);

fileOut.write(byteArray);



return file;

}

finally {

try {

if (fileOut != null) {

fileOut.close();

}

}

catch (IOException e) {

throw e;

}

}

}


   Like      Feedback      java.util.Random


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

	public LowestID(String representation) {

try {

StringTokenizer st = new StringTokenizer(representation, ",");

m_targetID = Codec.decode(st.nextToken());

m_storeID = Long.parseLong(st.nextToken());

m_lowestID = Long.parseLong(st.nextToken());

}

catch (NoSuchElementException e) {

throw new IllegalArgumentException("Could not create lowest ID object from: " + representation);

}

}


   Like      Feedback      java.util.StringTokenizer


 Sample 583. Code Sample / Example / Snippet of org.apache.ace.feedback.Descriptor

    public synchronized void getRange() throws Exception {

final Descriptor range = new Descriptor(TARGET_ID, 1, new SortedRangeSet("1-10"));

m_task.getDescriptor(new InputStream() {

int m_count = 0;

byte[] m_bytes = (range.toRepresentation() + " ").getBytes();

@Override

public int read() throws IOException {

if (m_count < m_bytes.length) {

byte b = m_bytes[m_count];

m_count++;

return b;

} else {

return -1;

}

}

});

}


   Like      Feedback      org.apache.ace.feedback.Descriptor


 Sample 584. Code Sample / Example / Snippet of org.apache.ace.log.target.store.impl.LogStoreImpl

    public void testTimedWrite() throws Exception {

File storeFile = File.createTempFile("feedback", ".store");

storeFile.deleteOnExit();



final int recordCount = 10000;



final LogStoreImpl store = createLogStore();



long start = System.nanoTime();

for (int i = 0; i < recordCount; i++) {

store.put(Arrays.asList(new Event("1,2,3,4,5")));

}

long end = System.nanoTime();

System.out.printf("Writing %d records took %.3f ms.%n", recordCount, (end - start) / 1.0e6);

}


   Like      Feedback      org.apache.ace.log.target.store.impl.LogStoreImpl


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 585. Code Sample / Example / Snippet of org.apache.ace.range.SortedRangeSet

    private void verifyStoreContents(final LogStoreImpl store, final int count, Writer... writers) throws IOException {

List<Descriptor> descriptors = store.getDescriptors();



long expectedID = 0;

for (Descriptor desc : descriptors) {

SortedRangeSet rangeSet = desc.getRangeSet();

RangeIterator rangeIter = rangeSet.iterator();



while (rangeIter.hasNext()) {

long id = rangeIter.next();



Event expectedEntry = null;

for (int i = 0; (expectedEntry == null) && i < writers.length; i++) {

expectedEntry = writers[i].m_written.remove(id);

}

assertNotNull(expectedEntry, "Event ID #" + id + " never written?!");

assertEquals(expectedEntry.getID(), expectedID++, "Entry ID mismatch?!");

}

}

}


   Like      Feedback      org.apache.ace.range.SortedRangeSet


 Sample 586. Code Sample / Example / Snippet of static org.apache.ace.test.utils.TestUtils.UNIT

public class WorkspaceManagerImplTest {

@SuppressWarnings("serial")

@Test(groups = { UNIT })

public void testPropertyGetter() {

WorkspaceManagerImpl s = new WorkspaceManagerImpl();

Assert.assertEquals(s.getProperty(new Properties() {{ put("key", "value"); }}, "key", "notused"), "value");

Assert.assertEquals(s.getProperty(new Properties() {{ put("unusedkey", "value"); }}, "key", "default"), "default");

Assert.assertEquals(s.getProperty(null, "key", "default"), "default");

}

}


   Like      Feedback      static org.apache.ace.test.utils.TestUtils.UNIT


 Sample 587. Code Sample / Example / Snippet of org.apache.ace.range.RangeIterator

    private void verifyStoreContents(final LogStoreImpl store, final int count, Writer... writers) throws IOException {

List<Descriptor> descriptors = store.getDescriptors();



long expectedID = 0;

for (Descriptor desc : descriptors) {

SortedRangeSet rangeSet = desc.getRangeSet();

RangeIterator rangeIter = rangeSet.iterator();



while (rangeIter.hasNext()) {

long id = rangeIter.next();



Event expectedEntry = null;

for (int i = 0; (expectedEntry == null) && i < writers.length; i++) {

expectedEntry = writers[i].m_written.remove(id);

}

assertNotNull(expectedEntry, "Event ID #" + id + " never written?!");

assertEquals(expectedEntry.getID(), expectedID++, "Entry ID mismatch?!");

}

}

}


   Like      Feedback      org.apache.ace.range.RangeIterator


 Sample 588. Code Sample / Example / Snippet of org.osgi.service.useradmin.UserAdmin

    protected final User createUser(String name) {

UserAdmin useradmin = getService(UserAdmin.class);

User user = (User) useradmin.createRole(name, Role.USER);

if (user == null) {

user = useradmin.getUser("username", name);

}

else {

user.getProperties().put("username", name);

}

return user;

}


   Like      Feedback      org.osgi.service.useradmin.UserAdmin


 Sample 589. Code Sample / Example / Snippet of java.io.ByteArrayInputStream

    protected final void importSingleUser(Repository userRepository, String userName, String password) throws Exception {

ByteArrayInputStream bis = new ByteArrayInputStream((

"<roles>" +

"<user name="" + userName + "">" +

"<properties><username>" + userName + "</username></properties>" +

"<credentials><password type="String">" + password + "</password></credentials>" +

"</user>" +

"</roles>").getBytes());



Assert.assertTrue("Committing test user data failed!", userRepository.commit(bis, userRepository.getRange().getHigh()));

}


   Like      Feedback      java.io.ByteArrayInputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 590. Code Sample / Example / Snippet of java.io.Writer

    private File createFileWithContents(String name, String extension, String contents) throws IOException {

File file = File.createTempFile(name, extension);

file.deleteOnExit();

Writer w = new OutputStreamWriter(new FileOutputStream(file));

w.write(contents);

w.close();

return file;

}




   Like      Feedback      java.io.Writer


 Sample 591. Code Sample / Example / Snippet of org.apache.ace.feedback.Event

    private Event createEvent(String version, URL dataURL) {

Dictionary<String, Object> properties = new Hashtable<>();

properties.put("deploymentpackage.url", dataURL.toString());

properties.put("deploymentpackage.version", version);

Event event = new Event(TOPIC_DEPLOYMENTPACKAGE_INSTALL, properties);

return event;

}


   Like      Feedback      org.apache.ace.feedback.Event


 Sample 592. Code Sample / Example / Snippet of java.util.concurrent.CountDownLatch

    public void testTooLongTask() throws Exception {

final CountDownLatch latch = new CountDownLatch(5);



Executer executer = new Executer(new Runnable() {

public void run() {

try {

Thread.sleep(20);

latch.countDown();

}

catch (InterruptedException e) {

e.printStackTrace();

}

}

});

executer.start(10);

assert latch.await(1, TimeUnit.SECONDS);

}


   Like      Feedback      java.util.concurrent.CountDownLatch


 Sample 593. Code Sample / Example / Snippet of org.osgi.service.useradmin.Authorization

    public Group getGroup(User user) {

Authorization auth = m_useradmin.getAuthorization(user);

String[] roles = auth.getRoles();

if (roles != null) {

for (String role : roles) {

Role result = m_useradmin.getRole(role);

if (result.getType() == Role.GROUP) {

Group group = (Group) result;

Role[] members = group.getMembers();

if (members != null) {

for (Role r : members) {

if (r.getType() == Role.USER && r.getName().equals(user.getName())) {

return group;

}

}

}

}

}

}

return null;

}


   Like      Feedback      org.osgi.service.useradmin.Authorization


 Sample 594. Code Sample / Example / Snippet of javax.naming.ldap.LdapName

    private String getName(X509Certificate certificate) {

try {

String dn = certificate.getSubjectX500Principal().getName();

if ("dn".equalsIgnoreCase(m_nameMatchPolicy)) {

return dn;

}



LdapName ldapDN = new LdapName(dn);

for (Rdn rdn : ldapDN.getRdns()) {

if (m_nameMatchPolicy.equalsIgnoreCase(rdn.getType())) {

return (String) rdn.getValue();

}

}

}

catch (InvalidNameException e) {

}

return null;

}


   Like      Feedback      javax.naming.ldap.LdapName


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 595. Code Sample / Example / Snippet of java.math.BigInteger

    private X509Certificate generateRootCertificate(String commonName, Date notBefore, Date notAfter) throws Exception {

X500Name issuer = new X500Name(commonName);

BigInteger serial = BigInteger.probablePrime(16, new Random());



SubjectPublicKeyInfo pubKeyInfo = convertToSubjectPublicKeyInfo(m_caKey.getPublic());



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

builder.addExtension(new Extension(Extension.basicConstraints, true, new DEROctetString(new BasicConstraints(true))));



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

return new JcaX509CertificateConverter().getCertificate(certHolder);

}


   Like      Feedback      java.math.BigInteger


 Sample 596. Code Sample / Example / Snippet of org.bouncycastle.cert.X509v3CertificateBuilder

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


 Sample 597. Code Sample / Example / Snippet of org.bouncycastle.cert.X509CertificateHolder

    private X509Certificate generateRootCertificate(String commonName, Date notBefore, Date notAfter) throws Exception {

X500Name issuer = new X500Name(commonName);

BigInteger serial = BigInteger.probablePrime(16, new Random());



SubjectPublicKeyInfo pubKeyInfo = convertToSubjectPublicKeyInfo(m_caKey.getPublic());



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

builder.addExtension(new Extension(Extension.basicConstraints, true, new DEROctetString(new BasicConstraints(true))));



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

return new JcaX509CertificateConverter().getCertificate(certHolder);

}


   Like      Feedback      org.bouncycastle.cert.X509CertificateHolder


 Sample 598. Code Sample / Example / Snippet of java.util.Calendar

    private static Calendar getToday() {

Calendar cal = Calendar.getInstance();

cal.set(Calendar.HOUR_OF_DAY, 12);

cal.set(Calendar.MINUTE, 0);

cal.set(Calendar.SECOND, 0);

cal.set(Calendar.MILLISECOND, 0);

return cal;

}


   Like      Feedback      java.util.Calendar


 Sample 599. Code Sample / Example / Snippet of javax.security.auth.x500.X500Principal

    private X509Certificate[] createValidCertificateChainWithDN(String... dns) {

X509Certificate[] result = new X509Certificate[dns.length];



X500Principal signerDN = m_keystore.getCA_DN();

KeyPair signerKeyPair = m_keystore.getCA_KeyPair();



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

KeyPair certKeyPair = m_keystore.generateKeyPair();



String dn = dns[i];

int idx = result.length - i - 1;



result[idx] = m_keystore.createCertificate(signerDN, signerKeyPair.getPrivate(), dn, yesterday(), tomorrow(), certKeyPair.getPublic());



signerDN = result[idx].getSubjectX500Principal();

signerKeyPair = certKeyPair;

}

return result;

}


   Like      Feedback      javax.security.auth.x500.X500Principal


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 600. Code Sample / Example / Snippet of java.security.KeyPair

    private X509Certificate[] createValidCertificateChainWithDN(String... dns) {

X509Certificate[] result = new X509Certificate[dns.length];



X500Principal signerDN = m_keystore.getCA_DN();

KeyPair signerKeyPair = m_keystore.getCA_KeyPair();



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

KeyPair certKeyPair = m_keystore.generateKeyPair();



String dn = dns[i];

int idx = result.length - i - 1;



result[idx] = m_keystore.createCertificate(signerDN, signerKeyPair.getPrivate(), dn, yesterday(), tomorrow(), certKeyPair.getPublic());



signerDN = result[idx].getSubjectX500Principal();

signerKeyPair = certKeyPair;

}

return result;

}


   Like      Feedback      java.security.KeyPair


 Sample 601. Code Sample / Example / Snippet of static org.mockito.Mockito.mock

    public void setUp() throws Exception {

String range = "1-100000";

Repository mock = new MockDeploymentRepository(range, generateHugeTestXml(), null);

m_backend = new RepositoryBasedProvider();

TestUtils.configureObject(m_backend, Repository.class, mock);

TestUtils.configureObject(m_backend, LogService.class);

}


   Like      Feedback      static org.mockito.Mockito.mock


 Sample 602. Code Sample / Example / Snippet of org.osgi.service.cm.Configuration

    protected void deleteConfig(String pid, String factoryPid) {

try {

Configuration config = getConfiguration(pid, factoryPid);

config.delete();

m_log.log(LogService.LOG_DEBUG, "Removed configuration for pid '" + pid + "'");

}

catch (Exception e) {

m_log.log(LogService.LOG_ERROR, "Unable to remove configuration for pid '" + pid + "'", e);

}

}


   Like      Feedback      org.osgi.service.cm.Configuration


 Sample 603. Code Sample / Example / Snippet of org.apache.felix.dm.DependencyManager

    protected synchronized void enableEventLogging() {

DependencyManager dm = m_dependencyManager;

m_eventLoggingComponent = dm.createComponent()

.setInterface(EventHandler.class.getName(), new Properties() {

{

put(EventConstants.EVENT_TOPIC, "*");

}

})

.setImplementation(new EventHandler() {

@Override

public void handleEvent(Event event) {

System.out.print("[EVENT] " + event.getTopic());

for (String key : event.getPropertyNames()) {

System.out.print(" " + key + "=" + event.getProperty(key));

}

System.out.println();

}

});

dm.add(m_eventLoggingComponent);

}


   Like      Feedback      org.apache.felix.dm.DependencyManager


 Sample 604. Code Sample / Example / Snippet of static org.apache.ace.test.utils.Util.dictionary

	protected void configureProvisionedServices() throws Exception {

m_echoServlet = new EchoServlet();



Dictionary<String, String> dictionary = new Hashtable<>();

dictionary.put(HttpConstants.ENDPOINT, "/echoServlet");

m_echoServletService = m_dependencyManager.createComponent()

.setImplementation(m_echoServlet)

.setInterface(Servlet.class.getName(), dictionary);



m_mockHttp = new MockHttpService();

m_mockHttpService = m_dependencyManager.createComponent()

.setImplementation(m_mockHttp)

.setInterface(HttpService.class.getName(), null);

}


   Like      Feedback      static org.apache.ace.test.utils.Util.dictionary


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 605. Code Sample / Example / Snippet of java.nio.channels.FileChannel

    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.nio.channels.FileChannel


 Sample 606. Code Sample / Example / Snippet of java.io.FileInputStream

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


 Sample 607. Code Sample / Example / Snippet of java.lang.reflect.Method

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

try {

Method bridge = handler.getClass().getMethod(method.getName(), method.getParameterTypes());

bridge.setAccessible(true);

return bridge.invoke(handler, args);

}

catch (NoSuchMethodException ex) {

return super.invoke(proxy, method, args);

}

catch (InvocationTargetException ex) {

throw ex.getCause();

}

}


   Like      Feedback      java.lang.reflect.Method


 Sample 608. Code Sample / Example / Snippet of static org.apache.ace.it.deployment.Constants.TEST_TARGETID

public interface Constants {

String TEST_AUTH_SCHEME = "<roles><group name="TestGroup"><properties><type>userGroup</type></properties></group>"

+ "<user name="d"><properties><username>d</username></properties><credentials>"

+ "<password>f</password></credentials><memberof>TestGroup</memberof></user></roles>";

String TEST_CUSTOMER = "apache";

int TEST_HTTP_PORT = TestConstants.PORT;

String TEST_TARGETID = "test-target";

}


   Like      Feedback      static org.apache.ace.it.deployment.Constants.TEST_TARGETID


 Sample 609. Code Sample / Example / Snippet of static org.apache.ace.it.deployment.Constants.TEST_CUSTOMER

public interface Constants {

String TEST_AUTH_SCHEME = "<roles><group name="TestGroup"><properties><type>userGroup</type></properties></group>"

+ "<user name="d"><properties><username>d</username></properties><credentials>"

+ "<password>f</password></credentials><memberof>TestGroup</memberof></user></roles>";

String TEST_CUSTOMER = "apache";

int TEST_HTTP_PORT = TestConstants.PORT;

String TEST_TARGETID = "test-target";

}


   Like      Feedback      static org.apache.ace.it.deployment.Constants.TEST_CUSTOMER


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 610. Code Sample / Example / Snippet of static org.apache.ace.it.deployment.Constants.TEST_HTTP_PORT

public interface Constants {

String TEST_AUTH_SCHEME = "<roles><group name="TestGroup"><properties><type>userGroup</type></properties></group>"

+ "<user name="d"><properties><username>d</username></properties><credentials>"

+ "<password>f</password></credentials><memberof>TestGroup</memberof></user></roles>";

String TEST_CUSTOMER = "apache";

int TEST_HTTP_PORT = TestConstants.PORT;

String TEST_TARGETID = "test-target";

}


   Like      Feedback      static org.apache.ace.it.deployment.Constants.TEST_HTTP_PORT


 Sample 611. Code Sample / Example / Snippet of static org.apache.ace.it.deployment.Constants.TEST_AUTH_SCHEME

public interface Constants {

String TEST_AUTH_SCHEME = "<roles><group name="TestGroup"><properties><type>userGroup</type></properties></group>"

+ "<user name="d"><properties><username>d</username></properties><credentials>"

+ "<password>f</password></credentials><memberof>TestGroup</memberof></user></roles>";

String TEST_CUSTOMER = "apache";

int TEST_HTTP_PORT = TestConstants.PORT;

String TEST_TARGETID = "test-target";

}


   Like      Feedback      static org.apache.ace.it.deployment.Constants.TEST_AUTH_SCHEME


 Sample 612. Code Sample / Example / Snippet of static org.apache.ace.it.repository.Utils.get

    public void testEmptyRepository() throws Exception {

Repository mock = new MockDeploymentRepository("", null, null);

TestUtils.configureObject(m_backend, Repository.class, mock);



List<String> versions = m_backend.getVersions(TARGET);

assert versions.size() == 0 : "From an empty repository, we should get 0 versions, but we get "

+ versions.size();

}


   Like      Feedback      static org.apache.ace.it.repository.Utils.get


 Sample 613. Code Sample / Example / Snippet of org.apache.ace.deployment.provider.impl.ArtifactDataImpl

    public boolean equals(Object other) {

if (!(other instanceof ArtifactDataImpl)) {

return false;

}

ArtifactDataImpl jarFile2 = (ArtifactDataImpl) other;



if (getSymbolicName() != null) {

return getSymbolicName().equals(jarFile2.getSymbolicName()) &&

getVersion().equals(jarFile2.getVersion());

}

else {

return m_url.equals(jarFile2.getUrl());

}

}


   Like      Feedback      org.apache.ace.deployment.provider.impl.ArtifactDataImpl


 Sample 614. Code Sample / Example / Snippet of java.util.concurrent.Semaphore

    private void removeRepository(String instanceName) throws IOException, InterruptedException, InvalidSyntaxException {

Configuration[] configs = listConfigurations("(factory.instance.pid=" + instanceName + ")");

if ((configs != null) && (configs.length > 0)) {

final Semaphore sem = new Semaphore(0);

ServiceTracker<Object, Object> tracker = new ServiceTracker<Object, Object>(m_bundleContext, m_bundleContext.createFilter("(factory.instance.pid=" + instanceName + ")"), null) {

@Override

public void removedService(ServiceReference<Object> reference, Object service) {

super.removedService(reference, service);

sem.release();

}

};

tracker.open();



try {

configs[0].delete();



if (!sem.tryAcquire(1, TimeUnit.SECONDS)) {

throw new IOException("Instance did not get removed in time.");

}

}

finally {

tracker.close();

}

}

}


   Like      Feedback      java.util.concurrent.Semaphore


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 615. Code Sample / Example / Snippet of org.osgi.service.useradmin.Group

    protected void configureAdditionalServices() throws Exception {

Group group = (Group) m_userAdmin.createRole(TEST_GROUP, Role.GROUP);

group.getProperties().put("type", "userGroup");



User user = (User) m_userAdmin.createRole("TestUser", Role.USER);

user.getProperties().put("email", "testUser@apache.org");

user.getCredentials().put("password", "swordfish");

user.getCredentials().put("certificate", "42".getBytes());



group.addMember(user);

}


   Like      Feedback      org.osgi.service.useradmin.Group


 Sample 616. Code Sample / Example / Snippet of org.osgi.service.useradmin.Role

    public void GetUserBroken() {

User newUser = null;

Role newRole = m_userAdmin.createRole((String) "Testuser", Role.USER);

Group group = (Group) m_userAdmin.getRole(TEST_GROUP);

if (newRole != null && group != null) {

newUser = (User) newRole;

newUser.getProperties().put("username", "u");

newUser.getCredentials().put("password", "p");

group.addMember(newUser);

}

assertEquals("Testuser", m_userEditor.getUser("u").getName());

}


   Like      Feedback      org.osgi.service.useradmin.Role


 Sample 617. Code Sample / Example / Snippet of java.io.OutputStream

    public static void generateBundle(ArtifactData data, Map<String, String> additionalHeaders) throws IOException {

OutputStream bundleStream = null;

try {

File dataFile = new File(data.getUrl().toURI());

OutputStream fileStream = new FileOutputStream(dataFile);

bundleStream = new JarOutputStream(fileStream, getBundleManifest(data.getSymbolicName(), data.getVersion(), additionalHeaders));

bundleStream.flush();

} catch (URISyntaxException e) {

throw new IOException();

} finally {

if (bundleStream != null) {

bundleStream.close();

}

}

}


   Like      Feedback      java.io.OutputStream


 Sample 618. Code Sample / Example / Snippet of java.util.jar.Manifest

    public InputStream getDeploymentPackage(String id, String version) throws OverloadedException, IOException {

List<ArtifactData> data = m_provider.getBundleData(id, version);

Manifest manifest = new Manifest();

Attributes main = manifest.getMainAttributes();



main.putValue("Manifest-Version", "1.0");

main.putValue("DeploymentPackage-SymbolicName", id);

main.putValue("DeploymentPackage-Version", version);



for (ArtifactData bd : data) {

manifest.getEntries().put(bd.getFilename(), bd.getManifestAttributes(false));

}



return DeploymentPackageStream.createStreamForThread(m_connectionFactory, manifest, data.iterator(), false);

}


   Like      Feedback      java.util.jar.Manifest


 Sample 619. Code Sample / Example / Snippet of java.util.jar.Attributes

    public InputStream getDeploymentPackage(String id, String version) throws OverloadedException, IOException {

List<ArtifactData> data = m_provider.getBundleData(id, version);

Manifest manifest = new Manifest();

Attributes main = manifest.getMainAttributes();



main.putValue("Manifest-Version", "1.0");

main.putValue("DeploymentPackage-SymbolicName", id);

main.putValue("DeploymentPackage-Version", version);



for (ArtifactData bd : data) {

manifest.getEntries().put(bd.getFilename(), bd.getManifestAttributes(false));

}



return DeploymentPackageStream.createStreamForThread(m_connectionFactory, manifest, data.iterator(), false);

}


   Like      Feedback      java.util.jar.Attributes


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 620. Code Sample / Example / Snippet of org.apache.ace.deployment.processor.DeploymentProcessor

    private DeploymentProcessor getDeploymentProcessor(HttpServletRequest request) throws AceRestException {

String processor = request.getParameter(PROCESSOR);

if (processor != null) {

DeploymentProcessor deploymentProcessor = m_processors.get(processor);

if (deploymentProcessor == null) {

throw new AceRestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not find a deployment processor called: " + processor);

}



m_log.log(LogService.LOG_DEBUG, "Using deployment processor " + processor);



return deploymentProcessor;

}



m_log.log(LogService.LOG_DEBUG, "Using default deployment processor...");



return new DefaultDeploymentProcessor();

}


   Like      Feedback      org.apache.ace.deployment.processor.DeploymentProcessor


 Sample 621. Code Sample / Example / Snippet of org.osgi.service.event.Event

    private Event createEvent(String version, URL dataURL) {

Dictionary<String, Object> properties = new Hashtable<>();

properties.put("deploymentpackage.url", dataURL.toString());

properties.put("deploymentpackage.version", version);

Event event = new Event(TOPIC_DEPLOYMENTPACKAGE_INSTALL, properties);

return event;

}


   Like      Feedback      org.osgi.service.event.Event


 Sample 622. Code Sample / Example / Snippet of org.apache.ace.repository.ext.CachedRepository

    private boolean isCacheUpToDate() {

CachedRepository cachedRepository = m_cachedRepository;

try {

return (cachedRepository != null && cachedRepository.isCurrent());

}

catch (IOException ioe) {

m_log.log(LogService.LOG_WARNING, "Failed to check if cache is current. Assuming it's not.", ioe);

return false;

}

}


   Like      Feedback      org.apache.ace.repository.ext.CachedRepository


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

    public void init(BundleContext context, DependencyManager manager) throws Exception {

manager.add(createComponent()

.setInterface(Servlet.class.getName(), null)

.setImplementation(DeploymentServlet.class)

.add(createConfigurationDependency().setPropagate(true).setPid(DEPLOYMENT_PID))

.add(createServiceDependency().setService(StreamGenerator.class).setRequired(true))

.add(createServiceDependency().setService(DeploymentProvider.class).setRequired(true))

.add(createServiceDependency().setService(DeploymentProcessor.class).setRequired(false).setCallbacks("addProcessor", "removeProcessor"))

.add(createServiceDependency().setService(LogService.class).setRequired(false))

);

manager.add(createComponent()

.setInterface(Servlet.class.getName(), null)

.setImplementation(AgentDeploymentServlet.class)

.add(createConfigurationDependency().setPropagate(true).setPid(AGENT_PID))

.add(createServiceDependency().setService(ConnectionFactory.class).setRequired(true))

.add(createServiceDependency().setService(LogService.class).setRequired(false))

);



Properties props = new Properties();

props.put("pattern", "/*");

manager.add(createComponent()

.setInterface(Filter.class.getName(), null)

.setImplementation(OverloadedFilter.class)

);

}


   Like      Feedback      java.util.Properties


 Sample 624. Code Sample / Example / Snippet of javax.servlet.Filter

    public List<ArtifactObject> lrp(String filter) throws Exception {

Filter f = m_context.createFilter(filter);

List<ArtifactObject> rps = m_artifactRepository.getResourceProcessors();

List<ArtifactObject> res = new LinkedList<>();

for (ArtifactObject rp : rps) {

if (f.matchCase(rp.getDictionary())) {

res.add(rp);

}

}

return res;

}




   Like      Feedback      javax.servlet.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 625. Code Sample / Example / Snippet of javax.servlet.http.HttpServletResponse

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

HttpServletResponse httpResponse = (HttpServletResponse) response;

try {

filterChain.doFilter(request, response);

}

catch (OverloadedException oe) {

OverloadedException overloadedException = (OverloadedException) oe;

httpResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);

httpResponse.setHeader(HTTP_RETRY_AFTER, "" + overloadedException.getBackoffTime());

}

}


   Like      Feedback      javax.servlet.http.HttpServletResponse


 Sample 626. Code Sample / Example / Snippet of org.w3c.dom.Node

    private static String getNamedItemText(NamedNodeMap map, String name) {

Node namedItem = map.getNamedItem(name);

if (namedItem == null) {

return null;

}

else {

return namedItem.getTextContent();

}

}


   Like      Feedback      org.w3c.dom.Node


 Sample 627. Code Sample / Example / Snippet of java.util.concurrent.ExecutorService

    public void hundredStreamsConcurrently() throws Exception {

ExecutorService e = Executors.newFixedThreadPool(5);

for (int i = 0; i < 10; i++) {

e.execute(new Runnable() {

public void run() {

for (int i = 0; i < 10; i++) {

try {

isJarInputStreamReadable();

}

catch (Exception e) {

m_failure = e;

}

}

}

});

}

e.shutdown();

e.awaitTermination(10, TimeUnit.SECONDS);



assert m_failure == null : "Test failed: " + m_failure.getLocalizedMessage();

}




   Like      Feedback      java.util.concurrent.ExecutorService


 Sample 628. Code Sample / Example / Snippet of org.apache.ace.deployment.provider.repositorybased.BaseRepositoryHandler.XmlDeploymentArtifact

    public void testGatherSingleArtifactOk() throws Exception {

DeploymentArtifactCollector handler = new DeploymentArtifactCollector(TARGET, VERSION1);



m_parser.parse(m_inputStream, handler);



List<XmlDeploymentArtifact>[] artifacts = handler.getArtifacts();

assert artifacts.length == 1 : "Expected a single artifact to be found!";

assert artifacts[0].size() == 1 : "Expected a single artifact to be found!";



XmlDeploymentArtifact artifact1 = artifacts[0].get(0);

assert new URL("file:///bundle1").equals(artifact1.getUrl()) : "Expected 'file:///bundle1' URL to be found!";

assert artifact1.getDirective().size() == 2 : "Expected two directives to be found!";

assert "bundle1".equals(artifact1.getDirective().get(KEY_SYMBOLICNAME)) : "Expected correct symbolic name to be found!";

assert "1.0.0".equals(artifact1.getDirective().get(KEY_VERSION)) : "Expected correct bundle version to be found!";

}


   Like      Feedback      org.apache.ace.deployment.provider.repositorybased.BaseRepositoryHandler.XmlDeploymentArtifact


 Sample 629. Code Sample / Example / Snippet of javax.xml.parsers.SAXParserFactory

    protected void setUp() throws Exception {

SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();

m_parser = saxParserFactory.newSAXParser();



String xml = generateValidTestXml();

m_inputStream = new ByteArrayInputStream(xml.getBytes());

}


   Like      Feedback      javax.xml.parsers.SAXParserFactory


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 630. Code Sample / Example / Snippet of org.apache.ace.deployment.provider.ArtifactData

    public void testSingleUnchangedBundleMultipleVersions() throws Exception {

Collection<ArtifactData> bundleData = m_backend.getBundleData(TARGET, VERSION1, VERSION1);

assert bundleData.size() == 1 : "Expect one bundle, got " + bundleData.size();

Iterator<ArtifactData> it = bundleData.iterator();

while (it.hasNext()) {

ArtifactData data = it.next();

assert data.getSize() == 100 : "Bundle has no sensible size?! " + data.getSize();

assert !data.hasChanged() : "The data should not have been changed.";

}

}


   Like      Feedback      org.apache.ace.deployment.provider.ArtifactData


 Sample 631. Code Sample / Example / Snippet of java.io.BufferedReader

        public Object install(InputStream inputStream) throws Exception {

m_installCalled = true;

BufferedReader bufReader = new BufferedReader(new InputStreamReader(inputStream));

String versionString = bufReader.readLine();

if (m_expectedInstallVersion.equals(new Version(versionString))) {

m_correctVersionInstalled = true;

}

return new Version(versionString);

}


   Like      Feedback      java.io.BufferedReader


 Sample 632. Code Sample / Example / Snippet of org.apache.ace.repository.Repository

    public void testEmptyRepository() throws Exception {

Repository mock = new MockDeploymentRepository("", null, null);

TestUtils.configureObject(m_backend, Repository.class, mock);



List<String> versions = m_backend.getVersions(TARGET);

assert versions.size() == 0 : "From an empty repository, we should get 0 versions, but we get "

+ versions.size();

}


   Like      Feedback      org.apache.ace.repository.Repository


 Sample 633. Code Sample / Example / Snippet of javax.xml.parsers.DocumentBuilderFactory

    private Document getDocument(InputStream input) throws IOException {

try {

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder;

builder = factory.newDocumentBuilder();

return builder.parse(input);

}

catch (ParserConfigurationException e) {

throw new IOException("Error instantiation XML parser:" + e.getMessage());

}

catch (SAXException e) {

throw new IOException("Error parsing user data:" + e.getMessage());

}

}


   Like      Feedback      javax.xml.parsers.DocumentBuilderFactory


 Sample 634. Code Sample / Example / Snippet of org.apache.ace.builder.DeploymentPackageBuilder

    protected static File createPackage(String name, Version version, File... bundles) throws Exception {

DeploymentPackageBuilder builder = DeploymentPackageBuilder.createDeploymentPackage(name, version.toString());



OutputStream fos = null;

try {

for (File bundle : bundles) {

builder.addBundle(bundle.toURI().toURL());

}



File file = File.createTempFile("testpackage", ".jar");

file.deleteOnExit();



fos = new FileOutputStream(file);

builder.generate(fos);



return file;

}

finally {

if (fos != null) {

fos.close();

}

}

}


   Like      Feedback      org.apache.ace.builder.DeploymentPackageBuilder


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 635. Code Sample / Example / Snippet of javax.swing.JScrollPane

    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();

JScrollPane scrollPane = new JScrollPane(textArea);


   Like      Feedback      javax.swing.JScrollPane


 Sample 636. Code Sample / Example / Snippet of org.osgi.framework.Bundle

    protected void configureProvisionedServices() throws Exception {

final String agentActivatorName = "org.apache.ace.agent.impl.Activator";



Bundle bundle = FrameworkUtil.getBundle(getClass());



Class<?> activatorClass = bundle.loadClass(agentActivatorName);

assertNotNull("Failed to load agent activator class (" + agentActivatorName + ")!", activatorClass);



m_agentActivator = (BundleActivator) activatorClass.newInstance();

}


   Like      Feedback      org.osgi.framework.Bundle


 Sample 637. Code Sample / Example / Snippet of org.apache.ace.agent.FeedbackHandler

        private void sendFeedbackToServer() {

try {

FeedbackHandler feedbackHandler = m_agentContext.getHandler(FeedbackHandler.class);

Set<String> channelNames = feedbackHandler.getChannelNames();

for (String channelName : channelNames) {

FeedbackChannel channel = feedbackHandler.getChannel(channelName);



logInfo("Synchronizing feedback of %s with server...", channelName);



channel.sendFeedback();

}

}

catch (Exception exception) {

logWarning("Feedback synchronization failed with %s.", exception, exception.getMessage());

}

}


   Like      Feedback      org.apache.ace.agent.FeedbackHandler


 Sample 638. Code Sample / Example / Snippet of org.apache.ace.agent.FeedbackChannel

        private void sendFeedbackToServer() {

try {

FeedbackHandler feedbackHandler = m_agentContext.getHandler(FeedbackHandler.class);

Set<String> channelNames = feedbackHandler.getChannelNames();

for (String channelName : channelNames) {

FeedbackChannel channel = feedbackHandler.getChannel(channelName);



logInfo("Synchronizing feedback of %s with server...", channelName);



channel.sendFeedback();

}

}

catch (Exception exception) {

logWarning("Feedback synchronization failed with %s.", exception, exception.getMessage());

}

}


   Like      Feedback      org.apache.ace.agent.FeedbackChannel


 Sample 639. Code Sample / Example / Snippet of org.apache.ace.bnd.repository.AceObrRepository

    public static AceObrRepository createRepository(String type, String location) throws Exception {

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

properties.put(AceObrRepository.PROP_REPO_TYPE, type);

properties.put(AceObrRepository.PROP_LOCATIONS, location);

AceObrRepository repository = new AceObrRepository();

repository.setProperties(properties);

return repository;

}


   Like      Feedback      org.apache.ace.bnd.repository.AceObrRepository


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 640. Code Sample / Example / Snippet of java.net.URI

    public static String getUrl(Resource resource) {

Map<String, Object> attrs = getNamespaceAttributes(resource, "osgi.content");

if (attrs == null)

return null;

URI url = (URI) attrs.get("url");

return url == null ? null : url.toString();

}


   Like      Feedback      java.net.URI


 Sample 641. Code Sample / Example / Snippet of org.osgi.framework.Version

    private Version getReleasedBaseVersion(Resource resource) throws Exception {

List<Resource> resources = findResources(m_releaseRepo, getIdentity(resource));

Version resourceVersion = getVersion(resource);

Version baseVersion = Version.emptyVersion;

for (Resource candidate : resources) {

Version candidateVersion = getVersion(candidate);

if (candidateVersion.compareTo(resourceVersion) < 0) {

if (candidateVersion.compareTo(baseVersion) > 0) {

baseVersion = candidateVersion;

}

}

}

return baseVersion;

}


   Like      Feedback      org.osgi.framework.Version


 Sample 642. Code Sample / Example / Snippet of java.io.InputStream

    public static boolean filesDiffer(File first, File second) throws Exception {

if (first.length() != second.length()) {

return true;

}

InputStream firstStream = new FileInputStream(first);

InputStream secondStream = new FileInputStream(second);

try {

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

if (firstStream.read() != secondStream.read()) {

return false;

}

}

return true;

}

finally {

try {

firstStream.close();

}

finally {

secondStream.close();

}

}

}


   Like      Feedback      java.io.InputStream


 Sample 643. Code Sample / Example / Snippet of aQute.bnd.deployer.repository.FixedIndexedRepo

    public static void ls(CommandRepo repo, String filter) throws Exception {



FixedIndexedRepo sourceRepo = repo.repo();

sourceRepo.reset();



Requirement requirement = getRequirement(filter);

List<Resource> resources = findResources(sourceRepo, requirement);



for (Resource resource : resources) {

String location = getUrl(resources.get(0));

System.out.println(resource + " => " + location);

}

}


   Like      Feedback      aQute.bnd.deployer.repository.FixedIndexedRepo


 Sample 644. Code Sample / Example / Snippet of java.net.HttpURLConnection

    private HttpURLConnection openConnection() throws IOException {

URL url = m_uri.toURL();



HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setInstanceFollowRedirects(m_client.isFollowRedirects());

conn.setAllowUserInteraction(false);

conn.setDefaultUseCaches(false);

conn.setUseCaches(false);

conn.setConnectTimeout(1000);

conn.setReadTimeout(1000);



return conn;

}


   Like      Feedback      java.net.HttpURLConnection


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 645. Code Sample / Example / Snippet of java.util.Timer

    public void shutdown(long delay) {

Timer timer = new Timer();

timer.schedule(new TimerTask() {

@Override

public void run() {

try {

m_context.getBundle(0).stop();

}

catch (BundleException e) {

e.printStackTrace();

}

}

}, delay);

}


   Like      Feedback      java.util.Timer


 Sample 646. Code Sample / Example / Snippet of java.io.BufferedWriter

    public static File createTmpConfigOnDisk(String config) throws Exception {

File file = File.createTempFile("template", ".xml");

file.deleteOnExit();

BufferedWriter bw = new BufferedWriter(new FileWriter(file));

try {

bw.write(config);

return file;

}

finally {

bw.close();

}

}


   Like      Feedback      java.io.BufferedWriter


 Sample 647. Code Sample / Example / Snippet of org.apache.ace.client.rest.util.WebResource

    public static WebResource createEntity(Client c, WebResource work, String type, String data) throws IOException {

WebResource entity = work.path(type);

try {

entity.post(data);

throw new IOException("Could not create " + type + " with data " + data);

}

catch (WebResourceException e2) {

return c.resource(e2.getResponse().getLocation());

}

}


   Like      Feedback      org.apache.ace.client.rest.util.WebResource


 Sample 648. Code Sample / Example / Snippet of java.net.URL

    public void importDeploymentPackage(String dpURL, boolean autoCommit) throws Exception {

URL url = URI.create(dpURL).toURL();



InputStream is = null;

JarInputStream jis = null;



try {

is = url.openStream();

jis = new JarInputStream(is);



importDeploymentPackage(jis, autoCommit);

}

finally {

closeSilently(is);

closeSilently(jis);

}

}


   Like      Feedback      java.net.URL


 Sample 649. Code Sample / Example / Snippet of java.io.File

    private ArtifactObject createArtifact(String name, Attributes attrs, InputStream is) throws Exception {

ArtifactObject artifact = findArtifact(name, attrs);



if (artifact != null) {

return artifact;

}

else if (Boolean.parseBoolean(attrs.getValue(DEPLOYMENT_PACKAGE_MISSING))) {

m_log.log(LogService.LOG_WARNING, String.format("Unable to create artifact '%s' as it is missing...", name));

return null;

}

else {

m_log.log(LogService.LOG_INFO, String.format("Creating artifact '%s'...", name));



File file = storeArtifactContents(name, is);

try {

return m_workspace.createArtifact(file.toURI().toURL().toExternalForm(), true /* upload */);

}

finally {

file.delete();

}

}

}


   Like      Feedback      java.io.File


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 650. Code Sample / Example / Snippet of org.apache.ace.client.repository.object.ArtifactObject

    private ArtifactObject createArtifact(String name, Attributes attrs, InputStream is) throws Exception {

ArtifactObject artifact = findArtifact(name, attrs);



if (artifact != null) {

return artifact;

}

else if (Boolean.parseBoolean(attrs.getValue(DEPLOYMENT_PACKAGE_MISSING))) {

m_log.log(LogService.LOG_WARNING, String.format("Unable to create artifact '%s' as it is missing...", name));

return null;

}

else {

m_log.log(LogService.LOG_INFO, String.format("Creating artifact '%s'...", name));



File file = storeArtifactContents(name, is);

try {

return m_workspace.createArtifact(file.toURI().toURL().toExternalForm(), true /* upload */);

}

finally {

file.delete();

}

}

}


   Like      Feedback      org.apache.ace.client.repository.object.ArtifactObject


 Sample 651. Code Sample / Example / Snippet of org.osgi.framework.Filter

    public List<ArtifactObject> lrp(String filter) throws Exception {

Filter f = m_context.createFilter(filter);

List<ArtifactObject> rps = m_artifactRepository.getResourceProcessors();

List<ArtifactObject> res = new LinkedList<>();

for (ArtifactObject rp : rps) {

if (f.matchCase(rp.getDictionary())) {

res.add(rp);

}

}

return res;

}




   Like      Feedback      org.osgi.framework.Filter


 Sample 652. Code Sample / Example / Snippet of org.apache.ace.client.repository.ObjectRepository

    public void deleteRepositoryObject(String entityType, String entityId) {

ObjectRepository objectRepository = getGenericObjectRepository(entityType);

RepositoryObject repositoryObject = objectRepository.get(entityId);

if (repositoryObject == null) {

throw new IllegalArgumentException("Could not find repository object!");

}



objectRepository.remove(repositoryObject);

}


   Like      Feedback      org.apache.ace.client.repository.ObjectRepository


 Sample 653. Code Sample / Example / Snippet of org.apache.ace.client.repository.stateful.StatefulTargetRepository

    public RepositoryObject createRepositoryObject(String entityType, Map<String, String> attributes,

Map<String, String> tags) throws IllegalArgumentException {

if (TARGET.equals(entityType)) {

ObjectRepository<StatefulTargetObject> repo = getGenericObjectRepository(TARGET);

StatefulTargetRepository statefulRepo = (StatefulTargetRepository) repo;

return statefulRepo.preregister(attributes, tags);

}

else {

prepareAssociationAttributes(entityType, attributes);

ObjectRepository<?> repo = getGenericObjectRepository(entityType);

return repo.create(attributes, tags);

}

}


   Like      Feedback      org.apache.ace.client.repository.stateful.StatefulTargetRepository


 Sample 654. Code Sample / Example / Snippet of com.google.gson.JsonObject

	public JsonElement serialize(Event e, Type typeOfSrc, JsonSerializationContext context) {

DateFormat format = SimpleDateFormat.getDateTimeInstance();

JsonObject event = new JsonObject();

event.addProperty("logId", e.getStoreID());

event.addProperty("id", e.getID());

event.addProperty("time", format.format(new Date(e.getTime())));

event.addProperty("type", toAuditEventType(e.getType()));

JsonObject eventProperties = new JsonObject();

Map<String, String> p = e.getProperties();

for (String key : p.keySet()) {

eventProperties.addProperty(key, p.get(key));

}

event.add("properties", eventProperties);

return event;

}


   Like      Feedback      com.google.gson.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 655. Populate DateFormat using SimpleDateFormat

public JsonElement serialize(Event e, Type typeOfSrc, JsonSerializationContext context) {
DateFormat format = SimpleDateFormat.getDateTimeInstance();
JsonObject event = new JsonObject();
event.addProperty("time", format.format(new Date(e.getTime())));
return event;
}

   Like      Feedback      java.text.DateFormat  SimpleDateFormat.getDateTimeInstance()  SimpleDateFormat


 Sample 656. Code Sample / Example / Snippet of org.apache.ace.client.repository.RepositoryObject

    private void createRepositoryObject(Workspace workspace, String entityType, RepositoryValueObject data, HttpServletRequest req, HttpServletResponse resp) throws IOException {

try {

RepositoryObject object = workspace.createRepositoryObject(entityType, data.attributes, data.tags);



resp.sendRedirect(req.getServletPath() + "/" + buildPathFromElements(WORK_FOLDER, workspace.getSessionID(), entityType, object.getDefinition()));

}

catch (IllegalArgumentException e) {

m_logger.log(LogService.LOG_WARNING, "Failed to add entity of type: " + entityType + " with data: " + data);

resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Could not add entity of type " + entityType + " with data: " + data);

}

}


   Like      Feedback      org.apache.ace.client.repository.RepositoryObject


 Sample 657. Code Sample / Example / Snippet of org.apache.felix.framework.util.VersionRange

    private boolean checkOSVersions(String currentOSVersion, String[] osversions)

throws BundleException

{

for (int i = 0; (osversions != null) && (i < osversions.length); i++)

{

try

{

VersionRange range = VersionRange.parse(osversions[i]);

if (range.isInRange(new Version(currentOSVersion)))

{

return true;

}

}

catch (Exception ex)

{

throw new BundleException(

"Error evaluating osversion: " + osversions[i], ex);

}

}

return false;

}


   Like      Feedback      org.apache.felix.framework.util.VersionRange


 Sample 658. Code Sample / Example / Snippet of org.apache.felix.framework.capabilityset.SimpleFilter

    private static boolean matchMandatoryAttrbute(String attrName, SimpleFilter sf)

{

if ((sf.getName() != null) && sf.getName().equals(attrName))

{

return true;

}

else if (sf.getOperation() == SimpleFilter.AND)

{

List list = (List) sf.getValue();

for (int i = 0; i < list.size(); i++)

{

SimpleFilter sf2 = (SimpleFilter) list.get(i);

if ((sf2.getName() != null)

&& sf2.getName().equals(attrName))

{

return true;

}

}

}

return false;

}


   Like      Feedback      org.apache.felix.framework.capabilityset.SimpleFilter


 Sample 659. Code Sample / Example / Snippet of org.apache.ace.connectionfactory.impl.UrlCredentials.AuthType

    private void supplyCredentials(URLConnection conn, UrlCredentials urlCreds) throws IOException {

final AuthType type = urlCreds.getType();

final Object[] creds = urlCreds.getCredentials();



if (AuthType.BASIC.equals(type)) {

applyBasicAuthentication(conn, creds);

}

else if (AuthType.CLIENT_CERT.equals(type)) {

applyClientCertificate(conn, creds);

}

else if (!AuthType.NONE.equals(type)) {

throw new IllegalArgumentException("Unknown authentication type: " + type);

}

}


   Like      Feedback      org.apache.ace.connectionfactory.impl.UrlCredentials.AuthType


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 660. Code Sample / Example / Snippet of javax.swing.JButton

    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();

JScrollPane scrollPane = new JScrollPane(textArea);

JButton browseButton = new JButton("Browse Queues");


   Like      Feedback      javax.swing.JButton


 Sample 661. Code Sample / Example / Snippet of java.util.Vector

    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();

JScrollPane scrollPane = new JScrollPane(textArea);

JButton browseButton = new JButton("Browse Queues");



Vector theQueues = new Vector();


   Like      Feedback      java.util.Vector


 Sample 662. Code Sample / Example / Snippet of javax.jms.Session

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



String propertiesFile = DEFAULT_PROPERTIES_FILE;

String brokerHostPort = "localhost";

String connectID = "MessageMonitor";

String userID = "Administrator";



String subscriptionTopics = "jms.samples.chat";

String textFontName = "Dialog";

String textFontStyle = "PLAIN";

String textFontSize = "12";

String title = "MessageMonitor";



JTextArea textArea = new JTextArea();

JScrollPane scrollPane = new JScrollPane(textArea);

JButton clearButton = new JButton("Clear");



Connection connection = null;

Session session = null;


   Like      Feedback      javax.jms.Session


 Sample 663. Code Sample / Example / Snippet of javax.jms.Connection

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



String propertiesFile = DEFAULT_PROPERTIES_FILE;

String brokerHostPort = "localhost";

String connectID = "MessageMonitor";

String userID = "Administrator";



String subscriptionTopics = "jms.samples.chat";

String textFontName = "Dialog";

String textFontStyle = "PLAIN";

String textFontSize = "12";

String title = "MessageMonitor";



JTextArea textArea = new JTextArea();

JScrollPane scrollPane = new JScrollPane(textArea);

JButton clearButton = new JButton("Clear");



Connection connection = null;


   Like      Feedback      javax.jms.Connection


 Sample 664. Code Sample / Example / Snippet of org.apache.activemq.broker.BrokerService

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

BrokerService broker = new BrokerService();

broker.setUseJmx(true);

broker.addConnector("tcp://localhost:61616");

broker.start();



Object lock = new Object();

synchronized (lock) {

lock.wait();

}

}


   Like      Feedback      org.apache.activemq.broker.BrokerService


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

    public void run() throws JMSException {

ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);

connection = factory.createConnection();

session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

topic = session.createTopic("topictest.messages");

control = session.createTopic("topictest.control");



MessageConsumer consumer = session.createConsumer(topic);

consumer.setMessageListener(this);



connection.start();



producer = session.createProducer(control);

System.out.println("Waiting for messages...");

}


   Like      Feedback      org.apache.activemq.ActiveMQConnectionFactory


 Sample 666. Code Sample / Example / Snippet of javax.jms.MessageConsumer

    public void run() throws JMSException {

ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);

connection = factory.createConnection();

session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

topic = session.createTopic("topictest.messages");

control = session.createTopic("topictest.control");



MessageConsumer consumer = session.createConsumer(topic);

consumer.setMessageListener(this);



connection.start();



producer = session.createProducer(control);

System.out.println("Waiting for messages...");

}


   Like      Feedback      javax.jms.MessageConsumer


 Sample 667. Code Sample / Example / Snippet of org.apache.commons.crypto.cipher.CryptoCipher

    public void testDefaultCipher() throws GeneralSecurityException {

CryptoCipher defaultCipher = CryptoCipherFactory

.getCryptoCipher("AES/CBC/NoPadding");

final String name = defaultCipher.getClass().getName();

if (OpenSsl.getLoadingFailureReason() == null) {

Assert.assertEquals(OpenSslCipher.class.getName(), name);

} else {

Assert.assertEquals(JceCipher.class.getName(), name);

}

}


   Like      Feedback      org.apache.commons.crypto.cipher.CryptoCipher


 Sample 668. Code Sample / Example / Snippet of org.apache.commons.crypto.random.CryptoRandom

    protected CryptoRandom getRandom(String className) throws Exception {

Properties props = new Properties();

props.setProperty(CryptoRandomFactory.CLASSES_KEY, className);

final CryptoRandom cryptoRandom = CryptoRandomFactory.getCryptoRandom(props);

Assert.assertEquals(className, cryptoRandom.getClass().getCanonicalName());

return cryptoRandom;

}


   Like      Feedback      org.apache.commons.crypto.random.CryptoRandom


 Sample 669. Code Sample / Example / Snippet of com.sun.jna.NativeLong

    private void throwOnError(int retVal) {  

if (retVal != 1) {

NativeLong err = OpenSslNativeJna.ERR_peek_error();

String errdesc = OpenSslNativeJna.ERR_error_string(err, null);

close();

throw new RuntimeException("return code " + retVal + " from OpenSSL. Err code is " + err + ": " + errdesc);

}

}


   Like      Feedback      com.sun.jna.NativeLong


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 670. Code Sample / Example / Snippet of org.apache.bcel.classfile.AnnotationDefault

    public void testMethodAnnotations() throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");

final Method m = getMethod(clazz, "fruit");

final AnnotationDefault a = (AnnotationDefault) findAttribute(

"AnnotationDefault", m.getAttributes());

final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();

assertTrue("Should be STRING but is " + val.getElementValueType(), val

.getElementValueType() == ElementValue.STRING);

assertTrue("Should have default of bananas but default is "

+ val.getValueString(), val.getValueString().equals("bananas"));

}


   Like      Feedback      org.apache.bcel.classfile.AnnotationDefault


 Sample 671. Code Sample / Example / Snippet of org.apache.bcel.classfile.Method

    public void testMethodAnnotations() throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");

final Method m = getMethod(clazz, "fruit");

final AnnotationDefault a = (AnnotationDefault) findAttribute(

"AnnotationDefault", m.getAttributes());

final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();

assertTrue("Should be STRING but is " + val.getElementValueType(), val

.getElementValueType() == ElementValue.STRING);

assertTrue("Should have default of bananas but default is "

+ val.getValueString(), val.getValueString().equals("bananas"));

}


   Like      Feedback      org.apache.bcel.classfile.Method


 Sample 672. Code Sample / Example / Snippet of org.apache.bcel.classfile.SimpleElementValue

    public void testMethodAnnotations() throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");

final Method m = getMethod(clazz, "fruit");

final AnnotationDefault a = (AnnotationDefault) findAttribute(

"AnnotationDefault", m.getAttributes());

final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();

assertTrue("Should be STRING but is " + val.getElementValueType(), val

.getElementValueType() == ElementValue.STRING);

assertTrue("Should have default of bananas but default is "

+ val.getValueString(), val.getValueString().equals("bananas"));

}


   Like      Feedback      org.apache.bcel.classfile.SimpleElementValue


 Sample 673. Code Sample / Example / Snippet of org.apache.bcel.classfile.JavaClass

    public void testMethodAnnotations() throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");

final Method m = getMethod(clazz, "fruit");

final AnnotationDefault a = (AnnotationDefault) findAttribute(

"AnnotationDefault", m.getAttributes());

final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();

assertTrue("Should be STRING but is " + val.getElementValueType(), val

.getElementValueType() == ElementValue.STRING);

assertTrue("Should have default of bananas but default is "

+ val.getValueString(), val.getValueString().equals("bananas"));

}


   Like      Feedback      org.apache.bcel.classfile.JavaClass


 Sample 674. Code Sample / Example / Snippet of org.apache.bcel.generic.AnnotationEntryGen

    protected String dumpAnnotationEntries(final AnnotationEntryGen[] as)

{

final StringBuilder result = new StringBuilder();

result.append("[");

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

{

final AnnotationEntryGen annotation = as[i];

result.append(annotation.toShortString());

if (i + 1 < as.length) {

result.append(",");

}

}

result.append("]");

return result.toString();

}


   Like      Feedback      org.apache.bcel.generic.AnnotationEntryGen


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 675. Code Sample / Example / Snippet of org.apache.bcel.generic.ObjectType

    public AnnotationEntryGen createFruitAnnotationEntry(final ConstantPoolGen cp,

final String aFruit, final boolean visibility)

{

final SimpleElementValueGen evg = new SimpleElementValueGen(

ElementValueGen.STRING, cp, aFruit);

final ElementValuePairGen nvGen = new ElementValuePairGen("fruit", evg, cp);

final ObjectType t = new ObjectType("SimpleStringAnnotation");

final List<ElementValuePairGen> elements = new ArrayList<>();

elements.add(nvGen);

return new AnnotationEntryGen(t, elements, visibility, cp);

}


   Like      Feedback      org.apache.bcel.generic.ObjectType


 Sample 676. Code Sample / Example / Snippet of org.apache.bcel.generic.ElementValuePairGen

    public AnnotationEntryGen createFruitAnnotationEntry(final ConstantPoolGen cp,

final String aFruit, final boolean visibility)

{

final SimpleElementValueGen evg = new SimpleElementValueGen(

ElementValueGen.STRING, cp, aFruit);

final ElementValuePairGen nvGen = new ElementValuePairGen("fruit", evg, cp);

final ObjectType t = new ObjectType("SimpleStringAnnotation");

final List<ElementValuePairGen> elements = new ArrayList<>();

elements.add(nvGen);

return new AnnotationEntryGen(t, elements, visibility, cp);

}


   Like      Feedback      org.apache.bcel.generic.ElementValuePairGen


 Sample 677. Code Sample / Example / Snippet of org.apache.bcel.classfile.Attribute

    protected String dumpAttributes(final Attribute[] as)

{

final StringBuilder result = new StringBuilder();

result.append("AttributeArray:[");

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

{

final Attribute attr = as[i];

result.append(attr.toString());

if (i + 1 < as.length) {

result.append(",");

}

}

result.append("]");

return result.toString();

}


   Like      Feedback      org.apache.bcel.classfile.Attribute


 Sample 678. Code Sample / Example / Snippet of org.apache.bcel.generic.SimpleElementValueGen

    public AnnotationEntryGen createFruitAnnotationEntry(final ConstantPoolGen cp,

final String aFruit, final boolean visibility)

{

final SimpleElementValueGen evg = new SimpleElementValueGen(

ElementValueGen.STRING, cp, aFruit);

final ElementValuePairGen nvGen = new ElementValuePairGen("fruit", evg, cp);

final ObjectType t = new ObjectType("SimpleStringAnnotation");

final List<ElementValuePairGen> elements = new ArrayList<>();

elements.add(nvGen);

return new AnnotationEntryGen(t, elements, visibility, cp);

}


   Like      Feedback      org.apache.bcel.generic.SimpleElementValueGen


 Sample 679. Code Sample / Example / Snippet of org.apache.bcel.generic.ClassGen

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


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 680. Code Sample / Example / Snippet of org.apache.bcel.generic.EnumElementValueGen

    public void testCreateEnumElementValue() throws Exception

{

final ClassGen cg = createClassGen("HelloWorld");

final ConstantPoolGen cp = cg.getConstantPool();

final ObjectType enumType = new ObjectType("SimpleEnum"); // Supports rainbow

final EnumElementValueGen evg = new EnumElementValueGen(enumType, "Red", cp);

assertTrue(

"The new ElementValue value index should match the contents of the constantpool but "

+ evg.getValueIndex() + "!=" + cp.lookupUtf8("Red"),

evg.getValueIndex() == cp.lookupUtf8("Red"));

checkSerialize(evg, cp);

}


   Like      Feedback      org.apache.bcel.generic.EnumElementValueGen


 Sample 681. Code Sample / Example / Snippet of org.apache.bcel.generic.ClassElementValueGen

    public void testCreateClassElementValue() throws Exception

{

final ClassGen cg = createClassGen("HelloWorld");

final ConstantPoolGen cp = cg.getConstantPool();

final ObjectType classType = new ObjectType("java.lang.Integer");

final ClassElementValueGen evg = new ClassElementValueGen(classType, cp);

assertTrue("Unexpected value for contained class: '"

+ evg.getClassString() + "'", evg.getClassString().contains("Integer"));

checkSerialize(evg, cp);

}


   Like      Feedback      org.apache.bcel.generic.ClassElementValueGen


 Sample 682. Code Sample / Example / Snippet of org.apache.bcel.classfile.EnclosingMethod

    public void testCheckMethodLevelNamedInnerClass()

throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM01$1S");

final ConstantPool pool = clazz.getConstantPool();

final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz);

assertTrue("Expected 1 EnclosingMethod attribute but found "

+ encMethodAttrs.length, encMethodAttrs.length == 1);

final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0];

final String enclosingClassName = em.getEnclosingClass().getBytes(pool);

final String enclosingMethodName = em.getEnclosingMethod().getName(pool);

assertTrue(

"Expected class name to be '"+PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01' but was "

+ enclosingClassName, enclosingClassName

.equals(PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01"));

assertTrue("Expected method name to be 'main' but was "

+ enclosingMethodName, enclosingMethodName.equals("main"));

}


   Like      Feedback      org.apache.bcel.classfile.EnclosingMethod


 Sample 683. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantPool

    public void testCheckMethodLevelNamedInnerClass()

throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM01$1S");

final ConstantPool pool = clazz.getConstantPool();

final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz);

assertTrue("Expected 1 EnclosingMethod attribute but found "

+ encMethodAttrs.length, encMethodAttrs.length == 1);

final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0];

final String enclosingClassName = em.getEnclosingClass().getBytes(pool);

final String enclosingMethodName = em.getEnclosingMethod().getName(pool);

assertTrue(

"Expected class name to be '"+PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01' but was "

+ enclosingClassName, enclosingClassName

.equals(PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01"));

assertTrue("Expected method name to be 'main' but was "

+ enclosingMethodName, enclosingMethodName.equals("main"));

}


   Like      Feedback      org.apache.bcel.classfile.ConstantPool


 Sample 684. Code Sample / Example / Snippet of org.apache.bcel.classfile.ArrayElementValue

    private void assertArrayElementValue(final int nExpectedArrayValues, final AnnotationEntry anno)

{

final ElementValuePair elementValuePair = anno.getElementValuePairs()[0];

assertEquals("value", elementValuePair.getNameString());

final ArrayElementValue ev = (ArrayElementValue) elementValuePair.getValue();

final ElementValue[] eva = ev.getElementValuesArray();

assertEquals(nExpectedArrayValues, eva.length);

}


   Like      Feedback      org.apache.bcel.classfile.ArrayElementValue


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 685. Code Sample / Example / Snippet of org.apache.bcel.util.SyntheticRepository

    private JavaClass getClassFrom(final String where, final String clazzname)

throws ClassNotFoundException

{

final SyntheticRepository repos = createRepos(where);

return repos.loadClass(clazzname);

}


   Like      Feedback      org.apache.bcel.util.SyntheticRepository


 Sample 686. Code Sample / Example / Snippet of org.apache.bcel.classfile.ElementValuePair

    private void assertArrayElementValue(final int nExpectedArrayValues, final AnnotationEntry anno)

{

final ElementValuePair elementValuePair = anno.getElementValuePairs()[0];

assertEquals("value", elementValuePair.getNameString());

final ArrayElementValue ev = (ArrayElementValue) elementValuePair.getValue();

final ElementValue[] eva = ev.getElementValuesArray();

assertEquals(nExpectedArrayValues, eva.length);

}


   Like      Feedback      org.apache.bcel.classfile.ElementValuePair


 Sample 687. Code Sample / Example / Snippet of org.apache.bcel.classfile.ClassParser

    private void testJar(final File file) throws Exception {

System.out.println(file);

try (JarFile jar = new JarFile(file)) {

final Enumeration<JarEntry> en = jar.entries();

while (en.hasMoreElements()) {

final JarEntry e = en.nextElement();

final String name = e.getName();

if (name.endsWith(".class")) {

try (InputStream in = jar.getInputStream(e)) {

final ClassParser parser = new ClassParser(in, name);

final JavaClass jc = parser.parse();

for (final Method m : jc.getMethods()) {

compare(name, m);

}

}

}

}

}

}


   Like      Feedback      org.apache.bcel.classfile.ClassParser


 Sample 688. Code Sample / Example / Snippet of org.apache.bcel.classfile.Code

    private void compare(final String name, final Method m) {

final Code c = m.getCode();

if (c == null) {

return; // e.g. abstract method

}

final byte[] src = c.getCode();

final InstructionList il = new InstructionList(src);

final byte[] out = il.getByteCode();

if (src.length == out.length) {

assertArrayEquals(name + ": " + m.toString(), src, out);

} else {

System.out.println(name + ": " + m.toString() + " " + src.length + " " + out.length);

System.out.println(bytesToHex(src));

System.out.println(bytesToHex(out));

for (final InstructionHandle ih : il) {

System.out.println(ih.toString(false));

}

fail("Array comparison failure");

}

}


   Like      Feedback      org.apache.bcel.classfile.Code


 Sample 689. Code Sample / Example / Snippet of org.apache.bcel.generic.InstructionHandle

    public void testRemoveLocalVariable() throws Exception {

final MethodGen mg = getMethod(Foo.class, "bar");



final LocalVariableGen lv = mg.getLocalVariables()[1];

assertEquals("variable name", "a", lv.getName());

final InstructionHandle start = lv.getStart();

final InstructionHandle end = lv.getEnd();

assertNotNull("scope start", start);

assertNotNull("scope end", end);

assertTrue("scope start not targeted by the local variable", Arrays.asList(start.getTargeters()).contains(lv));

assertTrue("scope end not targeted by the local variable", Arrays.asList(end.getTargeters()).contains(lv));



mg.removeLocalVariable(lv);



assertFalse("scope start still targeted by the removed variable", Arrays.asList(start.getTargeters()).contains(lv));

assertFalse("scope end still targeted by the removed variable", Arrays.asList(end.getTargeters()).contains(lv));

assertNull("scope start", lv.getStart());

assertNull("scope end", lv.getEnd());

}


   Like      Feedback      org.apache.bcel.generic.InstructionHandle


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 690. Code Sample / Example / Snippet of org.apache.bcel.generic.InstructionList

    private void compare(final String name, final Method m) {

final Code c = m.getCode();

if (c == null) {

return; // e.g. abstract method

}

final byte[] src = c.getCode();

final InstructionList il = new InstructionList(src);

final byte[] out = il.getByteCode();

if (src.length == out.length) {

assertArrayEquals(name + ": " + m.toString(), src, out);

} else {

System.out.println(name + ": " + m.toString() + " " + src.length + " " + out.length);

System.out.println(bytesToHex(src));

System.out.println(bytesToHex(out));

for (final InstructionHandle ih : il) {

System.out.println(ih.toString(false));

}

fail("Array comparison failure");

}

}


   Like      Feedback      org.apache.bcel.generic.InstructionList


 Sample 691. Code Sample / Example / Snippet of org.apache.bcel.generic.MethodGen

    public void testRemoveLocalVariable() throws Exception {

final MethodGen mg = getMethod(Foo.class, "bar");



final LocalVariableGen lv = mg.getLocalVariables()[1];

assertEquals("variable name", "a", lv.getName());

final InstructionHandle start = lv.getStart();

final InstructionHandle end = lv.getEnd();

assertNotNull("scope start", start);

assertNotNull("scope end", end);

assertTrue("scope start not targeted by the local variable", Arrays.asList(start.getTargeters()).contains(lv));

assertTrue("scope end not targeted by the local variable", Arrays.asList(end.getTargeters()).contains(lv));



mg.removeLocalVariable(lv);



assertFalse("scope start still targeted by the removed variable", Arrays.asList(start.getTargeters()).contains(lv));

assertFalse("scope end still targeted by the removed variable", Arrays.asList(end.getTargeters()).contains(lv));

assertNull("scope start", lv.getStart());

assertNull("scope end", lv.getEnd());

}


   Like      Feedback      org.apache.bcel.generic.MethodGen


 Sample 692. Code Sample / Example / Snippet of org.apache.bcel.generic.InvokeInstruction

    public void testB262() throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestEnum");

final ClassGen gen = new ClassGen(clazz);

final ConstantPoolGen pool = gen.getConstantPool();

final Method m = gen.getMethodAt(0);

final MethodGen mg = new MethodGen(m, gen.getClassName(), pool);

final InstructionList il = mg.getInstructionList();

final InstructionHandle ih = il.findHandle(3);

final InvokeInstruction ii = (InvokeInstruction)(ih.getInstruction());

final String cn = ii.getClassName(pool);

assertEquals("[Lorg.apache.bcel.data.PLSETestEnum;", cn);

}


   Like      Feedback      org.apache.bcel.generic.InvokeInstruction


 Sample 693. Code Sample / Example / Snippet of org.apache.bcel.classfile.LocalVariableTable

    public void testB79() throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass");

final ClassGen gen = new ClassGen(clazz);

final ConstantPoolGen pool = gen.getConstantPool();

final Method m = gen.getMethodAt(2);

final LocalVariableTable lvt = m.getLocalVariableTable();

final MethodGen mg = new MethodGen(m, gen.getClassName(), pool);

final LocalVariableTable new_lvt = mg.getLocalVariableTable(mg.getConstantPool());

assertEquals("number of locals", lvt.getTableLength(), new_lvt.getTableLength());

}


   Like      Feedback      org.apache.bcel.classfile.LocalVariableTable


 Sample 694. Code Sample / Example / Snippet of org.apache.bcel.generic.FieldGen

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

JavaClass clazz;



if ((clazz = Repository.lookupClass(argv[0])) == null) {

clazz = new ClassParser(argv[0]).parse(); // May throw IOException

}



ClassGen cg = new ClassGen(clazz);



for (Method method : clazz.getMethods()) {

MethodGen mg = new MethodGen(method, cg.getClassName(), cg.getConstantPool());

cg.replaceMethod(method, mg.getMethod());

}



for (Field field : clazz.getFields()) {

FieldGen fg = new FieldGen(field, cg.getConstantPool());

cg.replaceField(field, fg.getField());

}



cg.getJavaClass().dump(clazz.getClassName() + ".clazz");

}


   Like      Feedback      org.apache.bcel.generic.FieldGen


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 695. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantUtf8

    public static String[] getClassDependencies(ConstantPool pool) {

String[] tempArray = new String[pool.getLength()];

int size = 0;

StringBuilder buf = new StringBuilder();



for (int idx = 0; idx < pool.getLength(); idx++) {

Constant c = pool.getConstant(idx);

if (c != null && c.getTag() == Constants.CONSTANT_Class) {

ConstantUtf8 c1 = (ConstantUtf8) pool.getConstant(((ConstantClass) c).getNameIndex());

buf.setLength(0);

buf.append(c1.getBytes());

for (int n = 0; n < buf.length(); n++) {

if (buf.charAt(n) == '/') {

buf.setCharAt(n, '.');

}

}



tempArray[size++] = buf.toString();

}

}



String[] dependencies = new String[size];

System.arraycopy(tempArray, 0, dependencies, 0, size);

return dependencies;

}


   Like      Feedback      org.apache.bcel.classfile.ConstantUtf8


 Sample 696. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantNameAndType

    private void visitRef(ConstantCP ccp, boolean method) {

String class_name = ccp.getClass(cp);

add(class_name);



ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(ccp.getNameAndTypeIndex(),

Constants.CONSTANT_NameAndType);



String signature = cnat.getSignature(cp);



if (method) {

Type type = Type.getReturnType(signature);



checkType(type);



for (Type type1 : Type.getArgumentTypes(signature)) {

checkType(type1);

}

} else {

checkType(Type.getType(signature));

}

}


   Like      Feedback      org.apache.bcel.classfile.ConstantNameAndType


 Sample 697. Code Sample / Example / Snippet of org.apache.bcel.generic.LocalVariableGen

    public void testRemoveLocalVariable() throws Exception {

final MethodGen mg = getMethod(Foo.class, "bar");



final LocalVariableGen lv = mg.getLocalVariables()[1];

assertEquals("variable name", "a", lv.getName());

final InstructionHandle start = lv.getStart();

final InstructionHandle end = lv.getEnd();

assertNotNull("scope start", start);

assertNotNull("scope end", end);

assertTrue("scope start not targeted by the local variable", Arrays.asList(start.getTargeters()).contains(lv));

assertTrue("scope end not targeted by the local variable", Arrays.asList(end.getTargeters()).contains(lv));



mg.removeLocalVariable(lv);



assertFalse("scope start still targeted by the removed variable", Arrays.asList(start.getTargeters()).contains(lv));

assertFalse("scope end still targeted by the removed variable", Arrays.asList(end.getTargeters()).contains(lv));

assertNull("scope start", lv.getStart());

assertNull("scope end", lv.getEnd());

}


   Like      Feedback      org.apache.bcel.generic.LocalVariableGen


 Sample 698. Code Sample / Example / Snippet of org.apache.bcel.util.BCELifier

    public void test() throws Exception {

final OutputStream os = new ByteArrayOutputStream();

final JavaClass java_class = BCELifier.getJavaClass("Java8Example");

assertNotNull(java_class);

final BCELifier bcelifier = new BCELifier(java_class, os);

bcelifier.start();

}


   Like      Feedback      org.apache.bcel.util.BCELifier


 Sample 699. Code Sample / Example / Snippet of org.apache.bcel.util.InstructionFinder

    public void testSearch() {

final InstructionList il = new InstructionList();

il.append(new ILOAD(1));

il.append(new ILOAD(2));

il.append(new IADD());

il.append(new ISTORE(3));

final InstructionFinder finder = new InstructionFinder(il);



final Iterator<?> it = finder.search("ILOAD IADD", il.getInstructionHandles()[0], null );

final InstructionHandle[] ihs = (InstructionHandle[])it.next();

assertEquals(2, ihs.length);

assertEquals(ihs[0].getInstruction(), new ILOAD(2));

assertEquals(ihs[1].getInstruction(), new IADD());

}


   Like      Feedback      org.apache.bcel.util.InstructionFinder


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 700. Code Sample / Example / Snippet of org.apache.bcel.util.ClassPath

    public static ClassPath.ClassFile lookupClassFile( final String class_name ) {

try {

final ClassPath path = repository.getClassPath();

if (path == null) {

return null;

}

return path.getClassFile(class_name);

} catch (final IOException e) {

return null;

}

}


   Like      Feedback      org.apache.bcel.util.ClassPath


 Sample 701. Code Sample / Example / Snippet of org.apache.bcel.classfile.Constant

    public String getEnumTypeString()

{

return ((ConstantUtf8) getConstantPool().getConstant(typeIdx))

.getBytes();

}


   Like      Feedback      org.apache.bcel.classfile.Constant


 Sample 702. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantInteger

    public int getValueInt()

{

if (super.getElementValueType() != PRIMITIVE_INT) {

throw new RuntimeException(

"Dont call getValueString() on a non STRING ElementValue");

}

final ConstantInteger c = (ConstantInteger) getConstantPool().getConstant(idx);

return c.getBytes();

}


   Like      Feedback      org.apache.bcel.classfile.ConstantInteger


 Sample 703. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantClass

    public String getEnumTypeString()

{

return ((ConstantUtf8) getConstantPool().getConstant(typeIdx))

.getBytes();

}


   Like      Feedback      org.apache.bcel.classfile.ConstantClass


 Sample 704. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantCP

    public String getClassName( final ConstantPoolGen cpg ) {

final ConstantPool cp = cpg.getConstantPool();

final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());

final String className = cp.getConstantString(cmr.getClassIndex(), Const.CONSTANT_Class);

if (className.startsWith("[")) {

return "java.lang.Object";

}

return className.replace('/', '.');

}


   Like      Feedback      org.apache.bcel.classfile.ConstantCP


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 705. Code Sample / Example / Snippet of org.apache.bcel.classfile.Annotations

    public FieldGen(final Field field, final ConstantPoolGen cp) {

this(field.getAccessFlags(), Type.getType(field.getSignature()), field.getName(), cp);

final Attribute[] attrs = field.getAttributes();

for (final Attribute attr : attrs) {

if (attr instanceof ConstantValue) {

setValue(((ConstantValue) attr).getConstantValueIndex());

} else if (attr instanceof Annotations) {

final Annotations runtimeAnnotations = (Annotations)attr;

final AnnotationEntry[] annotationEntries = runtimeAnnotations.getAnnotationEntries();

for (final AnnotationEntry element : annotationEntries) {

addAnnotationEntry(new AnnotationEntryGen(element,cp,false));

}

} else {

addAttribute(attr);

}

}

}


   Like      Feedback      org.apache.bcel.classfile.Annotations


 Sample 706. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantFloat

    public int lookupFloat( final float n ) {

final int bits = Float.floatToIntBits(n);

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

if (constants[i] instanceof ConstantFloat) {

final ConstantFloat c = (ConstantFloat) constants[i];

if (Float.floatToIntBits(c.getBytes()) == bits) {

return i;

}

}

}

return -1;

}


   Like      Feedback      org.apache.bcel.classfile.ConstantFloat


 Sample 707. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantString

    public String stringifyValue()

{

final ConstantUtf8 cu8 = (ConstantUtf8) getConstantPool().getConstant(valueIdx);

return cu8.getBytes();

}


   Like      Feedback      org.apache.bcel.classfile.ConstantString


 Sample 708. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantLong

    public int lookupLong( final long n ) {

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

if (constants[i] instanceof ConstantLong) {

final ConstantLong c = (ConstantLong) constants[i];

if (c.getBytes() == n) {

return i;

}

}

}

return -1;

}


   Like      Feedback      org.apache.bcel.classfile.ConstantLong


 Sample 709. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantDouble

    public int lookupDouble( final double n ) {

final long bits = Double.doubleToLongBits(n);

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

if (constants[i] instanceof ConstantDouble) {

final ConstantDouble c = (ConstantDouble) constants[i];

if (Double.doubleToLongBits(c.getBytes()) == bits) {

return i;

}

}

}

return -1;

}


   Like      Feedback      org.apache.bcel.classfile.ConstantDouble


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 710. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantValue

    public void visitField( final Field field ) {

_out.println();

_out.println(" field = new FieldGen(" + printFlags(field.getAccessFlags()) + ", "

+ printType(field.getSignature()) + ", "" + field.getName() + "", _cp);");

final ConstantValue cv = field.getConstantValue();

if (cv != null) {

final String value = cv.toString();

_out.println(" field.setInitValue(" + value + ")");

}

_out.println(" _cg.addField(field.getField());");

}


   Like      Feedback      org.apache.bcel.classfile.ConstantValue


 Sample 711. Code Sample / Example / Snippet of org.apache.bcel.generic.BranchHandle

    private static BranchHandle bh_list = null; // List of reusable handles





static BranchHandle getBranchHandle( final BranchInstruction i ) {

if (bh_list == null) {

return new BranchHandle(i);

}

final BranchHandle bh = bh_list;

bh_list = (BranchHandle) bh.getNext();

bh.setInstruction(i);

return bh;

}


   Like      Feedback      org.apache.bcel.generic.BranchHandle


 Sample 712. Code Sample / Example / Snippet of org.apache.bcel.generic.BranchInstruction

    public void redirectBranches(final InstructionHandle old_target, final InstructionHandle new_target) {

for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) {

final Instruction i = ih.getInstruction();

if (i instanceof BranchInstruction) {

final BranchInstruction b = (BranchInstruction) i;

final InstructionHandle target = b.getTarget();

if (target == old_target) {

b.setTarget(new_target);

}

if (b instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH

final InstructionHandle[] targets = ((Select) b).getTargets();

for (int j = 0; j < targets.length; j++) {

if (targets[j] == old_target) {

((Select) b).setTarget(j, new_target);

}

}

}

}

}

}


   Like      Feedback      org.apache.bcel.generic.BranchInstruction


 Sample 713. Code Sample / Example / Snippet of org.apache.bcel.generic.Instruction

    public Instruction copy() {

Instruction i = null;

if (InstructionConst.getInstruction(this.getOpcode()) != null) {

i = this;

} else {

try {

i = (Instruction) clone();

} catch (final CloneNotSupportedException e) {

System.err.println(e);

}

}

return i;

}




   Like      Feedback      org.apache.bcel.generic.Instruction


 Sample 714. Code Sample / Example / Snippet of org.apache.bcel.generic.Select

    protected Object clone() throws CloneNotSupportedException {

final Select copy = (Select) super.clone();

copy.match = match.clone();

copy.indices = indices.clone();

copy.targets = targets.clone();

return copy;

}


   Like      Feedback      org.apache.bcel.generic.Select


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 715. Code Sample / Example / Snippet of org.apache.bcel.generic.CPInstruction

    public void replaceConstantPool(final ConstantPoolGen old_cp, final ConstantPoolGen new_cp) {

for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) {

final Instruction i = ih.getInstruction();

if (i instanceof CPInstruction) {

final CPInstruction ci = (CPInstruction) i;

final Constant c = old_cp.getConstant(ci.getIndex());

ci.setIndex(new_cp.addConstant(c, old_cp));

}

}

}


   Like      Feedback      org.apache.bcel.generic.CPInstruction


 Sample 716. Code Sample / Example / Snippet of org.apache.bcel.util.ClassQueue

    public JavaClass[] getAllInterfaces() throws ClassNotFoundException {

final ClassQueue queue = new ClassQueue();

final Set<JavaClass> allInterfaces = new TreeSet<>();

queue.enqueue(this);

while (!queue.empty()) {

final JavaClass clazz = queue.dequeue();

final JavaClass souper = clazz.getSuperClass();

final JavaClass[] _interfaces = clazz.getInterfaces();

if (clazz.isInterface()) {

allInterfaces.add(clazz);

} else {

if (souper != null) {

queue.enqueue(souper);

}

}

for (final JavaClass _interface : _interfaces) {

queue.enqueue(_interface);

}

}

return allInterfaces.toArray(new JavaClass[allInterfaces.size()]);

}


   Like      Feedback      org.apache.bcel.util.ClassQueue


 Sample 717. Code Sample / Example / Snippet of org.apache.bcel.generic.ReferenceType

    public ObjectType getLoadClassType( final ConstantPoolGen cpg ) {

final ReferenceType rt = getReferenceType(cpg);

if(rt instanceof ObjectType) {

return (ObjectType)rt;

}

throw new ClassGenException(rt.getSignature() + " does not represent an ObjectType");

}


   Like      Feedback      org.apache.bcel.generic.ReferenceType


 Sample 718. Code Sample / Example / Snippet of org.apache.bcel.verifier.VerificationResult

    public void testDefaultMethodValidation() {

final String classname = Collection.class.getName();



final Verifier verifier = VerifierFactory.getVerifier(classname);

VerificationResult result = verifier.doPass1();



assertEquals("Pass 1 verification of " + classname + " failed: " + result.getMessage(), VerificationResult.VERIFIED_OK,

result.getStatus());



result = verifier.doPass2();



assertEquals("Pass 2 verification of " + classname + " failed: " + result.getMessage(), VerificationResult.VERIFIED_OK,

result.getStatus());

}


   Like      Feedback      org.apache.bcel.verifier.VerificationResult


 Sample 719. Code Sample / Example / Snippet of org.apache.bcel.verifier.Verifier

    public void testDefaultMethodValidation() {

final String classname = Collection.class.getName();



final Verifier verifier = VerifierFactory.getVerifier(classname);

VerificationResult result = verifier.doPass1();



assertEquals("Pass 1 verification of " + classname + " failed: " + result.getMessage(), VerificationResult.VERIFIED_OK,

result.getStatus());



result = verifier.doPass2();



assertEquals("Pass 2 verification of " + classname + " failed: " + result.getMessage(), VerificationResult.VERIFIED_OK,

result.getStatus());

}


   Like      Feedback      org.apache.bcel.verifier.Verifier


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 720. Code Sample / Example / Snippet of org.apache.bcel.classfile.MethodParameters

    public Attribute copy(final ConstantPool _constant_pool) {

final MethodParameters c = (MethodParameters) clone();

c.parameters = new MethodParameter[parameters.length];



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

c.parameters[i] = parameters[i].copy();

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.MethodParameters


 Sample 721. Code Sample / Example / Snippet of org.apache.bcel.classfile.BootstrapMethods

    public BootstrapMethods copy(final ConstantPool _constant_pool) {

final BootstrapMethods c = (BootstrapMethods) clone();

c.bootstrap_methods = new BootstrapMethod[bootstrap_methods.length];



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

c.bootstrap_methods[i] = bootstrap_methods[i].copy();

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.BootstrapMethods


 Sample 722. Code Sample / Example / Snippet of org.apache.bcel.classfile.InnerClasses

public Attribute copy(final ConstantPool _constant_pool) {
final InnerClasses c = (InnerClasses) clone();
c.inner_classes = new InnerClass[inner_classes.length];
for (int i = 0; i < inner_classes.length; i++) {
c.inner_classes[i] = inner_classes[i].copy();
}
c.setConstantPool(_constant_pool);
return c;
}

   Like      Feedback      org.apache.bcel.classfile.InnerClasses  object initialization using clone


 Sample 723. Code Sample / Example / Snippet of org.apache.bcel.classfile.Synthetic

    public Attribute copy( final ConstantPool _constant_pool ) {

final Synthetic c = (Synthetic) 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.Synthetic


 Sample 724. Code Sample / Example / Snippet of org.apache.bcel.classfile.LocalVariableTypeTable

    public Attribute copy(final ConstantPool constant_pool) {

final LocalVariableTypeTable c = (LocalVariableTypeTable) clone();



c.local_variable_type_table = new LocalVariable[local_variable_type_table.length];

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

c.local_variable_type_table[i] = local_variable_type_table[i].copy();

}



c.setConstantPool(constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.LocalVariableTypeTable


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 725. Code Sample / Example / Snippet of org.apache.bcel.classfile.Node

  public void jjtAddChild(Node n, int i) {

if (children == null) {

children = new Node[i + 1];

} else if (i >= children.length) {

Node c[] = new Node[i + 1];

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

children = c;

}

children[i] = n;

}


   Like      Feedback      org.apache.bcel.classfile.Node


 Sample 726. Code Sample / Example / Snippet of org.apache.bcel.classfile.ParameterAnnotations

  public static ParameterAnnotationEntry[] createParameterAnnotationEntries(final Attribute[] attrs) {

final List<ParameterAnnotationEntry> accumulatedAnnotations = new ArrayList<>(attrs.length);

for (final Attribute attribute : attrs) {

if (attribute instanceof ParameterAnnotations) {

final ParameterAnnotations runtimeAnnotations = (ParameterAnnotations)attribute;

Collections.addAll(accumulatedAnnotations, runtimeAnnotations.getParameterAnnotationEntries());

}

}

return accumulatedAnnotations.toArray(new ParameterAnnotationEntry[accumulatedAnnotations.size()]);

}


   Like      Feedback      org.apache.bcel.classfile.ParameterAnnotations


 Sample 727. Code Sample / Example / Snippet of org.apache.bcel.classfile.Unknown

    public Attribute copy( final ConstantPool _constant_pool ) {

final Unknown c = (Unknown) 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.Unknown


 Sample 728. Code Sample / Example / Snippet of org.apache.bcel.classfile.StackMap

    public Attribute copy( final ConstantPool _constant_pool ) {

final StackMap c = (StackMap) clone();

c.map = new StackMapEntry[map.length];

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

c.map[i] = map[i].copy();

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.StackMap


 Sample 729. Code Sample / Example / Snippet of org.apache.bcel.classfile.LineNumberTable

    public Attribute copy( final ConstantPool _constant_pool ) {

final LineNumberTable c = (LineNumberTable) clone();

c.line_number_table = new LineNumber[line_number_table.length];

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

c.line_number_table[i] = line_number_table[i].copy();

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.LineNumberTable


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 730. Code Sample / Example / Snippet of org.apache.bcel.classfile.DescendingVisitor

    private void field_and_method_refs_are_valid() {

try {

final JavaClass jc = Repository.lookupClass(myOwner.getClassName());

final DescendingVisitor v = new DescendingVisitor(jc, new FAMRAV_Visitor(jc));

v.visit();



} catch (final ClassNotFoundException e) {

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

}

}


   Like      Feedback      org.apache.bcel.classfile.DescendingVisitor


 Sample 731. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveEntry

    private void addArchiveEntry(final ArchiveOutputStream out, final String filename, final File infile)

throws IOException, FileNotFoundException {

final ArchiveEntry entry = out.createArchiveEntry(infile, filename);

out.putArchiveEntry(entry);

IOUtils.copy(new FileInputStream(infile), out);

out.closeArchiveEntry();

archiveList.add(filename);

}


   Like      Feedback      org.apache.commons.compress.archivers.ArchiveEntry


 Sample 732. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveOutputStream

    protected File createEmptyArchive(final String archivename) throws Exception {

ArchiveOutputStream out = null;

OutputStream stream = null;

archiveList = new ArrayList<String>();

try {

archive = File.createTempFile("empty", "." + archivename);

archive.deleteOnExit();

stream = new FileOutputStream(archive);

out = factory.createArchiveOutputStream(archivename, stream);

out.finish();

} finally {

if (out != null) {

out.close();

} else if (stream != null) {

stream.close();

}

}

return archive;

}


   Like      Feedback      org.apache.commons.compress.archivers.ArchiveOutputStream


 Sample 733. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveInputStream

    protected void checkArchiveContent(final File archive, final List<String> expected)

throws Exception {

final InputStream is = new FileInputStream(archive);

try {

final BufferedInputStream buf = new BufferedInputStream(is);

final ArchiveInputStream in = factory.createArchiveInputStream(buf);

this.checkArchiveContent(in, expected);

} finally {

is.close();

}

}


   Like      Feedback      org.apache.commons.compress.archivers.ArchiveInputStream


 Sample 734. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.tar.TarArchiveEntry

    protected String getExpectedString(final ArchiveEntry entry) {

if (entry instanceof TarArchiveEntry) {

final TarArchiveEntry tarEntry = (TarArchiveEntry) entry;

if (tarEntry.isSymbolicLink()) {

return tarEntry.getName() + " -> " + tarEntry.getLinkName();

}

}

return entry.getName();

}


   Like      Feedback      org.apache.commons.compress.archivers.tar.TarArchiveEntry


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 735. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipArchiveInputStream

    private void testZipStreamWithImplodeCompression(final String filename, final String entryName) throws IOException {

final ZipArchiveInputStream zin = new ZipArchiveInputStream(new FileInputStream(new File(filename)));

final ZipArchiveEntry entry = zin.getNextZipEntry();

assertEquals("entry name", entryName, entry.getName());

assertTrue("entry can't be read", zin.canReadEntryData(entry));

assertEquals("method", ZipMethod.IMPLODING.getCode(), entry.getMethod());



final InputStream bio = new BoundedInputStream(zin, entry.getSize());



final ByteArrayOutputStream bout = new ByteArrayOutputStream();

final CheckedOutputStream out = new CheckedOutputStream(bout, new CRC32());

IOUtils.copy(bio, out);



out.flush();



assertEquals("CRC32", entry.getCrc(), out.getChecksum().getValue());

}


   Like      Feedback      org.apache.commons.compress.archivers.zip.ZipArchiveInputStream


 Sample 736. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.arj.ArjArchiveInputStream

    public void testArjUnarchive() throws Exception {

final StringBuilder expected = new StringBuilder();

expected.append("test1.xml<?xml version="1.0"?> ");

expected.append("<empty/>test2.xml<?xml version="1.0"?> ");

expected.append("<empty/> ");





final ArjArchiveInputStream in = new ArjArchiveInputStream(new FileInputStream(getFile("bla.arj")));

ArjArchiveEntry entry;



final StringBuilder result = new StringBuilder();

while ((entry = in.getNextEntry()) != null) {

result.append(entry.getName());

int tmp;

while ((tmp = in.read()) != -1) {

result.append((char) tmp);

}

assertFalse(entry.isDirectory());

}

in.close();

assertEquals(result.toString(), expected.toString());

}


   Like      Feedback      org.apache.commons.compress.archivers.arj.ArjArchiveInputStream


 Sample 737. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ar.ArArchiveEntry

    public void testLongFileNamesCauseExceptionByDefault() {

ArArchiveOutputStream os = null;

try {

os = new ArArchiveOutputStream(new ByteArrayOutputStream());

final ArArchiveEntry ae = new ArArchiveEntry("this_is_a_long_name.txt",

0);

os.putArchiveEntry(ae);

fail("Expected an exception");

} catch (final IOException ex) {

assertTrue(ex.getMessage().startsWith("filename too long"));

} finally {

closeQuietly(os);

}

}


   Like      Feedback      org.apache.commons.compress.archivers.ar.ArArchiveEntry


 Sample 738. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipArchiveEntry

    public void testCompressionMethod() throws Exception {

final ZipArchiveOutputStream zos =

new ZipArchiveOutputStream(new ByteArrayOutputStream());

final ZipArchiveEntry entry = new ZipArchiveEntry("foo");

assertEquals(-1, entry.getMethod());

assertFalse(zos.canWriteEntryData(entry));



entry.setMethod(ZipEntry.STORED);

assertEquals(ZipEntry.STORED, entry.getMethod());

assertTrue(zos.canWriteEntryData(entry));



entry.setMethod(ZipEntry.DEFLATED);

assertEquals(ZipEntry.DEFLATED, entry.getMethod());

assertTrue(zos.canWriteEntryData(entry));



entry.setMethod(6);

assertEquals(6, entry.getMethod());

assertFalse(zos.canWriteEntryData(entry));

zos.close();

}


   Like      Feedback      org.apache.commons.compress.archivers.zip.ZipArchiveEntry


 Sample 739. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipFile

    private void removeEntriesFoundInZipFile(final File result, final Map<String, byte[]> entries) throws IOException {

final ZipFile zf = new ZipFile(result);

final Enumeration<ZipArchiveEntry> entriesInPhysicalOrder = zf.getEntriesInPhysicalOrder();

while (entriesInPhysicalOrder.hasMoreElements()){

final ZipArchiveEntry zipArchiveEntry = entriesInPhysicalOrder.nextElement();

final InputStream inputStream = zf.getInputStream(zipArchiveEntry);

final byte[] actual = IOUtils.toByteArray(inputStream);

final byte[] expected = entries.remove(zipArchiveEntry.getName());

assertArrayEquals( "For " + zipArchiveEntry.getName(), expected, actual);

}

zf.close();

}


   Like      Feedback      org.apache.commons.compress.archivers.zip.ZipFile


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 740. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.sevenz.SevenZOutputFile

    public void testReadingBackLZMA2DictSize() throws Exception {

final File output = new File(dir, "lzma2-dictsize.7z");

final SevenZOutputFile outArchive = new SevenZOutputFile(output);

try {

outArchive.setContentMethods(Arrays.asList(new SevenZMethodConfiguration(SevenZMethod.LZMA2, 1 << 20)));

final SevenZArchiveEntry entry = new SevenZArchiveEntry();

entry.setName("foo.txt");

outArchive.putArchiveEntry(entry);

outArchive.write(new byte[] { 'A' });

outArchive.closeArchiveEntry();

} finally {

outArchive.close();

}



final SevenZFile archive = new SevenZFile(output);

try {

final SevenZArchiveEntry entry = archive.getNextEntry();

final SevenZMethodConfiguration m = entry.getContentMethods().iterator().next();

assertEquals(SevenZMethod.LZMA2, m.getMethod());

assertEquals(1 << 20, m.getOptions());

} finally {

archive.close();

}

}


   Like      Feedback      org.apache.commons.compress.archivers.sevenz.SevenZOutputFile


 Sample 741. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.sevenz.SevenZFile

    public void testAllEmptyFilesArchive() throws Exception {

final SevenZFile archive = new SevenZFile(getFile("7z-empty-mhc-off.7z"));

try {

assertNotNull(archive.getNextEntry());

} finally {

archive.close();

}

}


   Like      Feedback      org.apache.commons.compress.archivers.sevenz.SevenZFile


 Sample 742. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry

    public void testReadingBackLZMA2DictSize() throws Exception {

final File output = new File(dir, "lzma2-dictsize.7z");

final SevenZOutputFile outArchive = new SevenZOutputFile(output);

try {

outArchive.setContentMethods(Arrays.asList(new SevenZMethodConfiguration(SevenZMethod.LZMA2, 1 << 20)));

final SevenZArchiveEntry entry = new SevenZArchiveEntry();

entry.setName("foo.txt");

outArchive.putArchiveEntry(entry);

outArchive.write(new byte[] { 'A' });

outArchive.closeArchiveEntry();

} finally {

outArchive.close();

}



final SevenZFile archive = new SevenZFile(output);

try {

final SevenZArchiveEntry entry = archive.getNextEntry();

final SevenZMethodConfiguration m = entry.getContentMethods().iterator().next();

assertEquals(SevenZMethod.LZMA2, m.getMethod());

assertEquals(1 << 20, m.getOptions());

} finally {

archive.close();

}

}


   Like      Feedback      org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry


 Sample 743. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream

    public void testCpioUnarchive() throws Exception {

final StringBuilder expected = new StringBuilder();

expected.append("./test1.xml<?xml version="1.0"?> ");

expected.append("<empty/>./test2.xml<?xml version="1.0"?> ");

expected.append("<empty/> ");





final CpioArchiveInputStream in = new CpioArchiveInputStream(new FileInputStream(getFile("bla.cpio")));

CpioArchiveEntry entry;



final StringBuilder result = new StringBuilder();

while ((entry = (CpioArchiveEntry) in.getNextEntry()) != null) {

result.append(entry.getName());

int tmp;

while ((tmp = in.read()) != -1) {

result.append((char) tmp);

}

}

in.close();

assertEquals(result.toString(), expected.toString());

}


   Like      Feedback      org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream


 Sample 744. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipEncoding

    private static void assertUnicodeName(final ZipArchiveEntry ze,

final String expectedName,

final String encoding)

throws IOException {

if (!expectedName.equals(ze.getName())) {

final UnicodePathExtraField ucpf = findUniCodePath(ze);

assertNotNull(ucpf);



final ZipEncoding enc = ZipEncodingHelper.getZipEncoding(encoding);

final ByteBuffer ne = enc.encode(ze.getName());



final CRC32 crc = new CRC32();

crc.update(ne.array(), ne.arrayOffset(),

ne.limit() - ne.position());



assertEquals(crc.getValue(), ucpf.getNameCRC32());

assertEquals(expectedName, new String(ucpf.getUnicodeName(),

CharsetNames.UTF_8));

}

}


   Like      Feedback      org.apache.commons.compress.archivers.zip.ZipEncoding


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 745. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveStreamFactory

    public void testEncodingCtor() {

ArchiveStreamFactory fac = new ArchiveStreamFactory();

assertNull(fac.getEntryEncoding());

fac = new ArchiveStreamFactory(null);

assertNull(fac.getEntryEncoding());

fac = new ArchiveStreamFactory("UTF-8");

assertEquals("UTF-8", fac.getEntryEncoding());

}


   Like      Feedback      org.apache.commons.compress.archivers.ArchiveStreamFactory


 Sample 746. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.CompressorStreamFactory

    public void testOverride() {

CompressorStreamFactory fac = new CompressorStreamFactory();

assertFalse(fac.getDecompressConcatenated());

fac.setDecompressConcatenated(true);

assertTrue(fac.getDecompressConcatenated());



fac = new CompressorStreamFactory(false);

assertFalse(fac.getDecompressConcatenated());

try {

fac.setDecompressConcatenated(true);

fail("Expected IllegalStateException");

} catch (final IllegalStateException ise) {

}



fac = new CompressorStreamFactory(true);

assertTrue(fac.getDecompressConcatenated());

try {

fac.setDecompressConcatenated(true);

fail("Expected IllegalStateException");

} catch (final IllegalStateException ise) {

}

}


   Like      Feedback      org.apache.commons.compress.compressors.CompressorStreamFactory


 Sample 747. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.CompressorInputStream

    public void testBzip2Unarchive() throws Exception {

final File input = getFile("bla.txt.bz2");

final File output = new File(dir, "bla.txt");

final InputStream is = new FileInputStream(input);

final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);

final FileOutputStream os = new FileOutputStream(output);

IOUtils.copy(in, os);

is.close();

os.close();

}


   Like      Feedback      org.apache.commons.compress.compressors.CompressorInputStream


 Sample 748. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.gzip.GzipParameters

    public void testInvalidCompressionLevel() {

final GzipParameters parameters = new GzipParameters();

try {

parameters.setCompressionLevel(10);

fail("IllegalArgumentException not thrown");

} catch (final IllegalArgumentException e) {

}



try {

parameters.setCompressionLevel(-5);

fail("IllegalArgumentException not thrown");

} catch (final IllegalArgumentException e) {

}

}


   Like      Feedback      org.apache.commons.compress.compressors.gzip.GzipParameters


 Sample 749. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream

    private void testExtraFlags(final int compressionLevel, final int flag) throws Exception {

final FileInputStream fis = new FileInputStream(getFile("test3.xml"));

byte[] content;

try {

content = IOUtils.toByteArray(fis);

} finally {

fis.close();

}



final ByteArrayOutputStream bout = new ByteArrayOutputStream();



final GzipParameters parameters = new GzipParameters();

parameters.setCompressionLevel(compressionLevel);

final GzipCompressorOutputStream out = new GzipCompressorOutputStream(bout, parameters);

IOUtils.copy(new ByteArrayInputStream(content), out);

out.flush();

out.close();



assertEquals("extra flags (XFL)", flag, bout.toByteArray()[8]);

}


   Like      Feedback      org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 750. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.deflate.DeflateParameters

    public void testRawDeflateCreation()  throws Exception {

final File input = getFile("test1.xml");

final File output = new File(dir, "test1.xml.deflate");

final OutputStream out = new FileOutputStream(output);

try {

final DeflateParameters params = new DeflateParameters();

params.setWithZlibHeader(false);

final CompressorOutputStream cos = new DeflateCompressorOutputStream(out, params);

try {

IOUtils.copy(new FileInputStream(input), cos);

} finally {

cos.close();

}

} finally {

out.close();

}

}


   Like      Feedback      org.apache.commons.compress.compressors.deflate.DeflateParameters


 Sample 751. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.tar.TarArchiveInputStream

    public void readSimplePaxHeader() throws Exception {

final InputStream is = new ByteArrayInputStream(new byte[1]);

final TarArchiveInputStream tais = new TarArchiveInputStream(is);

final Map<String, String> headers = tais

.parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463 "

.getBytes(CharsetNames.UTF_8)));

assertEquals(1, headers.size());

assertEquals("1321711775.972059463", headers.get("atime"));

tais.close();

}


   Like      Feedback      org.apache.commons.compress.archivers.tar.TarArchiveInputStream


 Sample 752. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream

    public void readOfLength0ShouldReturn0() throws Exception {

final byte[] rawData = new byte[1048576];

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

rawData[i] = (byte) Math.floor(Math.random()*256);

}



final ByteArrayOutputStream baos = new ByteArrayOutputStream();

final BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos);

bzipOut.write(rawData);

bzipOut.flush();

bzipOut.close();

baos.flush();

baos.close();



final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

final BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais);

final byte[] buffer = new byte[1024];

Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));

Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0));

Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));

bzipIn.close();

}


   Like      Feedback      org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream


 Sample 753. Code Sample / Example / Snippet of org.apache.commons.compress.utils.BitInputStream

    public void testClearBitCache() throws IOException {

final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);

assertEquals(0x08, bis.readBits(4));

bis.clearBitCache();

assertEquals(0, bis.readBits(1));

bis.close();

}


   Like      Feedback      org.apache.commons.compress.utils.BitInputStream


 Sample 754. Code Sample / Example / Snippet of org.apache.commons.compress.utils.BoundedInputStream

    public void writeTo(final ZipArchiveOutputStream target) throws IOException {

backingStore.closeForWriting();

final InputStream data = backingStore.getInputStream();

for (final CompressedEntry compressedEntry : items) {

final BoundedInputStream rawStream = new BoundedInputStream(data, compressedEntry.compressedSize);

target.addRawArchiveEntry(compressedEntry.transferToArchiveEntry(), rawStream);

rawStream.close();

}

data.close();

}


   Like      Feedback      org.apache.commons.compress.utils.BoundedInputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 755. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream

    public void testCompressionMethod() throws Exception {

final ZipArchiveOutputStream zos =

new ZipArchiveOutputStream(new ByteArrayOutputStream());

final ZipArchiveEntry entry = new ZipArchiveEntry("foo");

assertEquals(-1, entry.getMethod());

assertFalse(zos.canWriteEntryData(entry));



entry.setMethod(ZipEntry.STORED);

assertEquals(ZipEntry.STORED, entry.getMethod());

assertTrue(zos.canWriteEntryData(entry));



entry.setMethod(ZipEntry.DEFLATED);

assertEquals(ZipEntry.DEFLATED, entry.getMethod());

assertTrue(zos.canWriteEntryData(entry));



entry.setMethod(6);

assertEquals(6, entry.getMethod());

assertFalse(zos.canWriteEntryData(entry));

zos.close();

}


   Like      Feedback      org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream


 Sample 756. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.tar.TarArchiveOutputStream

    public void shouldUseSpecifiedEncodingWhenReadingGNULongNames()

throws Exception {

final ByteArrayOutputStream bos = new ByteArrayOutputStream();

final String encoding = CharsetNames.UTF_16;

final String name = "1234567890123456789012345678901234567890123456789"

+ "01234567890123456789012345678901234567890123456789"

+ "01234567890u00e4";

final TarArchiveOutputStream tos =

new TarArchiveOutputStream(bos, encoding);

tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

TarArchiveEntry t = new TarArchiveEntry(name);

t.setSize(1);

tos.putArchiveEntry(t);

tos.write(30);

tos.closeArchiveEntry();

tos.close();

final byte[] data = bos.toByteArray();

final ByteArrayInputStream bis = new ByteArrayInputStream(data);

final TarArchiveInputStream tis =

new TarArchiveInputStream(bis, encoding);

t = tis.getNextTarEntry();

assertEquals(name, t.getName());

tis.close();

}


   Like      Feedback      org.apache.commons.compress.archivers.tar.TarArchiveOutputStream


 Sample 757. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.dump.DumpArchiveInputStream

    public void testConsumesArchiveCompletely() throws Exception {

final InputStream is = DumpArchiveInputStreamTest.class

.getResourceAsStream("/archive_with_trailer.dump");

final DumpArchiveInputStream dump = new DumpArchiveInputStream(is);

while (dump.getNextDumpEntry() != null) {

}

final byte[] expected = new byte[] {

'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', ' '

};

final byte[] actual = new byte[expected.length];

is.read(actual);

assertArrayEquals(expected, actual);

dump.close();

}


   Like      Feedback      org.apache.commons.compress.archivers.dump.DumpArchiveInputStream


 Sample 758. Code Sample / Example / Snippet of org.tukaani.xz.LZMA2Options

    private LZMA2Options getOptions(final Object opts) throws IOException {

if (opts instanceof LZMA2Options) {

return (LZMA2Options) opts;

}

final LZMA2Options options = new LZMA2Options();

options.setDictSize(numberOptionOrDefault(opts));

return options;

}


   Like      Feedback      org.tukaani.xz.LZMA2Options


 Sample 759. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream

    public void readOfLength0ShouldReturn0() throws Exception {

final byte[] rawData = new byte[1048576];

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

rawData[i] = (byte) Math.floor(Math.random()*256);

}



final ByteArrayOutputStream baos = new ByteArrayOutputStream();

final BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos);

bzipOut.write(rawData);

bzipOut.flush();

bzipOut.close();

baos.flush();

baos.close();



final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

final BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais);

final byte[] buffer = new byte[1024];

Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));

Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0));

Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));

bzipIn.close();

}


   Like      Feedback      org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 760. Code Sample / Example / Snippet of org.apache.commons.compress.utils.CountingOutputStream

    public void output() throws Exception {

final ByteArrayOutputStream bos = new ByteArrayOutputStream();

final CountingOutputStream o = new CountingOutputStream(bos);

o.write(1);

assertEquals(1, o.getBytesWritten());

o.write(new byte[] { 2, 3 });

assertEquals(3, o.getBytesWritten());

o.write(new byte[] { 2, 3, 4, 5, }, 2, 1);

assertEquals(4, o.getBytesWritten());

o.count(-1);

assertEquals(4, o.getBytesWritten());

o.count(-2);

assertEquals(2, o.getBytesWritten());

o.close();

assertArrayEquals(new byte[] { 1, 2, 3, 4 }, bos.toByteArray());

}


   Like      Feedback      org.apache.commons.compress.utils.CountingOutputStream


 Sample 761. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.snappy.FramedSnappyCompressorInputStream

    public void testRemainingChunkTypes() throws Exception {

final FileInputStream isSz = new FileInputStream(getFile("mixed.txt.sz"));

final ByteArrayOutputStream out = new ByteArrayOutputStream();

try {

final FramedSnappyCompressorInputStream in = new FramedSnappyCompressorInputStream(isSz);

IOUtils.copy(in, out);

out.close();

} finally {

isSz.close();

}



assertArrayEquals(new byte[] { '1', '2', '3', '4',

'5', '6', '7', '8', '9',

'5', '6', '7', '8', '9',

'5', '6', '7', '8', '9',

'5', '6', '7', '8', '9',

'5', '6', '7', '8', '9', 10,

'1', '2', '3', '4',

'1', '2', '3', '4',

}, out.toByteArray());

}


   Like      Feedback      org.apache.commons.compress.compressors.snappy.FramedSnappyCompressorInputStream


 Sample 762. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.deflate.DeflateCompressorInputStream

    public void availableShouldReturnNonZero() throws IOException {

final File input = AbstractTestCase.getFile("bla.tar.deflatez");

final InputStream is = new FileInputStream(input);

try {

final DeflateCompressorInputStream in =

new DeflateCompressorInputStream(is);

Assert.assertTrue(in.available() > 0);

in.close();

} finally {

is.close();

}

}


   Like      Feedback      org.apache.commons.compress.compressors.deflate.DeflateCompressorInputStream


 Sample 763. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.deflate.DeflateCompressorOutputStream

    public void canReadASingleByteFlushAndFinish() throws IOException {

final ByteArrayOutputStream bos = new ByteArrayOutputStream();

final DeflateCompressorOutputStream cos = new DeflateCompressorOutputStream(bos);

cos.write(99);

cos.flush();

cos.finish();

Assert.assertTrue(bos.toByteArray().length > 0);

cos.close();

}


   Like      Feedback      org.apache.commons.compress.compressors.deflate.DeflateCompressorOutputStream


 Sample 764. GunZip file using Apache Commons


   public void testGzipCreation() throws Exception {
final File input = getFile("test1.xml");
final File output = new File(dir, "test1.xml.gz");
final OutputStream out = new FileOutputStream(output);
try {
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("gz", out);
try {
IOUtils.copy(new FileInputStream(input), cos);
} finally {
cos.close();
}
} finally {
out.close();
}
}

   Like      Feedback     Zip file using Apache Commons   Compress file using Apache Commons   GunZip file using Apache Commons  Code Sample / Example / Snippet of org.apache.commons.compress.compressors.CompressorOutputStream  IOUtils.copy


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 765. Usage of Static Block and Instance Initialization Block

public class BuggyBread { 

   static {
      System.out.println("Static Block");
   }

   {
      System.out.println("Instance Initialization Block");
   }

   BuggyBread(){
      System.out.println("Constructor");
   }

   public static void main(String[] args){
      System.out.println("Main Method");
      new BuggyBread();
   }
}

   Like      Feedback     static block   Instance Initialization Block


 Sample 766. Usage of Builder Class / Builder Pattern

public class BuggyBread {

   private String element1; // Make them private as it supports stronger encapsulation

   private String element2;

   private BuggyBread(String element1, String element2){ // Make it private so that it can only be used by Builder
      this.element1 = element1;
      this.element2 = element2;
   }

   public static class Builder {
      // Create Builder as nested class as its only supposed to Build BuggyBread objects,
      // Make it public so that it can be accessed from outside
      private String element1; // Make them private as it supports stronger encapsulation

      private String element2;

      Builder(){}; // We have to define this constructor if we need overloaded constructor too and need to initialize without arguments too

      Builder(BuggyBread buggybread){ // overloaded constructor to make things easy
         element1 = buggybread.element1;
         element2 = buggybread.element2;
      }

      Builder withElement1(String element1){ // Builder method to either populate elements or override ( if populated through overloaded constructor )
         this.element1 = element1;
         return this;
      }

      Builder withElement2(String element2){
         this.element2 = element2;
         return this;
      }

      BuggyBread build(){ // method to build BuggyBread object using final contents from Builder
         BuggyBread buggybread = new BuggyBread(element1,element2);
         return buggybread;
      }
   }
}

   Like      Feedback     builder pattern  builder class


 Sample 767. Using Javascript SessionStorage

//save a value
sessionStorage.setItem("name", "Nicholas");

//retrieve item
var name = sessionStorage.getItem("name");

//get the key name for the first item
var key = sessionStorage.key(0);

//remove the key
sessionStorage.removeItem(key);

//check how many key-value pairs are present
var count = sessionStorage.length;

Here is the example in which we are checking that if there are values in the Session Storage , first load the arrays with those values.

if (sessionStorage.length != 0){
for(i=0;i<=90;i++){
if(sessionStorage.getItem(i) != null) {
array.push(i);
}
}

   Like      Feedback     SessionStorage  javascript


 Sample 768. Display Elements of a List

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

System.out.println(myList); // Prints [A, B, C]

   Like      Feedback     Print elements of a list


 Sample 769. Display elements of a List using For loop

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

for(String str:myList){ // prints A B C
   System.out.println(str);
}

   Like      Feedback     Print elements of a list   for loop   arraylist  list  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 770. Display elements of a List using For Loop and index

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

for(int index=0;index < myList.size(); index++){
   System.out.println(myList.get(index));
}

   Like      Feedback     Print elements of a list   arraylist  list  collections   for loop


 Sample 771. Maven - Add Dependency in Pom File

<dependencies>
<dependency>
<groupId></groupId>
<artifactId></artifactId>
</dependency>
</dependencies>

   Like      Feedback     maven  pom


 Sample 772. Maven - Add Dependency and excluding transitive dependency

<dependencies>
<dependency>
<groupId></groupId>
<artifactId></artifactId>
<exclusions>
<exclusion>
<groupId></groupId>
<artifactId></artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

   Like      Feedback     maven  pom  excluding transitive depedency


 Sample 773. Maven Pom File Template

<project>
<parent>
<groupId></groupId>
<artifactId></artifactId>
<version></version>
</parent>

<modelVersion></modelVersion>

<artifactId></artifactId>
<packaging></packaging>

<name></name>
<url></url>

<properties>
</properties>

<dependencies>
<dependency>
<groupId></groupId>
<artifactId></artifactId>
</dependency>
</dependencies>
<build>
<resources>
<resource>
   <directory></directory>
   <filtering></filtering>
</resource>
</resources>
<plugins>
<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
   <artifactId>maven-assembly-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

   Like      Feedback     maven  pom file  sample pom file


 Sample 774. Maven - SCM ( Source Code Management ) config in POM file

<scm>
<connection></connection>
<developerConnection></developerConnection>
<url></url>
</scm>

   Like      Feedback     maven  pom file  maven scm configuration


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 775. Rename a File

public static void main(String[] args) {
File oldFileName = new File("D:/oldFile.txt");
File newFileName = new File("D:/newFile.txt");
oldFileName.renameTo(newFileName);
}

   Like      Feedback     file io  input output  rename a file  renaming file


 Sample 776. Write CSV values to a file using au.com.bytecode.opencsv.CSVWriter

String[] stringArray1 = new String[5];
String[] stringArray2 = new String[5];
String[] stringArray3 = new String[5];

List listOfStringArrays = new ArrayList();
listOfStringArrays.add(stringArray1);
listOfStringArrays.add(stringArray2);
listOfStringArrays.add(stringArray3);

File file = new File("BuggyBread.txt");
CSVWriter csvWriter = null;
try {
   csvWriter = new CSVWriter(new FileWriter(file),CSVWriter.DEFAULT_SEPARATOR);
} catch (Exception ex){
}
csvWriter.writeAll(listOfStringArrays);

   Like      Feedback     array of Strings  csv writer


 Sample 777. Write a program / method to print first letter of words in a string.

public void printFirstLetterOfWords(String str){
   String[] splittedStringArray = str.split(" ");
   for(String word:splittedStringArray){
      System.out.println(word.charAt(0));
   }
}

   Like      Feedback     Code  Coding  String


 Sample 778. Rolling File Appender for Log4j


                 ignoreExceptions="false">
      
   %d %p %c - %m %n
      

      

   Like      Feedback     log4j  log4j appender  log4j rolling file appender


 Sample 779. Hibernate - Mapping the Id to RowId of Table ( workaround for Table having no primary key )

@Id
@Column(name="ROWID")
private String id;

   Like      Feedback     Hibernate  workaround for Table having no primary key  mapping Id to RowId


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 780. Usage of com.google.common.base.Preconditions.checkNotNull

Preconditions.checkNotNull(objectRef, "object reference holds null at this point");

   Like      Feedback     Google Guava  Preconditions


 Sample 781. Usage of com.google.common.base.Preconditions.checkArgument

Preconditions.checkArgument(argument >= 0, "argument should be a positive number");

   Like      Feedback     Google Guava  Preconditions


 Sample 782. Sample Log4j config with Rolling File Appender within Time Based Triggering Policy

<Configuration status="DEBUG">
<Appenders>
<RollingFile name="File" fileName="logs/xyz.log" filePattern="logs/xyz-%d{MM-dd-yyyy}.log.gz">
      <TimeBasedTriggeringPolicy />
   </RollingFile>
</Appenders>
<Loggers>
<Root level="DEBUG">
<AppenderRef ref="File" />
</Root>
</Loggers>
</Configuration>

   Like      Feedback     log4j  rolling logs with log4j  TimeBasedTriggeringPolicy


 Sample 783. Sample Log4j config with RollingRandomAccessFile appender and TimeBasedTriggeringPolicy

<Configuration status="INFO">
<Appenders>
<RollingRandomAccessFile name="File" fileName="logs/xyz.log" immediateFlush="true" filePattern="logs/xyz-%d{MM-dd-yyyy}.log.gz">
      <TimeBasedTriggeringPolicy />
   </RollingRandomAccessFile>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="File" />
</Root>
</Loggers>
</Configuration>

   Like      Feedback     log4j  rolling logs with log4j  TimeBasedTriggeringPolicy  RollingRandomAccessFile


 Sample 784. Sample Log4j config file with RollingRandomAccessFile appender ( Rolling Logs ) and SizeBasedTriggeringPolicy

<Configuration status="INFO">
<Appenders>
<RollingRandomAccessFile name="File" fileName="logs/xyz.log" immediateFlush="true" filePattern="logs/xyz-%d{MM-dd-yyyy}.log.gz">
      <SizeBasedTriggeringPolicy size="250 MB"/>
   </RollingRandomAccessFile>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="File" />
</Root>
</Loggers>
</Configuration>

   Like      Feedback     log4j  SizeBasedTriggeringPolicy  RollingRandomAccessFile


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 785. BigDecimal multiple method implementation

public BigDecimal multiply(BigDecimal multiplicand) {
int productScale = checkScale((long) scale + multiplicand.scale);
if (this.intCompact != INFLATED) {
if ((multiplicand.intCompact != INFLATED)) {
return multiply(this.intCompact, multiplicand.intCompact, productScale);
} else {
return multiply(this.intCompact, multiplicand.intVal, productScale);
}
} else {
if ((multiplicand.intCompact != INFLATED)) {
return multiply(multiplicand.intCompact, this.intVal, productScale);
} else {
return multiply(this.intVal, multiplicand.intVal, productScale);
}
}
}

   Like      Feedback     BigDecimal


 Sample 786. Usage of

import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.web.multipart.MultipartResolver;

@EnableWebMvc
@Configuration
public class Application extends WebMvcConfigurerAdapter {
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(500000);
return multipartResolver;
}
}

   Like      Feedback     Usage of MultipartResolver  multipartResolver.setMaxUploadSize(500000)  Setting max file size using Spring multipartResolver


 Sample 787. Usage of java.util.stream.Stream

List<Integer> list1 = Arrays.asList(1, 2);
List<Integer> list2 = Arrays.asList(4, 5);

Stream.of(list1, list1)
.flatMap(list -> list.stream())
.forEach(System.out::println);

   Like      Feedback     Stream.flatMap  System.out::println


 Sample 788. Usage of Java 8 Consumer interface

Consumer<String> consumer = s->{
   System.out.println(s);
};

consumer.accept("BuggyBread"); // prints BuggyBread

   Like      Feedback     Java 8 Consumer  Consumer interface


 Sample 789. Get only sub directories in a directory using FileFilter

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

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

   Like      Feedback     FileFilter


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 790. Usage of java.util.function.BiPredicate

BiPredicate<String, String> predicate = (s1, s2) -> (s1.equals(s2));

System.out.println(predicate.test("BUGGY", "BREAD"));

   Like      Feedback     BiPredicate  Java 8 BiPredicate


 Sample 791. Usage of

com.amazonaws.services.kinesis.AmazonKinesisClient
com.amazonaws.services.kinesis.model.PutRecordsRequest
com.amazonaws.services.kinesis.model.PutRecordsRequestEntry
com.amazonaws.services.kinesis.model.PutRecordsResult

PutRecordsRequestEntry entry = new PutRecordsRequestEntry();
entry.setPartitionKey(KEY);
entry.setData(VALUE.getBytes());

List<PutRecordsRequestEntry> entries = new ArrayList<PutRecordsRequestEntry>();
entries.add(entry);

PutRecordsRequest putRecordsRequest = new PutRecordsRequest();
putRecordsRequest.setStreamName(KINESIS-STREAM-NAME);
putRecordsRequest.setRecords(entries);

PutRecordsResult putRecordsResult = client.putRecords(putRecordsRequest);

   Like      Feedback     amazon kinesis   amazon aws   sending record to kinesis


 Sample 792. Write a Program to swap 2 variables ( using 3rd variable )

int x = 1;
int y = 2;
int z = x;
x = y;
y = z;

System.out.println("x="+x);
System.out.println("y="+y);

   Like      Feedback     swap 2 variables  code  coding


 Sample 793. Write a Program to swap two variables ( without using 3rd variable )


int x = 1;
int y = 2;

x = x+y;
y = x-y;
x = x-y;

System.out.println("x="+x);
System.out.println("y="+y);

   Like      Feedback     swap 2 variables


 Sample 794. Write a Program for selection sort.

public class SelectionSort {
   public static void main(String[] args){
      int a[] = {1,3,4,5,7,8,2,6};
      
      for(int i=0;i<a.length;i++){
         for(int j=0;j<i;j++){
            if(a[j] > a[j]){
               int temporary = a[j];
               a[j] = a[i];
               a[i] = temporary;
            }
         }
      }
      
      for(int i=0;i<a.length;i++){
         System.out.println(a[i]);
      }
   }
}

   Like      Feedback     sorting algorithm  selection sort


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 795. Write a program for bubble sort.

public class BubbleSort {
   public static void main(String[] args){
      int a[] = {1,3,4,5,7,8,2,6};
      
      for(int i=0;i<a.length-1;i++){
         for(int j=i;j<a.length;j++){
            if(a[j] < a[j]){
               int temporary = a[j];
               a[j] = a[i];
               a[i] = temporary;
            }
         }
      }
      
      for(int i=0;i<a.length;i++){
         System.out.println(a[i]);
      }
   }
}

   Like      Feedback     sorting algorithm  Bubble sort


 Sample 796. Print duplicate characters in a string / char array without using library

public class CountDuplicates {
   public static void main(String[] args){
      char[] alreadyOccured = new char[10];
      
      char[] charArray = {'b','u','g','g','y','b','r','e','a','d'};
      
      for(int countArray=0;countArray<charArray.length;countArray++){
         boolean charAlreadyOccured = false;
         for(int countAlreadyOccured=0;countAlreadyOccured<alreadyOccured.length;countAlreadyOccured++){
            if(charArray[countArray] == alreadyOccured[countAlreadyOccured]){
               charAlreadyOccured = true;
               break;
            }
         }
         if(charAlreadyOccured){
            System.out.println(charArray[countArray]);
         } else {
            alreadyOccured[countArray] = charArray[countArray];
         }
      }
   }
}

   Like      Feedback     string  char array


 Sample 797. Write a Program to replace characters in a String ( without using String replace method )

public class ReplaceCharacters{
   public static void main(String[] args){
      String str = "Hello BuggyBread";
      
      char[] charArray = str.toCharArray();
      int countCharacter = str.length();
      for(int count=0;count<countCharacter;count++){
         if(charArray[count] == 'g'){
            charArray[count] = 'd';
         }
      }
      String replacedString = new String(charArray).toString();
      
      System.out.println(replacedString);
   }
}

   Like      Feedback     string  replace characters in a string


 Sample 798. Write a Program to show Java thread usage by extending Thread class

public class MyClass {
   static class MyThreadClass extends Thread{

      @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  Thread class


 Sample 799. Write a Program to find two maximum numbers in an array

public class FindTwoMax {
public static void main(String[] args) {
int myArray[] = { 1, 3, 5, 8, 6, 3 };
int max1 = myArray[0];
int max2 = 0;
for (int count = 0; count < myArray.length; count++) {
if (max2 < myArray[count]) {
max2 = max1;
max1 = myArray[count];
} else if (max2 < myArray[count]) {
max2 = myArray[count];
}
}
System.out.println(max1);
System.out.println(max2);
}
}

   Like      Feedback     find 2 max in array


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 800. Write a Program to read a file and then count number of words

public class CountwordsinFile {
public static void main(String[] args) throws IOException{
String line = null;

File file = new File("C:Hello.txt");
FileReader fileReader = new FileReader(file);

BufferedReader bufferedReader = new BufferedReader(fileReader);

int countWords = 0;

do {

line = bufferedReader.readLine();
countWords += line.split(" ").length;

} while(line != null);
}
}

   Like      Feedback     file handling  count number of words  code  coding  file handling


 Sample 801. Write a Program to right shift single character in a string

public class RightShiftCharacter {
   public static void main(String args[]) {
      String str = "Hello";
      
      char[] charArray = str.toCharArray();
      
      for(int count=charArray.length-1;count>0;count--){
         charArray[count] = charArray[count-1];
      }
      
      String newString = new StringBuilder().append(charArray).toString();
      
      System.out.println(newString);      
   }
}

   Like      Feedback     string manipulation.right shift character


 Sample 802. Given a list of File objects, sort them by their name

public List sortFiles(List<File> files) {
files.sort(new Comparator<File>() {
@Override
public int compare(File file1, File file2) {
return file1.getName().compareTo(file2.getName());
}
});

return files.
}

   Like      Feedback     file


 Sample 803. Wait till Page loads in selenium / Web Driver

public void waitTillPageLoads() {

ExpectedCondition < Boolean > expectedCondition = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete");
try {
WebDriverWait wait = new WebDriverWait(driver, 90);
wait.until(expectedCondition);
driver.quit();
} catch (Exception exception) {

}
}

   Like      Feedback     selenum  webdriver


 Sample 804. AWS Kinesis Consumer

import com.amazonaws.kinesis.deagg.RecordDeaggregator;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.KinesisEvent;

public class KinesisConsumer implements RequestHandler<KinesisEvent, Void> {
   
   public Void handleRequest(KinesisEvent event, Context context) {
      System.out.println("Received " + event.getRecords().size() + " Event Records.");
      
      RecordDeaggregator.stream(event.getRecords().stream(), userRecord -> {
         String message = new String(userRecord.getData().array());
         System.out.println(message);
      });

      return null;
   }
}

   Like      Feedback     AWS Kinesis Consumer


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 805. Google Recommendation Engine Api Call for Logging Events

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;

public class GoogleRecommendationEngineApi {
      
   public void callGoogleApi(String json){

String userEventApiPostUrl =
       "https://recommendationengine.googleapis.com/v1eap/product/catalogs/<CATALOG_NAME>/events:write?key=<API_KEY>";

try {      
       HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
       requestFactory = httpTransport.createRequestFactory();

       HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(userEventApiPostUrl),
               ByteArrayContent.fromString("application/json", json));
            
       HttpResponse response = request.execute();
      
       System.out.println("Status: " + response.getStatusCode());
      
} catch (Exception e) {
         e.printStackTrace();
      }
   }
}

   Like      Feedback     Google Recommendation Engine. Google Recommendation Engine Logging Event


 Sample 806. Code to get Module name for the class

Module module = Test.class.getModule();
System.out.println(module.getName());

   Like      Feedback     java 9  java 9 module


 Sample 807. Code to get all packages of a Module

public class Test {
   public static void main(String[] args) {
      Module module = Test.class.getModule();
      System.out.println(module.getPackages());
   }   
}

   Like      Feedback     java 9  java 9 module


 Sample 808. Code to get Module name for List class

Module module = java.util.List.class.getModule();
System.out.println(module.getName()); // prints java.base

   Like      Feedback     java 9  java 9 module


 Sample 809. Code to print all packages of a module

Module module = java.util.List.class.getModule();
System.out.println(module.getPackages());

   Like      Feedback     java 9  java 9 modules


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 810. Code to get exports of a particular Module

Module module = java.util.List.class.getModule();
ModuleDescriptor moduleDescriptor = module.getDescriptor();
System.out.println(moduleDescriptor.exports());

   Like      Feedback     java 9  java 9 modules  get exports for a module


 Sample 811. Code to get ModuleDescriptor from a particular Module

Module module = java.util.List.class.getModule();
ModuleDescriptor moduleDescriptor = module.getDescriptor();

   Like      Feedback     java 9  java 9 modules  get ModuleDescriptor for a module


 Sample 812. Code to get main class in a particular module

Module module = java.util.List.class.getModule();
ModuleDescriptor moduleDescriptor = module.getDescriptor();
System.out.println(moduleDescriptor.mainClass());

   Like      Feedback     java 9  java 9 modules  get main class for a module  get main class for a module in java 9  java module


 Sample 813. Usage of JavaBean Annotation

@JavaBean(description = "",defaultProperty="",defaultEventSet="")
public class Test {
}

   Like      Feedback     JavaBean Annotation  java 9


 Sample 814. Initializing a list using factory method in java 9

Usage of List.of()

List<String> countryList = List.of("France","Belgium","Germany");

   Like      Feedback     java 9


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 815. Initializing a map using factory method in java 9

Usage of Map.of()

Map<String,String> countryCodeMap = Map.of("France","FR","United States","US","Canada","CA");

   Like      Feedback     java 9


 Sample 816. Code Sample for

jdk.jshell.JShell;
jdk.jshell.MethodSnippet;
jdk.jshell.Snippet;

JShell.Builder builder =
    JShell.builder()
    .in(System.in)
    .out(System.out)
    .err(System.out);
      
JShell jshell = builder.build();
      
System.out.println(jshell.snippets()
.filter(sn -> sn.kind() == Snippet.Kind.METHOD)
.map(sn -> (MethodSnippet) sn).findFirst().get().signature());

   Like      Feedback     java 9  java 9 Jshell  Jshell


 Sample 817. Averaging Group By using Java 8

<Collection_Reference>.stream().collect(Collectors.groupingBy(<Class_Name>::<Method_to_get_group_by_element>,
               Collectors.averagingDouble(<Class_Name>::<Method_to_get_element_to_perform_averaging_on>)));

Example -

Get Dept and it's average Salary

list..stream().collect(Collectors.groupingBy(Employee::getDept,
               Collectors.averagingDouble(Employee::getSalary)));

   Like      Feedback     java 8


 Sample 818. Using kohsuke for command line options

Add the following dependency

<dependency>
      <groupId>org.kohsuke.args4j</groupId>
      <artifactId>args4j-maven-plugin</artifactId>
      <version>2.33</version>
</dependency>

In the main class add the following element

@Option(name = "-date", required = true, metaVar = "mmddyyyy", usage = "date for which we want this to happen")
private String date = null;

Within the main method add code to parse command line args and populate date

public static void main(String args[]){
try {
    parser.parseArgument(args);
    SimpleDateFormat commandLineDateFormat = new SimpleDateFormat("mmddyyyy", Locale.getDefault());
Date date = commandLineDateFormat.parse(date);

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

   Like      Feedback     org.kohsuke.args4j.CmdLineParser  org.kohsuke.args4j.Option   kohsuke  command line options


 Sample 819. Custom Date Range for Google Adwords Report

// Create a Report Definition

ReportDefinition reportDefinition = new ReportDefinition();

// Set the Repo Date Range type as Custom Date

reportDefinition.setDateRangeType(ReportDefinitionDateRangeType.CUSTOM_DATE);

// Create. a date format as Google want date as string a specific format

SimpleDateFormat dateFormat = new SimpleDateFormat("YYYYMMDD", Locale.getDefault());
      
// Create selector

Selector selector = new Selector();

// Add fields to selector

selector.getFields()
            .addAll(Arrays.asList("Id", "CampaignName");

// Set Min and Max date to the selector
      
selector.getDateRange().setMin(dateFormat.format(startDate));
selector.getDateRange().setMax(dateFormat.format(endDate));

// Add selector to Report Definition

reportDefinition.setSelector(selector);

   Like      Feedback     Adwords Reports  Google Adwords  Adwords  Custom Date Range for Google Adwords report  Custom Date Range for Adwords  ReportDefinitionDateRangeType.CUSTOM_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 820. Ngrx Reducer method , State interface and Initial state variable

export interface IAppState{
myNumber: number;
}

export const INITIAL_STATE: IAppState = {
myNumber: 0
}

export function reducer(state,action){

if(action.type == INCREMENT){

let num:number[] = state.myNumber;
let num1:number = num.length + 1;

return Object.assign({},...state,{
myNumber: state.myNumber + 1
})
} else {
return state;
}
}

   Like      Feedback     Ngrx


 Sample 821. Angular component to display continuously changing time

export class myComponent implements OnInit {

currentTime:string;

constructor() { }

ngOnInit() {
setInterval(() => {
this.currentTime = new Date().toTimeString();
}, 100);
}
}

   Like      Feedback     angular



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