Merge remote-tracking branch 'upstream/master'

Conflicts:
	libraries/pom.xml
This commit is contained in:
parthkaria
2017-09-27 14:42:30 +05:30
652 changed files with 21671 additions and 1550 deletions
@@ -0,0 +1,43 @@
package com.baeldung.commons.io;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import java.io.File;
public class FileMonitor {
public static void main(String[] args) throws Exception {
File folder = FileUtils.getTempDirectory();
startFileMonitor(folder);
}
/**
* @param folder
* @throws Exception
*/
public static void startFileMonitor(File folder) throws Exception {
FileAlterationObserver observer = new FileAlterationObserver(folder);
FileAlterationMonitor monitor = new FileAlterationMonitor(5000);
FileAlterationListener fal = new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
// on create action
}
@Override
public void onFileDelete(File file) {
// on delete action
}
};
observer.addListener(fal);
monitor.addObserver(observer);
monitor.start();
}
}
@@ -0,0 +1,11 @@
package com.baeldung.commons.lang3;
import org.apache.commons.lang3.concurrent.LazyInitializer;
public class SampleLazyInitializer extends LazyInitializer<SampleObject> {
@Override
protected SampleObject initialize() {
return new SampleObject();
}
}
@@ -0,0 +1,7 @@
package com.baeldung.commons.lang3;
public class SampleObject {
//Ignored
}
@@ -0,0 +1,47 @@
package com.baeldung.fj;
import fj.F;
import fj.F1Functions;
import fj.Unit;
import fj.data.IO;
import fj.data.IOFunctions;
public class FunctionalJavaIOMain {
public static IO<Unit> printLetters(final String s) {
return () -> {
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
return Unit.unit();
};
}
public static void main(String[] args) {
F<String, IO<Unit>> printLetters = i -> printLetters(i);
IO<Unit> lowerCase = IOFunctions
.stdoutPrintln("What's your first Name ?");
IO<Unit> input = IOFunctions.stdoutPrint("First Name: ");
IO<Unit> userInput = IOFunctions.append(lowerCase, input);
IO<String> readInput = IOFunctions.stdinReadLine();
F<String, String> toUpperCase = i -> i.toUpperCase();
F<String, IO<Unit>> transformInput = F1Functions
.<String, IO<Unit>, String> o(printLetters).f(toUpperCase);
IO<Unit> readAndPrintResult = IOFunctions.bind(readInput,
transformInput);
IO<Unit> program = IOFunctions.bind(userInput,
nothing -> readAndPrintResult);
IOFunctions.toSafe(program).run();
}
}
@@ -0,0 +1,48 @@
package com.baeldung.fj;
import fj.F;
import fj.Show;
import fj.data.Array;
import fj.data.List;
import fj.data.Option;
import fj.function.Characters;
import fj.function.Integers;
public class FunctionalJavaMain {
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
public static void main(String[] args) {
List<Integer> fList = List.list(3, 4, 5, 6);
List<Boolean> evenList = fList.map(isEven);
Show.listShow(Show.booleanShow).println(evenList);
fList = fList.map(i -> i + 1);
Show.listShow(Show.intShow).println(fList);
Array<Integer> a = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
Array<Integer> b = a.filter(Integers.even);
Show.arrayShow(Show.intShow).println(b);
Array<String> array = Array.array("Welcome", "To", "baeldung");
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
System.out.println(isExist);
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sum = intArray.foldLeft(Integers.add, 0);
System.out.println(sum);
Option<Integer> n1 = Option.some(1);
Option<Integer> n2 = Option.some(2);
F<Integer, Option<Integer>> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
Option<Integer> result1 = n1.bind(f1);
Option<Integer> result2 = n2.bind(f1);
Show.optionShow(Show.intShow).println(result1);
Show.optionShow(Show.intShow).println(result2);
}
}
@@ -1,187 +0,0 @@
package com.baeldung.geotools;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
public class ShapeFile {
private static final String FILE_NAME = "shapefile.shp";
public static void main(String[] args) throws Exception {
DefaultFeatureCollection collection = new DefaultFeatureCollection();
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
SimpleFeatureType TYPE = DataUtilities.createType("Location", "location:Point:srid=4326," + "name:String");
SimpleFeatureType CITY = createFeatureType();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY);
addLocations(featureBuilder, collection);
File shapeFile = getNewShapeFile();
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<String, Serializable>();
params.put("url", shapeFile.toURI()
.toURL());
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
dataStore.createSchema(CITY);
// If you decide to use the TYPE type and create a Data Store with it,
// You will need to uncomment this line to set the Coordinate Reference System
// newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
Transaction transaction = new DefaultTransaction("create");
String typeName = dataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
featureStore.setTransaction(transaction);
try {
featureStore.addFeatures(collection);
transaction.commit();
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
} finally {
transaction.close();
}
System.exit(0); // success!
} else {
System.out.println(typeName + " does not support read/write access");
System.exit(1);
}
}
public static SimpleFeatureType createFeatureType() {
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("Location");
builder.setCRS(DefaultGeographicCRS.WGS84);
builder.add("Location", Point.class);
builder.length(15)
.add("Name", String.class);
SimpleFeatureType CITY = builder.buildFeatureType();
return CITY;
}
public static void addLocations(SimpleFeatureBuilder featureBuilder, DefaultFeatureCollection collection) {
Map<String, List<Double>> locations = new HashMap<>();
double lat = 13.752222;
double lng = 100.493889;
String name = "Bangkok";
addToLocationMap(name, lat, lng, locations);
lat = 53.083333;
lng = -0.15;
name = "New York";
addToLocationMap(name, lat, lng, locations);
lat = -33.925278;
lng = 18.423889;
name = "Cape Town";
addToLocationMap(name, lat, lng, locations);
lat = -33.859972;
lng = 151.211111;
name = "Sydney";
addToLocationMap(name, lat, lng, locations);
lat = 45.420833;
lng = -75.69;
name = "Ottawa";
addToLocationMap(name, lat, lng, locations);
lat = 30.07708;
lng = 31.285909;
name = "Cairo";
addToLocationMap(name, lat, lng, locations);
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
for (Map.Entry<String, List<Double>> location : locations.entrySet()) {
Point point = geometryFactory.createPoint(new Coordinate(location.getValue()
.get(0),
location.getValue()
.get(1)));
featureBuilder.add(point);
featureBuilder.add(name);
SimpleFeature feature = featureBuilder.buildFeature(null);
collection.add(feature);
}
}
private static void addToLocationMap(String name, double lat, double lng, Map<String, List<Double>> locations) {
List<Double> coordinates = new ArrayList<>();
coordinates.add(lat);
coordinates.add(lng);
locations.put(name, coordinates);
}
private static File getNewShapeFile() {
String filePath = new File(".").getAbsolutePath() + FILE_NAME;
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save shapefile");
chooser.setSelectedFile(new File(filePath));
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
System.exit(0);
}
File shapeFile = chooser.getSelectedFile();
if (shapeFile.equals(filePath)) {
System.out.println("Error: cannot replace " + filePath);
System.exit(0);
}
return shapeFile;
}
}
@@ -0,0 +1,34 @@
package com.baeldung.jcache;
import java.io.Serializable;
import javax.cache.event.CacheEntryCreatedListener;
import javax.cache.event.CacheEntryEvent;
import javax.cache.event.CacheEntryListenerException;
import javax.cache.event.CacheEntryUpdatedListener;
public class SimpleCacheEntryListener implements CacheEntryCreatedListener<String, String>, CacheEntryUpdatedListener<String, String>, Serializable {
/**
*
*/
private static final long serialVersionUID = -712657810462878763L;
private boolean updated;
private boolean created;
public boolean getUpdated() {
return this.updated;
}
public boolean getCreated() {
return this.created;
}
public void onUpdated(Iterable<CacheEntryEvent<? extends String, ? extends String>> events) throws CacheEntryListenerException {
this.updated = true;
}
public void onCreated(Iterable<CacheEntryEvent<? extends String, ? extends String>> events) throws CacheEntryListenerException {
this.created = true;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.jcache;
import java.util.HashMap;
import java.util.Map;
import javax.cache.integration.CacheLoader;
import javax.cache.integration.CacheLoaderException;
public class SimpleCacheLoader implements CacheLoader<Integer, String> {
@Override
public String load(Integer key) throws CacheLoaderException {
return "fromCache" + key;
}
@Override
public Map<Integer, String> loadAll(Iterable<? extends Integer> keys) throws CacheLoaderException {
Map<Integer, String> data = new HashMap<>();
for (int key : keys) {
data.put(key, load(key));
}
return data;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.jcache;
import java.io.Serializable;
import javax.cache.processor.EntryProcessor;
import javax.cache.processor.EntryProcessorException;
import javax.cache.processor.MutableEntry;
public class SimpleEntryProcessor implements EntryProcessor<String, String, String>, Serializable {
/**
*
*/
private static final long serialVersionUID = -5616476363722945132L;
public String process(MutableEntry<String, String> entry, Object... args) throws EntryProcessorException {
if (entry.exists()) {
String current = entry.getValue();
entry.setValue(current + " - modified");
return current;
}
return null;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.jdeffered;
import org.jdeferred.Deferred;
import org.jdeferred.Promise;
import org.jdeferred.impl.DeferredObject;
class FilterDemo {
private static String modifiedMsg;
static String filter(String msg) {
Deferred<String, ?, ?> d = new DeferredObject<>();
Promise<String, ?, ?> p = d.promise();
Promise<String, ?, ?> filtered = p.then((result) -> {
modifiedMsg = "Hello " + result;
});
filtered.done(r -> System.out.println("filtering done"));
d.resolve(msg);
return modifiedMsg;
}
}
@@ -0,0 +1,35 @@
package com.baeldung.jdeffered;
import org.jdeferred.Deferred;
import org.jdeferred.DonePipe;
import org.jdeferred.Promise;
import org.jdeferred.impl.DeferredObject;
class PipeDemo {
public enum Result {
SUCCESS, FAILURE
};
private static Result status;
static Result validate(int num) {
Deferred<Integer, ?, ?> d = new DeferredObject<>();
Promise<Integer, ?, ?> p = d.promise();
p.then((DonePipe<Integer, Integer, Exception, Void>) result -> {
if (result < 90) {
return new DeferredObject<Integer, Exception, Void>()
.resolve(result);
} else {
return new DeferredObject<Integer, Exception, Void>()
.reject(new Exception("Unacceptable value"));
}
}).done(r -> status = Result.SUCCESS)
.fail(r -> status = Result.FAILURE);
d.resolve(num);
return status;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.jdeffered;
import org.jdeferred.Deferred;
import org.jdeferred.Promise;
import org.jdeferred.impl.DeferredObject;
class PromiseDemo {
static void startJob(String jobName) {
Deferred<String, String, String> deferred = new DeferredObject<>();
Promise<String, String, String> promise = deferred.promise();
promise.done(result -> System.out.println("Job done"))
.fail(rejection -> System.out.println("Job fail"))
.progress(progress -> System.out.println("Job is in progress"))
.always((state, result, rejection) -> System.out.println("Job execution started"));
deferred.resolve(jobName);
// deferred.notify("");
// deferred.reject("oops");
}
}
@@ -0,0 +1,38 @@
package com.baeldung.jdeffered;
import org.jdeferred.Deferred;
import org.jdeferred.DeferredManager;
import org.jdeferred.Promise;
import org.jdeferred.impl.DefaultDeferredManager;
import org.jdeferred.impl.DeferredObject;
public class ThreadSafeDemo {
public static void task() {
DeferredManager dm = new DefaultDeferredManager();
Deferred<String, String, String> deferred = new DeferredObject<>();
Promise<String, String, String> p1 = deferred.promise();
Promise<String, String, String> p = dm.when(p1)
.done(r -> System.out.println("done"))
.fail(r -> System.out.println("fail"));
synchronized (p) {
while (p.isPending()) {
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
try {
p.waitSafely();
} catch (InterruptedException e) {
e.printStackTrace();
}
deferred.resolve("Hello Baeldung");
}
}
@@ -0,0 +1,22 @@
package com.baeldung.jdeffered.manager;
import org.jdeferred.Deferred;
import org.jdeferred.DeferredManager;
import org.jdeferred.Promise;
import org.jdeferred.impl.DefaultDeferredManager;
import org.jdeferred.impl.DeferredObject;
class DeferredManagerDemo {
public static void initiate() {
Deferred<String, String, String> deferred = new DeferredObject<>();
DeferredManager dm = new DefaultDeferredManager();
Promise<String, String, String> p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise();
dm.when(p1, p2, p3).done((result) -> {
System.out.println("done");
}).fail((result) -> {
System.out.println("fail");
});
deferred.resolve("Hello Baeldung");
}
}
@@ -0,0 +1,24 @@
package com.baeldung.jdeffered.manager;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.jdeferred.Deferred;
import org.jdeferred.DeferredManager;
import org.jdeferred.Promise;
import org.jdeferred.impl.DefaultDeferredManager;
import org.jdeferred.impl.DeferredObject;
class DeferredManagerWithExecutorDemo {
public static void initiate() {
ExecutorService executor = Executors.newFixedThreadPool(10);
Deferred<String, String, String> deferred = new DeferredObject<>();
DeferredManager dm = new DefaultDeferredManager(executor);
Promise<String, String, String> p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise();
dm.when(p1, p2, p3)
.done(r -> System.out.println("done"))
.fail(r -> System.out.println("fail"));
deferred.resolve("done");
}
}
@@ -0,0 +1,14 @@
package com.baeldung.jdeffered.manager;
import org.jdeferred.DeferredManager;
import org.jdeferred.impl.DefaultDeferredManager;
class SimpleDeferredManagerDemo {
public static void initiate() {
DeferredManager dm = new DefaultDeferredManager();
dm.when(() -> 1)
.done(r -> System.out.println("done"))
.fail(Throwable::printStackTrace);
}
}
@@ -0,0 +1,57 @@
package com.baeldung.jira;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClientFactory;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class JiraClient {
private static final String USERNAME = "jira.user";
private static final String PASSWORD = "secret";
private static final String JIRA_URL = "http://jira.company.com";
public static void main(String[] args) {
final Issue issue = new JiraClient().getIssue("MYKEY-1234");
System.out.println(issue.getDescription());
}
private Issue getIssue(String issueKey) {
JiraRestClient restClient = getJiraRestClient();
Issue issue = restClient.getIssueClient().getIssue(issueKey).claim();
closeRestClient(restClient);
return issue;
}
private JiraRestClient getJiraRestClient() {
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI jiraServerUri = getJiraUri();
return factory
.createWithBasicHttpAuthentication(jiraServerUri, USERNAME, PASSWORD);
}
private URI getJiraUri() {
URI jiraServerUri = null;
try {
jiraServerUri = new URI(JIRA_URL);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return jiraServerUri;
}
private void closeRestClient(JiraRestClient restClient) {
try {
restClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,5 @@
package com.baeldung.mbassador;
public class AckMessage extends Message {
}
@@ -0,0 +1,5 @@
package com.baeldung.mbassador;
public class Message {
}
@@ -0,0 +1,15 @@
package com.baeldung.mbassador;
public class RejectMessage extends Message {
int code;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.measurement;
import javax.measure.Quantity;
import javax.measure.quantity.Volume;
public class WaterTank {
private Quantity<Volume> capacityMeasure;
private double capacityDouble;
public void setCapacityMeasure(Quantity<Volume> capacityMeasure) {
this.capacityMeasure = capacityMeasure;
}
public void setCapacityDouble(double capacityDouble) {
this.capacityDouble = capacityDouble;
}
public Quantity<Volume> getCapacityMeasure() {
return capacityMeasure;
}
public double getCapacityDouble() {
return capacityDouble;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.protonpack;
import java.util.Optional;
import java.util.stream.Stream;
import static com.codepoetics.protonpack.collectors.CollectorUtils.maxBy;
import static com.codepoetics.protonpack.collectors.CollectorUtils.minBy;
public class CollectorUtilsExample {
public void minMaxProjectionCollector() {
Stream<String> integerStream = Stream.of("a", "bb", "ccc", "1");
Optional<String> max = integerStream.collect(maxBy(String::length));
Optional<String> min = integerStream.collect(minBy(String::length));
}
}
@@ -0,0 +1,107 @@
package com.baeldung.protonpack;
import com.codepoetics.protonpack.Indexed;
import com.codepoetics.protonpack.StreamUtils;
import com.codepoetics.protonpack.selectors.Selectors;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class StreamUtilsExample {
public void createInfiniteIndex() {
LongStream indices = StreamUtils.indices();
}
public void zipAStreamWithIndex() {
Stream<String> source = Stream.of("Foo", "Bar", "Baz");
List<Indexed<String>> zipped = StreamUtils
.zipWithIndex(source)
.collect(Collectors.toList());
}
public void zipAPairOfStreams() {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("Apple", "Banana", "Carrot");
List<String> zipped = StreamUtils
.zip(streamA, streamB, (a, b) -> a + " is for " + b)
.collect(Collectors.toList());
}
public void zipThreeStreams() {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("aggravating", "banausic", "complaisant");
Stream<String> streamC = Stream.of("Apple", "Banana", "Carrot");
List<String> zipped = StreamUtils
.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c)
.collect(Collectors.toList());
}
public void mergeThreeStreams() {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("apple", "banana", "carrot", "date");
Stream<String> streamC = Stream.of("fritter", "split", "cake", "roll", "pastry");
Stream<List<String>> merged = StreamUtils.mergeToList(streamA, streamB, streamC);
}
public void interleavingStreamsUsingRoundRobin() {
Stream<String> streamA = Stream.of("Peter", "Paul", "Mary");
Stream<String> streamB = Stream.of("A", "B", "C", "D", "E");
Stream<String> streamC = Stream.of("foo", "bar", "baz", "xyzzy");
Stream<String> interleaved = StreamUtils.interleave(Selectors.roundRobin(), streamA, streamB, streamC);
}
public void takeWhileAndTakeUntilStream() {
Stream<Integer> infiniteInts = Stream.iterate(0, i -> i + 1);
Stream<Integer> finiteIntsWhileLessThan10 = StreamUtils.takeWhile(infiniteInts, i -> i < 10);
Stream<Integer> finiteIntsUntilGreaterThan10 = StreamUtils.takeUntil(infiniteInts, i -> i > 10);
}
public void skipWhileAndSkipUntilStream() {
Stream<Integer> ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> skippedWhileConditionMet = StreamUtils.skipWhile(ints, i -> i < 4);
Stream<Integer> skippedUntilConditionMet = StreamUtils.skipWhile(ints, i -> i > 4);
}
public void unfoldStream() {
Stream<Integer> unfolded = StreamUtils.unfold(1, i -> (i < 10) ? Optional.of(i + 1) : Optional.empty());
}
public void windowedStream() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
List<List<Integer>> windows = StreamUtils
.windowed(integerStream, 2)
.collect(toList());
List<List<Integer>> windowsWithSkipIndex = StreamUtils
.windowed(integerStream, 3, 2)
.collect(toList());
List<List<Integer>> windowsWithSkipIndexAndAllowLowerSize = StreamUtils
.windowed(integerStream, 2, 2, true)
.collect(toList());
}
public void groupRunsStreams() {
Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5);
List<List<Integer>> runs = StreamUtils
.groupRuns(integerStream)
.collect(toList());
}
public void aggreagateOnBiElementPredicate() {
Stream<String> stream = Stream.of("a1", "b1", "b2", "c1");
Stream<List<String>> aggregated = StreamUtils.aggregate(stream, (e1, e2) -> e1.charAt(0) == e2.charAt(0));
}
}
@@ -0,0 +1,33 @@
package com.baeldung.retrofit.basic;
import java.util.List;
import com.baeldung.retrofit.models.Contributor;
import com.baeldung.retrofit.models.Repository;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
public interface GitHubBasicApi {
/**
* List GitHub repositories of user
* @param user GitHub Account
* @return GitHub repositories
*/
@GET("users/{user}/repos")
Call<List<Repository>> listRepos(@Path("user") String user);
/**
* List Contributors of a GitHub Repository
* @param user GitHub Account
* @param repo GitHub Repository
* @return GitHub Repository Contributors
*/
@GET("repos/{user}/{repo}/contributors")
Call<List<Contributor>> listRepoContributors(
@Path("user") String user,
@Path("repo") String repo);
}
@@ -0,0 +1,14 @@
package com.baeldung.retrofit.basic;
import java.io.IOException;
import java.util.List;
public class GitHubBasicApp {
public static void main(String[] args) throws IOException {
String userName = "eugenp";
List<String> topContributors = new GitHubBasicService()
.getTopContributors(userName);
topContributors.forEach(System.out::println);
}
}
@@ -0,0 +1,60 @@
package com.baeldung.retrofit.basic;
import com.baeldung.retrofit.models.Contributor;
import com.baeldung.retrofit.models.Repository;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class GitHubBasicService {
private GitHubBasicApi gitHubApi;
GitHubBasicService() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
gitHubApi = retrofit.create(GitHubBasicApi.class);
}
List<String> getTopContributors(String userName) throws IOException {
List<Repository> repos = gitHubApi
.listRepos(userName)
.execute()
.body();
repos = repos != null ? repos : Collections.emptyList();
return repos.stream()
.flatMap(repo -> getContributors(userName, repo))
.sorted((a, b) -> b.getContributions() - a.getContributions())
.map(Contributor::getName)
.distinct()
.sorted()
.collect(Collectors.toList());
}
private Stream<Contributor> getContributors(String userName, Repository repo) {
List<Contributor> contributors = null;
try {
contributors = gitHubApi
.listRepoContributors(userName, repo.getName())
.execute()
.body();
} catch (IOException e) {
e.printStackTrace();
}
contributors = contributors != null ? contributors : Collections.emptyList();
return contributors.stream()
.filter(c -> c.getContributions() > 100);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.retrofit.models;
import com.google.gson.annotations.SerializedName;
public class Contributor {
@SerializedName("login")
private String name;
private Integer contributions;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getContributions() {
return contributions;
}
public void setContributions(Integer contributions) {
this.contributions = contributions;
}
@Override
public String toString() {
return "Contributer [name=" + name + ", contributions=" + contributions + "]";
}
}
@@ -0,0 +1,27 @@
package com.baeldung.retrofit.models;
public class Repository {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Repository [name=" + name + ", description=" + description + "]";
}
}
@@ -0,0 +1,33 @@
package com.baeldung.retrofit.rx;
import java.util.List;
import com.baeldung.retrofit.models.Contributor;
import com.baeldung.retrofit.models.Repository;
import retrofit2.http.GET;
import retrofit2.http.Path;
import rx.Observable;
public interface GitHubRxApi {
/**
* List GitHub repositories of user
* @param user GitHub Account
* @return GitHub repositories
*/
@GET("users/{user}/repos")
Observable<List<Repository>> listRepos(@Path("user") String user);
/**
* List Contributors of a GitHub Repository
* @param user GitHub Account
* @param repo GitHub Repository
* @return GitHub Repository Contributors
*/
@GET("repos/{user}/{repo}/contributors")
Observable<List<Contributor>> listRepoContributors(
@Path("user") String user,
@Path("repo") String repo);
}
@@ -0,0 +1,12 @@
package com.baeldung.retrofit.rx;
import java.io.IOException;
public class GitHubRxApp {
public static void main(String[] args) throws IOException {
String userName = "eugenp";
new GitHubRxService().getTopContributors(userName)
.subscribe(System.out::println);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.retrofit.rx;
import com.baeldung.retrofit.models.Contributor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
class GitHubRxService {
private GitHubRxApi gitHubApi;
GitHubRxService() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
gitHubApi = retrofit.create(GitHubRxApi.class);
}
Observable<String> getTopContributors(String userName) {
return gitHubApi.listRepos(userName)
.flatMapIterable(x -> x)
.flatMap(repo -> gitHubApi.listRepoContributors(userName, repo.getName()))
.flatMapIterable(x -> x)
.filter(c -> c.getContributions() > 100)
.sorted((a, b) -> b.getContributions() - a.getContributions())
.map(Contributor::getName)
.distinct();
}
}
@@ -0,0 +1,58 @@
package com.baeldung.retrofitguide;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class GitHubServiceGenerator {
private static final String BASE_URL = "https://api.github.com/";
private static Retrofit.Builder builder
= new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
private static OkHttpClient.Builder httpClient
= new OkHttpClient.Builder();
private static HttpLoggingInterceptor logging
= new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BASIC);
public static <S> S createService(Class<S> serviceClass) {
if (!httpClient.interceptors().contains(logging)) {
httpClient.addInterceptor(logging);
builder.client(httpClient.build());
retrofit = builder.build();
}
return retrofit.create(serviceClass);
}
public static <S> S createService(Class<S> serviceClass, final String token) {
if (token != null) {
httpClient.interceptors().clear();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder()
.header("Authorization", token);
Request request = builder.build();
return chain.proceed(request);
}
});
builder.client(httpClient.build());
retrofit = builder.build();
}
return retrofit.create(serviceClass);
}
}
@@ -0,0 +1,49 @@
package com.baeldung.retrofitguide;
import java.io.IOException;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Main {
public static void main(String[] args) {
//Manual creation
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
UserService service = retrofit.create(UserService.class);
//Using GitHubServiceGenerator
service = GitHubServiceGenerator.createService(UserService.class);
Call<User> callSync = service.getUser("eugenp");
Call<User> callAsync = service.getUser("eugenp");
try {
Response<User> response = callSync.execute();
User user = response.body();
System.out.println(user);
} catch (IOException ex) {
}
// Execute the call asynchronously. Get a positive or negative callback.
callAsync.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
System.out.println(user);
}
@Override
public void onFailure(Call<User> call, Throwable throwable) {
System.out.println(throwable);
}
});
}
}
@@ -0,0 +1,65 @@
package com.baeldung.retrofitguide;
public class User {
private String login;
private long id;
private String url;
private String company;
private String blog;
private String email;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getBlog() {
return blog;
}
public void setBlog(String blog) {
this.blog = blog;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}';
}
}
@@ -0,0 +1,17 @@
package com.baeldung.retrofitguide;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface UserService {
@GET("/users")
public Call<List<User>> getUsers(@Query("per_page") int per_page, @Query("page") int page);
@GET("/users/{username}")
public Call<User> getUser(@Path("username") String username);
}
@@ -0,0 +1,56 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.baeldung.yarg;
import com.haulmont.yarg.formatters.factory.DefaultFormatterFactory;
import com.haulmont.yarg.loaders.factory.DefaultLoaderFactory;
import com.haulmont.yarg.loaders.impl.JsonDataLoader;
import com.haulmont.yarg.reporting.Reporting;
import com.haulmont.yarg.reporting.RunParams;
import com.haulmont.yarg.structure.Report;
import com.haulmont.yarg.structure.ReportBand;
import com.haulmont.yarg.structure.ReportOutputType;
import com.haulmont.yarg.structure.impl.BandBuilder;
import com.haulmont.yarg.structure.impl.ReportBuilder;
import com.haulmont.yarg.structure.impl.ReportTemplateBuilder;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DocumentController {
@RequestMapping(path = "/generate/doc", method = RequestMethod.GET)
public void generateDocument(HttpServletResponse response) throws IOException {
ReportBuilder reportBuilder = new ReportBuilder();
ReportTemplateBuilder reportTemplateBuilder = new ReportTemplateBuilder()
.documentPath("./src/main/resources/Letter.docx")
.documentName("Letter.docx")
.outputType(ReportOutputType.docx)
.readFileFromPath();
reportBuilder.template(reportTemplateBuilder.build());
BandBuilder bandBuilder = new BandBuilder();
String json = FileUtils.readFileToString(new File("./src/main/resources/Data.json"));
ReportBand main = bandBuilder.name("Main")
.query("Main", "parameter=param1 $.main", "json")
.build();
reportBuilder.band(main);
Report report = reportBuilder.build();
Reporting reporting = new Reporting();
reporting.setFormatterFactory(new DefaultFormatterFactory());
reporting.setLoaderFactory(
new DefaultLoaderFactory()
.setJsonDataLoader(new JsonDataLoader()));
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
reporting.runReport(new RunParams(report).param("param1", json), response.getOutputStream());
}
}