Share

Search Java Code Snippets


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





#Java - Code Snippets for '#Era' - 44 code snippet(s) found

 Sample 1. 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  stringbuffer.append  java.lang.String  java.lang.StringBuffer  String Manipulation


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

// Populate a List using Set elements.

// Declare and Initialize the Collection

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

// Add Elements

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

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

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

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

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

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


 Sample 3. 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 4. 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 5. 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 6. 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 7. 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 8. 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 9. 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 10. 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 11. 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 12. Usage of Iterator

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

   Like      Feedback     collections  Iterator


 Sample 13. Get all Permutations of List Elements using Apache Commons PermutationIterator

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

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

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


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


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 15. Find 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 16. Generate Random Number till 100

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

   Like      Feedback     Random Number Generation  Random


 Sample 17. 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 18. 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 19. 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 20. 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 21. Code Sample / Example / Snippet of org.apache.spark.mllib.clustering.PowerIterationClusteringModel

  public static void main(String[] args) {

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

JavaSparkContext sc = new JavaSparkContext(sparkConf);



@SuppressWarnings("unchecked")

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

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

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

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

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

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



PowerIterationClustering pic = new PowerIterationClustering()

.setK(2)

.setMaxIterations(10);

PowerIterationClusteringModel model = pic.run(similarities);



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

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

}



sc.stop();

}


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


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


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


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


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


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


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. 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 36. 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 37. 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 38. 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 39. 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


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. 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 42. 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 43. 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 44. 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



comments powered by Disqus