getUsers(){
30 | return users;
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/snippets/io/IncrementalSyncSequential/code/src/main/java/com/alibaba/middleware/race/sync/server/Result.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.middleware.race.sync.server;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Queue;
5 |
6 | /**
7 | * One result in queried range
8 | *
9 | * Created by yfu on 6/17/17.
10 | */
11 | final class Result implements Comparable {
12 |
13 | static final Result DONE = new Result(-1, null, -1, -1);
14 |
15 | private final long key;
16 |
17 | final byte[] buffer;
18 | final int offset;
19 | final int length;
20 |
21 | public Result(long key, byte[] buffer, int offset, int length) {
22 | this.key = key;
23 | this.buffer = buffer;
24 | this.offset = offset;
25 | this.length = length;
26 | }
27 |
28 | @Override
29 | public int compareTo(Result o) {
30 | return Long.signum(key - o.key);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/design-patterns/state/example/states/State.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.state.example.states;
2 |
3 | import refactoring_guru.state.example.ui.Player;
4 |
5 | /**
6 | * EN: Common interface for all states.
7 | *
8 | * RU: Общий интерфейс всех состояний.
9 | */
10 | public abstract class State {
11 | Player player;
12 |
13 | /**
14 | * EN: Context passes itself through the state constructor. This may help a
15 | * state to fetch some useful context data if needed.
16 | *
17 | * RU: Контекст передаёт себя в конструктор состояния, чтобы состояние могло
18 | * обращаться к его данным и методам в будущем, если потребуется.
19 | */
20 | State(Player player) {
21 | this.player = player;
22 | }
23 |
24 | public abstract String onLock();
25 | public abstract String onPlay();
26 | public abstract String onNext();
27 | public abstract String onPrevious();
28 | }
29 |
--------------------------------------------------------------------------------
/concurrency/akka/akka-spring/src/main/java/org/baeldung/akka/SpringActorProducer.java:
--------------------------------------------------------------------------------
1 | import akka.actor.Actor;
2 | import akka.actor.IndirectActorProducer;
3 | import org.springframework.context.ApplicationContext;
4 |
5 | public class SpringActorProducer implements IndirectActorProducer {
6 |
7 | private ApplicationContext applicationContext;
8 |
9 | private String beanActorName;
10 |
11 | public SpringActorProducer(ApplicationContext applicationContext, String beanActorName) {
12 | this.applicationContext = applicationContext;
13 | this.beanActorName = beanActorName;
14 | }
15 |
16 | @Override
17 | public Actor produce() {
18 | return (Actor) applicationContext.getBean(beanActorName);
19 | }
20 |
21 | @Override
22 | public Class extends Actor> actorClass() {
23 | return (Class extends Actor>) applicationContext.getType(beanActorName);
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/design-patterns/flyweight/example/forest/Forest.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.flyweight.example.forest;
2 |
3 | import refactoring_guru.flyweight.example.trees.Tree;
4 | import refactoring_guru.flyweight.example.trees.TreeFactory;
5 | import refactoring_guru.flyweight.example.trees.TreeType;
6 |
7 | import javax.swing.*;
8 | import java.awt.*;
9 | import java.util.ArrayList;
10 | import java.util.List;
11 |
12 | public class Forest extends JFrame {
13 | private List trees = new ArrayList<>();
14 |
15 | public void plantTree(int x, int y, String name, Color color, String otherTreeData) {
16 | TreeType type = TreeFactory.getTreeType(name, color, otherTreeData);
17 | Tree tree = new Tree(x, y, type);
18 | trees.add(tree);
19 | }
20 |
21 | @Override
22 | public void paint(Graphics graphics) {
23 | for (Tree tree : trees) {
24 | tree.draw(graphics);
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/design-patterns/visitor/example/shapes/CompoundShape.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.visitor.example.shapes;
2 |
3 | import refactoring_guru.visitor.example.visitor.Visitor;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | public class CompoundShape implements Shape {
9 | public int id;
10 | public List children = new ArrayList<>();
11 |
12 | public CompoundShape(int id) {
13 | this.id = id;
14 | }
15 |
16 | @Override
17 | public void move(int x, int y) {
18 | // move shape
19 | }
20 |
21 | @Override
22 | public void draw() {
23 | // draw shape
24 | }
25 |
26 | public int getId() {
27 | return id;
28 | }
29 |
30 | @Override
31 | public String accept(Visitor visitor) {
32 | return visitor.visitCompoundGraphic(this);
33 | }
34 |
35 | public void add(Shape shape) {
36 | children.add(shape);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/snippets/io/FileIO-MOM/code_klosefu/src/main/java/io/openmessaging/demo/DefaultMessageFactory.java:
--------------------------------------------------------------------------------
1 | package io.openmessaging.demo;
2 |
3 | import io.openmessaging.BytesMessage;
4 | import io.openmessaging.MessageFactory;
5 | import io.openmessaging.MessageHeader;
6 |
7 | public class DefaultMessageFactory implements MessageFactory {
8 |
9 | @Override public BytesMessage createBytesMessageToTopic(String topic, byte[] body) {
10 | DefaultBytesMessage defaultBytesMessage = new DefaultBytesMessage(body);
11 | defaultBytesMessage.putHeaders(MessageHeader.TOPIC, topic);
12 | return defaultBytesMessage;
13 | }
14 |
15 | @Override public BytesMessage createBytesMessageToQueue(String queue, byte[] body) {
16 | DefaultBytesMessage defaultBytesMessage = new DefaultBytesMessage(body);
17 | defaultBytesMessage.putHeaders(MessageHeader.QUEUE, queue);
18 | return defaultBytesMessage;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/design-patterns/abstract_factory/example/factories/MacOSFactory.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.abstract_factory.example.factories;
2 |
3 | import refactoring_guru.abstract_factory.example.buttons.Button;
4 | import refactoring_guru.abstract_factory.example.buttons.MacOSButton;
5 | import refactoring_guru.abstract_factory.example.checkboxes.Checkbox;
6 | import refactoring_guru.abstract_factory.example.checkboxes.MacOSCheckbox;
7 |
8 | /**
9 | * EN: Each concrete factory extends basic factory and responsible for creating
10 | * products of a single variety.
11 | *
12 | * RU: Каждая конкретная фабрика знает и создаёт только продукты своей вариации.
13 | */
14 | public class MacOSFactory implements GUIFactory {
15 |
16 | @Override
17 | public Button createButton() {
18 | return new MacOSButton();
19 | }
20 |
21 | @Override
22 | public Checkbox createCheckbox() {
23 | return new MacOSCheckbox();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/design-patterns/builder/example/builders/Builder.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.builder.example.builders;
2 |
3 | import refactoring_guru.builder.example.cars.Type;
4 | import refactoring_guru.builder.example.components.Engine;
5 | import refactoring_guru.builder.example.components.GPSNavigator;
6 | import refactoring_guru.builder.example.components.Transmission;
7 | import refactoring_guru.builder.example.components.TripComputer;
8 |
9 | /**
10 | * EN: Builder interface defines all possible ways to configure a product.
11 | *
12 | * RU: Интерфейс Строителя объявляет все возможные этапы и шаги конфигурации
13 | * продукта.
14 | */
15 | public interface Builder {
16 | void setType(Type type);
17 | void setSeats(int seats);
18 | void setEngine(Engine engine);
19 | void setTransmission(Transmission transmission);
20 | void setTripComputer(TripComputer tripComputer);
21 | void setGPSNavigator(GPSNavigator gpsNavigator);
22 | }
23 |
--------------------------------------------------------------------------------
/design-patterns/command/example/commands/CutCommand.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.command.example.commands;
2 |
3 | import refactoring_guru.command.example.editor.Editor;
4 |
5 | public class CutCommand extends Command {
6 |
7 | public CutCommand(Editor editor) {
8 | super(editor);
9 | }
10 |
11 | @Override
12 | public boolean execute() {
13 | if (editor.textField.getSelectedText().isEmpty()) return false;
14 |
15 | backup();
16 | String source = editor.textField.getText();
17 | editor.clipboard = editor.textField.getSelectedText();
18 | editor.textField.setText(cutString(source));
19 | return true;
20 | }
21 |
22 | private String cutString(String source) {
23 | String start = source.substring(0, editor.textField.getSelectionStart());
24 | String end = source.substring(editor.textField.getSelectionEnd());
25 | return start + end;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/concurrency/akka/akka-start/src/main/java/sample/hello/Main2.java:
--------------------------------------------------------------------------------
1 | import akka.actor.*;
2 |
3 | public class Main2 {
4 |
5 | public static void main(String[] args) {
6 | ActorSystem system = ActorSystem.create("Hello");
7 | ActorRef a = system.actorOf(Props.create(HelloWorld.class), "helloWorld");
8 | system.actorOf(Props.create(Terminator.class, a), "terminator");
9 | }
10 |
11 | public static class Terminator extends AbstractLoggingActor {
12 |
13 | private final ActorRef ref;
14 |
15 | public Terminator(ActorRef ref) {
16 | this.ref = ref;
17 | getContext().watch(ref);
18 | }
19 |
20 | @Override
21 | public Receive createReceive() {
22 | return receiveBuilder()
23 | .match(Terminated.class, t -> {
24 | log().info("{} has terminated, shutting down system", ref.path());
25 | getContext().system().terminate();
26 | })
27 | .build();
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/design-patterns/abstract_factory/example/factories/WindowsFactory.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.abstract_factory.example.factories;
2 |
3 | import refactoring_guru.abstract_factory.example.buttons.Button;
4 | import refactoring_guru.abstract_factory.example.buttons.WindowsButton;
5 | import refactoring_guru.abstract_factory.example.checkboxes.Checkbox;
6 | import refactoring_guru.abstract_factory.example.checkboxes.WindowsCheckbox;
7 |
8 | /**
9 | * EN: Each concrete factory extends basic factory and responsible for creating
10 | * products of a single variety.
11 | *
12 | * RU: Каждая конкретная фабрика знает и создаёт только продукты своей вариации.
13 | */
14 | public class WindowsFactory implements GUIFactory {
15 |
16 | @Override
17 | public Button createButton() {
18 | return new WindowsButton();
19 | }
20 |
21 | @Override
22 | public Checkbox createCheckbox() {
23 | return new WindowsCheckbox();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/design-patterns/visitor/example/shapes/Dot.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.visitor.example.shapes;
2 |
3 | import refactoring_guru.visitor.example.visitor.Visitor;
4 |
5 | public class Dot implements Shape {
6 | private int id;
7 | private int x;
8 | private int y;
9 |
10 | public Dot() {
11 | }
12 |
13 | public Dot(int id, int x, int y) {
14 | this.id = id;
15 | this.x = x;
16 | this.y = y;
17 | }
18 |
19 | @Override
20 | public void move(int x, int y) {
21 | // move shape
22 | }
23 |
24 | @Override
25 | public void draw() {
26 | // draw shape
27 | }
28 |
29 | public String accept(Visitor visitor) {
30 | return visitor.visitDot(this);
31 | }
32 |
33 | public int getX() {
34 | return x;
35 | }
36 |
37 | public int getY() {
38 | return y;
39 | }
40 |
41 | public int getId() {
42 | return id;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/concurrency/basic/src/main/java/primitive/atomic/AtomicTest.java:
--------------------------------------------------------------------------------
1 | package primitive.atomic;
2 |
3 | import java.util.concurrent.atomic.AtomicInteger;
4 |
5 | /**
6 | * Atomic 测试
7 | */
8 |
9 | public class AtomicTest {
10 |
11 | private static final int THREADS_COUNT = 20;
12 | private static final AtomicInteger race = new AtomicInteger();
13 |
14 | private static void increase() {
15 | race.incrementAndGet();
16 | }
17 |
18 | public static void main(String[] args) {
19 | Thread[] threads = new Thread[THREADS_COUNT];
20 |
21 | for (int i = 0; i < THREADS_COUNT; ++i) {
22 | threads[i] = new Thread(() -> {
23 | for (int j = 0; j < 10000; j++) {
24 | increase();
25 | }
26 | });
27 | threads[i].start();
28 | }
29 |
30 | while (Thread.activeCount() > 1) {
31 | Thread.yield();
32 | }
33 |
34 | System.out.println(race.get());
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/concurrency/akka/akka-spring-boot/src/main/java/com/chriniko/example/akkaspringexample/file/FileLinesCounter.java:
--------------------------------------------------------------------------------
1 | import org.springframework.stereotype.Component;
2 |
3 | import java.io.IOException;
4 | import java.nio.file.Files;
5 | import java.nio.file.Paths;
6 |
7 | @Component
8 | public class FileLinesCounter {
9 |
10 | public long count(String filename, boolean hasHeaders) {
11 |
12 | try {
13 | long count = Files.lines(Paths.get(filename)).count();
14 | return hasHeaders ? count - 1 : count;
15 | } catch (IOException e) {
16 | e.printStackTrace(System.err);
17 | throw new RuntimeException(e);
18 | }
19 |
20 | }
21 |
22 | public String getFile(String resourcePath) {
23 | return this.getClass()
24 | .getClassLoader()
25 | .getResource(resourcePath)
26 | .toString()
27 | .replace("file:", "");
28 | }
29 |
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/concurrency/akka/akka-spring-boot/src/main/java/com/chriniko/example/akkaspringexample/integration/akka/SpringAkkaExtension.java:
--------------------------------------------------------------------------------
1 | import akka.actor.Extension;
2 | import akka.actor.Props;
3 | import org.springframework.context.ApplicationContext;
4 | import org.springframework.stereotype.Component;
5 |
6 | @Component
7 | public class SpringAkkaExtension implements Extension {
8 |
9 | private ApplicationContext applicationContext;
10 |
11 | public void initialize(ApplicationContext applicationContext) {
12 | this.applicationContext = applicationContext;
13 | }
14 |
15 | public Props props(String actorBeanName) {
16 | return Props.create(SpringActorProducer.class, applicationContext, actorBeanName);
17 | }
18 |
19 | public static String classNameToSpringName(Class> clazz) {
20 |
21 | String simpleName = clazz.getSimpleName();
22 |
23 | return simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/design-patterns/adapter/example/adapters/SquarePegAdapter.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.adapter.example.adapters;
2 |
3 | import refactoring_guru.adapter.example.round.RoundPeg;
4 | import refactoring_guru.adapter.example.square.SquarePeg;
5 |
6 | /**
7 | * EN: Adapter allows fitting square pegs into round holes.
8 | *
9 | * RU: Адаптер позволяет использовать КвадратныеКолышки и КруглыеОтверстия
10 | * вместе.
11 | */
12 | public class SquarePegAdapter extends RoundPeg {
13 | private SquarePeg peg;
14 |
15 | public SquarePegAdapter(SquarePeg peg) {
16 | this.peg = peg;
17 | }
18 |
19 | @Override
20 | public double getRadius() {
21 | double result;
22 | // EN: Calculate a minimum circle radius, which can fit this peg.
23 | //
24 | // RU: Рассчитываем минимальный радиус, в который пролезет этот колышек.
25 | result = (Math.sqrt(Math.pow((peg.getWidth() / 2), 2) * 2));
26 | return result;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/concurrency/akka/akka-cluster/src/main/java/sample/cluster/factorial/FactorialBackend.java:
--------------------------------------------------------------------------------
1 | import java.math.BigInteger;
2 | import java.util.concurrent.CompletableFuture;
3 |
4 | import akka.actor.AbstractActor;
5 | import static akka.pattern.PatternsCS.pipe;
6 |
7 | public class FactorialBackend extends AbstractActor {
8 |
9 | @Override
10 | public Receive createReceive() {
11 | return receiveBuilder()
12 | .match(Integer.class, n -> {
13 |
14 | CompletableFuture result =
15 | CompletableFuture.supplyAsync(() -> factorial(n))
16 | .thenApply((factorial) -> new FactorialResult(n, factorial));
17 |
18 | pipe(result, getContext().dispatcher()).to(sender());
19 |
20 | })
21 | .build();
22 | }
23 |
24 | BigInteger factorial(int n) {
25 | BigInteger acc = BigInteger.ONE;
26 | for (int i = 1; i <= n; ++i) {
27 | acc = acc.multiply(BigInteger.valueOf(i));
28 | }
29 | return acc;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/concurrency/akka/akka-fsm/src/main/java/sample/fsm/Messages.java:
--------------------------------------------------------------------------------
1 | import akka.actor.ActorRef;
2 |
3 | public class Messages {
4 |
5 | public static final class Busy {
6 | public final ActorRef chopstick;
7 | public Busy(ActorRef chopstick){
8 | this.chopstick = chopstick;
9 | }
10 | }
11 |
12 | private static interface PutMessage {};
13 | public static final Object Put = new PutMessage() {
14 | @Override
15 | public String toString() { return "Put"; }
16 | };
17 |
18 | private static interface TakeMessage {};
19 | public static final Object Take = new TakeMessage() {
20 | @Override
21 | public String toString() { return "Take"; }
22 | };
23 |
24 | public static final class Taken {
25 | public final ActorRef chopstick;
26 | public Taken(ActorRef chopstick){
27 | this.chopstick = chopstick;
28 | }
29 | }
30 |
31 | private static interface ThinkMessage {};
32 | public static final Object Think = new ThinkMessage() {};
33 | }
34 |
--------------------------------------------------------------------------------
/concurrency/akka/akka-cluster/src/main/java/sample/cluster/transformation/TransformationBackendMain.java:
--------------------------------------------------------------------------------
1 | import com.typesafe.config.Config;
2 | import com.typesafe.config.ConfigFactory;
3 |
4 | import akka.actor.ActorSystem;
5 | import akka.actor.Props;
6 |
7 | public class TransformationBackendMain {
8 |
9 | public static void main(String[] args) {
10 | // Override the configuration of the port when specified as program argument
11 | final String port = args.length > 0 ? args[0] : "0";
12 | final Config config =
13 | ConfigFactory.parseString(
14 | "akka.remote.netty.tcp.port=" + port + "\n" +
15 | "akka.remote.artery.canonical.port=" + port)
16 | .withFallback(ConfigFactory.parseString("akka.cluster.roles = [backend]"))
17 | .withFallback(ConfigFactory.load());
18 |
19 | ActorSystem system = ActorSystem.create("ClusterSystem", config);
20 |
21 | system.actorOf(Props.create(TransformationBackend.class), "backend");
22 |
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/design-patterns/bridge/example/OutputDemo.txt:
--------------------------------------------------------------------------------
1 | Tests with basic remote.
2 | Remote: power toggle
3 | ------------------------------------
4 | | I'm TV set.
5 | | I'm enabled
6 | | Current volume is 30%
7 | | Current channel is 1
8 | ------------------------------------
9 |
10 | Tests with advanced remote.
11 | Remote: power toggle
12 | Remote: mute
13 | ------------------------------------
14 | | I'm TV set.
15 | | I'm disabled
16 | | Current volume is 0%
17 | | Current channel is 1
18 | ------------------------------------
19 |
20 | Tests with basic remote.
21 | Remote: power toggle
22 | ------------------------------------
23 | | I'm radio.
24 | | I'm enabled
25 | | Current volume is 30%
26 | | Current channel is 1
27 | ------------------------------------
28 |
29 | Tests with advanced remote.
30 | Remote: power toggle
31 | Remote: mute
32 | ------------------------------------
33 | | I'm radio.
34 | | I'm disabled
35 | | Current volume is 0%
36 | | Current channel is 1
37 | ------------------------------------
--------------------------------------------------------------------------------
/concurrency/akka/akka-spring-boot/src/main/java/com/chriniko/example/akkaspringexample/integration/akka/SpringActorProducer.java:
--------------------------------------------------------------------------------
1 | import akka.actor.Actor;
2 | import akka.actor.IndirectActorProducer;
3 | import org.springframework.context.ApplicationContext;
4 |
5 | public class SpringActorProducer implements IndirectActorProducer {
6 |
7 | private final ApplicationContext applicationContext;
8 | private final String actorBeanName;
9 |
10 | public SpringActorProducer(ApplicationContext applicationContext, String actorBeanName) {
11 | this.applicationContext = applicationContext;
12 | this.actorBeanName = actorBeanName;
13 | }
14 |
15 | @Override
16 | public Actor produce() {
17 | return (Actor) applicationContext.getBean(actorBeanName);
18 | }
19 |
20 | @SuppressWarnings("unchecked")
21 | @Override
22 | public Class extends Actor> actorClass() {
23 | return (Class extends Actor>) applicationContext.getType(actorBeanName);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/design-patterns/decorator/example/Demo.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.decorator.example;
2 |
3 | import refactoring_guru.decorator.example.decorators.*;
4 |
5 | public class Demo {
6 | public static void main(String[] args) {
7 | String salaryRecords = "Name,Salary\nJohn Smith,100000\nSteven Jobs,912000";
8 | DataSourceDecorator encoded = new CompressionDecorator(
9 | new EncryptionDecorator(
10 | new FileDataSource("out/OutputDemo.txt")));
11 | encoded.writeData(salaryRecords);
12 | DataSource plain = new FileDataSource("out/OutputDemo.txt");
13 |
14 | System.out.println("- Input ----------------");
15 | System.out.println(salaryRecords);
16 | System.out.println("- Encoded --------------");
17 | System.out.println(plain.readData());
18 | System.out.println("- Decoded --------------");
19 | System.out.println(encoded.readData());
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/design-patterns/iterator/example/OutputDemo.txt:
--------------------------------------------------------------------------------
1 | Please specify social network to target spam tool (default:Facebook):
2 | 1. Facebook
3 | 2. LinkedIn
4 | > 1
5 |
6 | Iterating over friends...
7 |
8 | Facebook: Loading 'friends' list of 'anna.smith@bing.com' over the network...
9 | Facebook: Loading profile 'mad_max@ya.com' over the network...
10 | Sent message to: 'mad_max@ya.com'. Message body: 'Hey! This is Anna's friend Josh. Can you do me a favor and like this post [link]?'
11 | Facebook: Loading profile 'catwoman@yahoo.com' over the network...
12 | Sent message to: 'catwoman@yahoo.com'. Message body: 'Hey! This is Anna's friend Josh. Can you do me a favor and like this post [link]?'
13 |
14 | Iterating over coworkers...
15 |
16 | Facebook: Loading 'coworkers' list of 'anna.smith@bing.com' over the network...
17 | Facebook: Loading profile 'sam@amazon.com' over the network...
18 | Sent message to: 'sam@amazon.com'. Message body: 'Hey! This is Anna's boss Jason. Anna told me you would be interested in [link].'
19 |
--------------------------------------------------------------------------------
/concurrency/akka/akka-spring-boot/src/main/java/com/chriniko/example/akkaspringexample/configuration/SchedulingConfiguration.java:
--------------------------------------------------------------------------------
1 | import org.springframework.context.annotation.Bean;
2 | import org.springframework.context.annotation.Configuration;
3 | import org.springframework.scheduling.annotation.EnableScheduling;
4 | import org.springframework.scheduling.annotation.SchedulingConfigurer;
5 | import org.springframework.scheduling.config.ScheduledTaskRegistrar;
6 |
7 | import java.util.concurrent.ExecutorService;
8 | import java.util.concurrent.Executors;
9 |
10 | @Configuration
11 | @EnableScheduling
12 | public class SchedulingConfiguration implements SchedulingConfigurer {
13 |
14 | @Override
15 | public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
16 | taskRegistrar.setScheduler(taskScheduler());
17 | }
18 |
19 | @Bean(destroyMethod = "shutdown")
20 | public ExecutorService taskScheduler() {
21 | return Executors.newScheduledThreadPool(1);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/design-patterns/visitor/example/Demo.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.visitor.example;
2 |
3 | import refactoring_guru.visitor.example.shapes.*;
4 | import refactoring_guru.visitor.example.visitor.XMLExportVisitor;
5 |
6 | public class Demo {
7 | public static void main(String[] args) {
8 | Dot dot = new Dot(1, 10, 55);
9 | Circle circle = new Circle(2, 23, 15, 10);
10 | Rectangle rectangle = new Rectangle(3, 10, 17, 20, 30);
11 |
12 | CompoundShape compoundShape = new CompoundShape(4);
13 | compoundShape.add(dot);
14 | compoundShape.add(circle);
15 | compoundShape.add(rectangle);
16 |
17 | CompoundShape c = new CompoundShape(5);
18 | c.add(dot);
19 | compoundShape.add(c);
20 |
21 | export(circle, compoundShape);
22 | }
23 |
24 | private static void export(Shape... shapes) {
25 | XMLExportVisitor exportVisitor = new XMLExportVisitor();
26 | System.out.println(exportVisitor.export(shapes));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/concurrency/akka/akka-sharding/src/main/java/sample/sharding/ShardingApp.java:
--------------------------------------------------------------------------------
1 | import akka.actor.ActorSystem;
2 | import akka.actor.Props;
3 |
4 | import com.typesafe.config.Config;
5 | import com.typesafe.config.ConfigFactory;
6 |
7 | public class ShardingApp {
8 |
9 | public static void main(String[] args) {
10 | if (args.length == 0)
11 | startup(new String[] { "2551", "2552", "0" });
12 | else
13 | startup(args);
14 | }
15 |
16 | public static void startup(String[] ports) {
17 | for (String port : ports) {
18 | // Override the configuration of the port
19 | Config config = ConfigFactory.parseString(
20 | "akka.remote.netty.tcp.port=" + port).withFallback(
21 | ConfigFactory.load());
22 |
23 | // Create an Akka system
24 | ActorSystem system = ActorSystem.create("ShardingSystem", config);
25 |
26 | // Create an actor that starts the sharding and sends random messages
27 | system.actorOf(Props.create(Devices.class));
28 | }
29 | }
30 | }
--------------------------------------------------------------------------------
/design-patterns/mediator/example/components/Title.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.mediator.example.components;
2 |
3 | import refactoring_guru.mediator.example.mediator.Mediator;
4 |
5 | import javax.swing.*;
6 | import java.awt.event.KeyEvent;
7 |
8 | /**
9 | * EN: Concrete components don't talk with each other. They have only one
10 | * communication channel–sending requests to the mediator.
11 | *
12 | * RU: Конкретные компоненты никак не связаны между собой. У них есть только
13 | * один канал общения – через отправку уведомлений посреднику.
14 | */
15 | public class Title extends JTextField implements Component {
16 | private Mediator mediator;
17 |
18 | @Override
19 | public void setMediator(Mediator mediator) {
20 | this.mediator = mediator;
21 | }
22 |
23 | @Override
24 | protected void processComponentKeyEvent(KeyEvent keyEvent) {
25 | mediator.markNote();
26 | }
27 |
28 | @Override
29 | public String getName() {
30 | return "Title";
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/design-patterns/state/example/states/ReadyState.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.state.example.states;
2 |
3 | import refactoring_guru.state.example.ui.Player;
4 |
5 | /**
6 | * EN: They can also trigger state transitions in the context.
7 | *
8 | * RU: Они также могут переводить контекст в другие состояния.
9 | */
10 | public class ReadyState extends State {
11 |
12 | public ReadyState(Player player) {
13 | super(player);
14 | }
15 |
16 | @Override
17 | public String onLock() {
18 | player.changeState(new LockedState(player));
19 | return "Locked...";
20 | }
21 |
22 | @Override
23 | public String onPlay() {
24 | String action = player.startPlayback();
25 | player.changeState(new PlayingState(player));
26 | return action;
27 | }
28 |
29 | @Override
30 | public String onNext() {
31 | return "Locked...";
32 | }
33 |
34 | @Override
35 | public String onPrevious() {
36 | return "Locked...";
37 | }
38 | }
39 |
--------------------------------------------------------------------------------