#Java - Code Snippets for '#For' - 51 code snippet(s) found |
|
Sample 1. 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 2. 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 3. 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 4. 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 5. 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 |
|
|
Sample 6. 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 7. 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 8. 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 9. 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 10. 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 11. Get 6 days before today as per HijrahChronology | |
|
AbstractChronology abstractChrono = HijrahChronology.INSTANCE;
System.out.println(abstractChrono.dateNow().minus(6, ChronoUnit.DAYS));
|
|
Like Feedback AbstractChronology HijrahChronology ChronoUnit.DAYS ChronoUnit |
|
|
Sample 12. 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 13. 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 14. 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 15. 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 16. 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 17. Initialize Date using SimpleDateFormat and parsing string | |
|
Date endDate = new SimpleDateFormat("yyyyMMdd").parse("20160426");
|
|
Like Feedback SimpleDateFormat Date SimpleDateFormat.parse java.text.SimpleDateFormat |
|
|
Sample 18. Method to get specific format files from a directory | |
|
private Collection<File> getDocAndTextFiles() {
File directory = new File("C:DocDir");
if (directory.exists() && directory.isDirectory()) {
Collection<File> files = FileUtils.listFiles(directory, new String[] { "doc","txt" }, false);
}
return files;
}
|
|
Like Feedback file handling file directory FileUtils.listFiles fileutils |
|
|
Sample 19. 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 20. 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 21. 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 22. 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 23. Use java.time.format.DateTimeFormatter to Parse date in the format YYYYMMDD+HHmmss | |
|
DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendValue(YEAR, 4)
.appendValue(MONTH_OF_YEAR, 2)
.appendValue(DAY_OF_MONTH, 2)
.appendOffset("+HHMMss", "Z")
.toFormatter();
TemporalAccessor temporal = null;
try {
temporal = dateTimeFormatter.parse("2016101+235700");
System.out.println(temporal.toString()); // prints {OffsetSeconds=86220},ISO resolved to 2016-01-01
} catch (DateTimeParseException ex){
System.out.println("Error parsing date");
}
|
|
Like Feedback DateTimeFormatter Parse Date in Java 8 Parse date using DateTimeFormatter and DateTimeFormatterBuilder |
|
|
Sample 24. 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 25. 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 26. 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 27. 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 28. 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 29. 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 30. 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 31. 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 32. 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 33. 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 34. 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 35. 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 36. 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 37. 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 |
|
|
Sample 38. 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 39. Rolling File Appender for Log4j | |
|
ignoreExceptions="false">
%d %p %c - %m %n
|
|
Like Feedback log4j log4j appender log4j rolling file appender |
|
|
|
Sample 40. 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 |
|
|
Sample 41. 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 |
|
|
Sample 42. 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 43. 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 44. 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 45. 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 46. 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 47. 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 48. 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 49. 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 50. 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 51. 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 |
|
|