output
stringlengths 7
516k
| instruction
stringclasses 1
value | input
stringlengths 6
884k
|
---|---|---|
```package com.github.hykes.codegen;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.jetbrains.java.generate.velocity.VelocityFactory;
import org.junit.Assert;
import org.junit.Test;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
/**
* @author hehaiyangwork@gmail.com
* @date 2017/12/19
*/
public class VelocityTest {
@Test
public void testSplitLowerCase() {
VelocityEngine velocityEngine = VelocityFactory.getVelocityEngine();
velocityEngine.loadDirective("com.github.hykes.codegen.directive.LowerCase");
velocityEngine.loadDirective("com.github.hykes.codegen.directive.Split");
String template = "#Split(\"#LowerCase(${NAME})\" '.')";
Map<String, Object> map = new HashMap<>();
map.put("NAME", "HykesIsStrong");
StringWriter writer = new StringWriter();
velocityEngine.evaluate(new VelocityContext(map), writer, "", template);
Assert.assertEquals(writer.toString(), "hykes.is.strong");
}
}
```
|
Please help me generate a test for this class.
|
```package com.github.hykes.codegen.utils;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.log.NullLogChute;
import org.jetbrains.java.generate.velocity.VelocityFactory;
import java.io.StringWriter;
/**
* @author hehaiyangwork@gmail.com
* @date 2017/12/24
*/
public class VelocityUtil {
protected final static VelocityEngine VELOCITY_ENGINE = VelocityFactory.getVelocityEngine();
static {
/*
IDEA ็ URLClassLoader ๆ ๆณ่ทๅๅฝๅๆไปถ็ path
@see org.apache.velocity.util.ClassUtils
*/
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(VelocityUtil.class.getClassLoader());
VELOCITY_ENGINE.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, NullLogChute.class.getName());
VELOCITY_ENGINE.loadDirective("com.github.hykes.codegen.directive.LowerCase");
VELOCITY_ENGINE.loadDirective("com.github.hykes.codegen.directive.UpperCase");
VELOCITY_ENGINE.loadDirective("com.github.hykes.codegen.directive.Append");
VELOCITY_ENGINE.loadDirective("com.github.hykes.codegen.directive.Split");
VELOCITY_ENGINE.loadDirective("com.github.hykes.codegen.directive.ImportPackage");
VELOCITY_ENGINE.loadDirective("com.github.hykes.codegen.directive.GetPackage");
Thread.currentThread().setContextClassLoader(classLoader);
}
public static String evaluate(Context context, String inputStr) {
StringWriter writer = new StringWriter();
VELOCITY_ENGINE.evaluate(context, writer, "", inputStr);
return writer.toString();
}
}
```
|
```package com.arcbees.chosen.integrationtest.client.testcases.dropdownposition;
import java.util.EnumSet;
import com.arcbees.chosen.client.ChosenOptions;
import com.arcbees.chosen.client.DropdownBoundariesProvider;
import com.arcbees.chosen.client.DropdownPosition;
import com.arcbees.chosen.client.gwt.ChosenValueListBox;
import com.arcbees.chosen.integrationtest.client.domain.CarBrand;
import com.arcbees.chosen.integrationtest.client.domain.DefaultCarRenderer;
import com.google.gwt.dom.client.Element;
import com.google.gwt.text.shared.AbstractRenderer;
public class DropdownPositionTestHelper {
public static final AbstractRenderer<CarBrand> RENDERER = new DefaultCarRenderer();
public static ChosenValueListBox buildSample(DropdownPosition dropdownPosition, Element dropdownBoundaries,
DropdownBoundariesProvider dropdownBoundariesProvider) {
ChosenOptions options = new ChosenOptions();
options.setDropdownPosition(dropdownPosition);
options.setDropdownBoundaries(dropdownBoundaries);
options.setDropdownBoundariesProvider(dropdownBoundariesProvider);
return buildListbox(options);
}
private static ChosenValueListBox<CarBrand> buildListbox(ChosenOptions options) {
ChosenValueListBox<CarBrand> listBox = new ChosenValueListBox<CarBrand>(RENDERER, options);
listBox.setAcceptableValues(EnumSet.of(CarBrand.AUDI, CarBrand.BENTLEY, CarBrand.BMW));
listBox.setValue(CarBrand.AUDI);
return listBox;
}
}
```
|
Please help me generate a test for this class.
|
```package com.arcbees.chosen.client;
public enum DropdownPosition {
BELOW, ABOVE, AUTO
}
```
|
```package com.arcbees.chosen.integrationtest.client.testcases;
import com.arcbees.chosen.integrationtest.client.domain.CarBrand;
public class ChooseOption extends SimpleValueListBox {
@Override
public void run() {
super.run();
getListBox().setValue(CarBrand.AUDI);
}
}
```
|
Please help me generate a test for this class.
|
```package com.arcbees.chosen.client;
import com.arcbees.chosen.client.resources.Resources;
import com.google.gwt.dom.client.Element;
public class ChosenOptions {
private boolean allowSingleDeselect;
private int disableSearchThreshold;
private int maxSelectedOptions;
private String noResultsText;
private String placeholderText;
private String placeholderTextMultiple;
private String placeholderTextSingle;
private Resources resources;
private boolean searchContains;
private boolean singleBackstrokeDelete;
private boolean highlightSearchTerm;
private ResultsFilter resultFilter;
private DropdownPosition dropdownPosition;
private Element dropdownBoundaries;
private DropdownBoundariesProvider dropdownBoundariesProvider;
private int mobileViewportMaxWidth;
private String oneSelectedTextMultipleMobile;
private String manySelectedTextMultipleMobile;
private boolean mobileAnimation;
private int mobileAnimationSpeed;
public ChosenOptions() {
setDefault();
}
public int getDisableSearchThreshold() {
return disableSearchThreshold;
}
/**
* Set the number of items needed to show and enable the search input. This option is when the Chosen component is
* used in "multiple select" mode or when a custom ResultFilter is used.
*
* @param disableSearchThreshold number of items needed to show and enable the search input
*/
public ChosenOptions setDisableSearchThreshold(int disableSearchThreshold) {
this.disableSearchThreshold = disableSearchThreshold;
return this;
}
public Element getDropdownBoundaries() {
return dropdownBoundaries;
}
/**
* When {@link com.arcbees.chosen.client.ChosenOptions#dropdownPosition} is set to
* {@link com.arcbees.chosen.client.DropdownPosition#AUTO}, this element will be used to calculate the available
* vertical space below the dropdown.
*/
public ChosenOptions setDropdownBoundaries(Element dropdownBoundaries) {
this.dropdownBoundaries = dropdownBoundaries;
return this;
}
public DropdownBoundariesProvider getDropdownBoundariesProvider() {
return dropdownBoundariesProvider;
}
/**
* See {@link com.arcbees.chosen.client.ChosenOptions#setDropdownBoundaries(com.google.gwt.dom.client.Element)}.
* Useful for cases when the {@link com.arcbees.chosen.client.ChosenOptions#dropdownBoundaries} cannot be defined
* when the Chosen widget is built.
* <p/>
* {@link com.arcbees.chosen.client.ChosenOptions#setDropdownBoundaries(com.google.gwt.dom.client.Element)} will
* have priority over this setting.
*/
public ChosenOptions setDropdownBoundariesProvider(DropdownBoundariesProvider dropdownBoundariesProvider) {
this.dropdownBoundariesProvider = dropdownBoundariesProvider;
return this;
}
public DropdownPosition getDropdownPosition() {
return dropdownPosition;
}
/**
* Sets the positioning of the dropdown.
* If set to {@link com.arcbees.chosen.client.DropdownPosition#BELOW}, dropdown will be displayed below the input
* box.
* If set to {@link com.arcbees.chosen.client.DropdownPosition#ABOVE}, dropdown will be displayed above the input
* box.
* If set to {@link com.arcbees.chosen.client.DropdownPosition#AUTO}, dropdown will be displayed below the input
* box only if there's enough vertical space between the input box and the bottom of the
* {@link com.arcbees.chosen.client.ChosenOptions#dropdownBoundaries}. Otherwise, the dropdown will be displayed
* above the input box.
* <p/>
* If not set, it will default to {@link com.arcbees.chosen.client.DropdownPosition#BELOW}.
*/
public ChosenOptions setDropdownPosition(DropdownPosition dropdownPosition) {
this.dropdownPosition = dropdownPosition;
return this;
}
public int getMaxSelectedOptions() {
return maxSelectedOptions;
}
public ChosenOptions setMaxSelectedOptions(int maxSelectedOptions) {
this.maxSelectedOptions = maxSelectedOptions;
return this;
}
public int getMobileViewportMaxWidth() {
return mobileViewportMaxWidth;
}
/**
* Set the max width threshold below which the component will consider to be displayed on mobile device.
* <p/>
* If you want to disable the mobile layout of the component on every device, set the
* <code>mobileViewportMaxWidth</code> to -1.
* <p/>
* The component is responsive only if you define a viewport in your html file, example:
* <meta name="viewport" content="width=device-width, initial-scale=1">
*
* @param mobileViewportMaxWidth max width threshold below which the component will consider
* to be displayed on mobile device
*/
public ChosenOptions setMobileViewportMaxWidth(int mobileViewportMaxWidth) {
this.mobileViewportMaxWidth = mobileViewportMaxWidth;
return this;
}
public String getOneSelectedTextMultipleMobile() {
return oneSelectedTextMultipleMobile;
}
/**
* Set the text to use when one option is selected on a mobile multiple select.
* <p/>
* <code>{}</code> can be used in the text to indicate where to put the number of option selected (in this case 1).
* <p/>
* Ex:
* options.setOneSelectedTextMultipleMobile("{} country selected");
*/
public ChosenOptions setOneSelectedTextMultipleMobile(String oneSelectedTextMultipleMobile) {
this.oneSelectedTextMultipleMobile = oneSelectedTextMultipleMobile;
return this;
}
public String getManySelectedTextMultipleMobile() {
return manySelectedTextMultipleMobile;
}
/**
* Set the text to use when several options are selected on a mobile multiple select.
* <p/>
* <code>{}</code> can be used in the text to indicate where to put the number of option selected.
* <p/>
* Ex:
* options.setManySelectedTextMultipleMobile("{} countries selected");
*/
public ChosenOptions setManySelectedTextMultipleMobile(String manySelectedTextMultipleMobile) {
this.manySelectedTextMultipleMobile = manySelectedTextMultipleMobile;
return this;
}
public String getNoResultsText() {
return noResultsText;
}
public ChosenOptions setNoResultsText(String noResultsText) {
this.noResultsText = noResultsText;
return this;
}
public String getPlaceholderText() {
return placeholderText;
}
public ChosenOptions setPlaceholderText(String placeholderText) {
this.placeholderText = placeholderText;
return this;
}
public String getPlaceholderTextMultiple() {
return placeholderTextMultiple;
}
public ChosenOptions setPlaceholderTextMultiple(String placeholderTextMultiple) {
this.placeholderTextMultiple = placeholderTextMultiple;
return this;
}
public String getPlaceholderTextSingle() {
return placeholderTextSingle;
}
public ChosenOptions setPlaceholderTextSingle(String placeholderTextSingle) {
this.placeholderTextSingle = placeholderTextSingle;
return this;
}
public Resources getResources() {
return resources;
}
public ChosenOptions setResources(Resources resources) {
this.resources = resources;
return this;
}
/**
* provide the {@code ResultFilter} instance used to filter the data.
*/
public ResultsFilter getResultFilter() {
return resultFilter;
}
public void setResultFilter(ResultsFilter resultFilter) {
this.resultFilter = resultFilter;
}
/**
* Specify if the deselection is allowed on single selects.
*/
public boolean isAllowSingleDeselect() {
return allowSingleDeselect;
}
public ChosenOptions setAllowSingleDeselect(Boolean allowSingleDeselect) {
this.allowSingleDeselect = allowSingleDeselect;
return this;
}
public boolean isHighlightSearchTerm() {
return highlightSearchTerm;
}
public void setHighlightSearchTerm(boolean highlightSearchTerm) {
this.highlightSearchTerm = highlightSearchTerm;
}
public boolean isSearchContains() {
return searchContains;
}
public ChosenOptions setSearchContains(boolean searchContains) {
this.searchContains = searchContains;
return this;
}
public boolean isSingleBackstrokeDelete() {
return singleBackstrokeDelete;
}
public ChosenOptions setSingleBackstrokeDelete(boolean singleBackstrokeDelete) {
this.singleBackstrokeDelete = singleBackstrokeDelete;
return this;
}
public boolean isMobileAnimation() {
return mobileAnimation;
}
public ChosenOptions setMobileAnimation(boolean mobileAnimation) {
this.mobileAnimation = mobileAnimation;
return this;
}
public ChosenOptions setMobileAnimationSpeed(int mobileAnimationSpeed) {
this.mobileAnimationSpeed = mobileAnimationSpeed;
return this;
}
public int getMobileAnimationSpeed() {
return this.mobileAnimationSpeed;
}
private void setDefault() {
allowSingleDeselect = false;
disableSearchThreshold = 0;
searchContains = false;
singleBackstrokeDelete = false;
maxSelectedOptions = -1;
highlightSearchTerm = true;
dropdownPosition = DropdownPosition.BELOW;
mobileViewportMaxWidth = 649;
oneSelectedTextMultipleMobile = "{} item selected";
manySelectedTextMultipleMobile = "{} items selected";
mobileAnimation = true;
mobileAnimationSpeed = 150;
}
}
```
|
```package Chap4_ClassAndInterface.item19;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.util.Base64;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertSame;
class SerializableSubFooTest {
@DisplayName("์ญ์ง๋ ฌํ์ readObject๊ฐ ์ฌ์ ์๋ ๋ฉ์๋ ํธ์ถ")
@Test
void name() throws IOException, ClassNotFoundException{
SerializableSubFoo subFoo = new SerializableSubFoo();
subFoo.setStr("hi!!!!");
//์ง๋ ฌํ
byte[] serializedFoo;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(subFoo);
serializedFoo = baos.toByteArray();
}
}
// ์ญ์ง๋ ฌํ
assertThatThrownBy(() -> {
byte[] deserializedMember = Base64.getDecoder().decode(Base64.getEncoder().encodeToString(serializedFoo));
try (ByteArrayInputStream bais = new ByteArrayInputStream(deserializedMember)) {
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
Object objectMember = ois.readObject();
SerializableSubFoo deserialized = (SerializableSubFoo) objectMember;
assertSame(deserialized,subFoo);
}
}
}).isInstanceOf(NullPointerException.class);
}
}
```
|
Please help me generate a test for this class.
|
```package Chap4_ClassAndInterface.item19;
public class SerializableSubFoo extends SerializableFoo {
String str;
public void setStr(String str) {
this.str = str;
}
@Override
public void overrideMe() {
System.out.println("This is SubFoo's overrideMe");
if (str == null) {
throw new NullPointerException();
}
System.out.println(str);
}
}
```
|
```package Chap12_Serialization.item86.proxy;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import static org.assertj.core.api.Assertions.assertThat;
class SubTest {
@DisplayName("ํ๋ก์ X")
@Test
void name() throws Exception {
Sub sub = new Sub(2);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream outputStream = new ObjectOutputStream(baos);
outputStream.writeObject(sub);
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream objectInputStream = new ObjectInputStream(byteInputStream);
Sub deserialize = (Sub) objectInputStream.readObject();
assertThat(deserialize.getSubValue()).isEqualTo(2);
}
@DisplayName("ํ๋ก์ O")
@Test
void name2() throws Exception {
ProxySub proxySub = new ProxySub(2);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream outputStream = new ObjectOutputStream(baos);
outputStream.writeObject(proxySub);
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream objectInputStream = new ObjectInputStream(byteInputStream);
ProxySub deserialize = (ProxySub) objectInputStream.readObject();
assertThat(deserialize.getSubValue()).isEqualTo(2);
}
}```
|
Please help me generate a test for this class.
|
```package Chap12_Serialization.item86.proxy;
import java.io.Serializable;
public class Sub extends Super implements Serializable {
private int subValue;
public Sub(final int subValue) {
super(subValue - 1);
this.subValue = subValue;
}
public int getSubValue() {
return subValue;
}
}
```
|
```package Chap12_Serialization.item90;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Base64;
import static org.assertj.core.api.Assertions.assertThat;
class FooTest {
@DisplayName("์ง๋ ฌํ ์ญ์ง๋ ฌํ ๊ณผ์ ")
@Test
void getValue() throws IOException, ClassNotFoundException {
byte[] serializedFooBytes;
Foo foo = new Foo("START");
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(foo);
serializedFooBytes = baos.toByteArray();
}
}
byte[] deserializedFooBytes = Base64.getDecoder().decode(Base64.getEncoder().encodeToString(serializedFooBytes));
Foo deserializedFoo;
try (ByteArrayInputStream bais = new ByteArrayInputStream(deserializedFooBytes)) {
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
Object objectMember = ois.readObject();
deserializedFoo = (Foo) objectMember;
}
}
// assertThat(deserializedFoo.getValue()).isEqualTo("FIX");
// assertThat(deserializedFoo.getValue()).isEqualTo("READ_OBJECT");
assertThat(deserializedFoo.getValue()).isEqualTo("START");
}
}```
|
Please help me generate a test for this class.
|
```package Chap12_Serialization.item90;
import java.io.ObjectInputStream;
import java.io.Serializable;
public class Foo implements Serializable {
public static final Foo INSTANCE = new Foo("FIX");
private String value;
public Foo(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
private Object writeReplace() {
return new FooProxy(this);
}
private void readObject(ObjectInputStream in) {
throw new UnsupportedOperationException();
}
static class FooProxy implements Serializable {
private String value;
public FooProxy(Foo foo) {
this.value = foo.value;
}
private Object readResolve() {
return new Foo(this.value);
}
}
// private void readObject(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
// objectInputStream.defaultReadObject();
//
// this.value = "READ_OBJECT";
// }
// private Object readResolve() {
// return Foo.INSTANCE;
// }
}
```
|
```package Chap6_EnumTypeAndAnnotation.item37;
import Chap6_EnumTypeAndAnnotation.item35.Ensemble;
import org.junit.jupiter.api.Test;
class CustomContainerTest {
@Test
void name() {
CustomContainer<LifeCycle> customContainer = new CustomContainer<>(LifeCycle.ANNUAL, LifeCycle.BIENNIAL);
customContainer.hi();
customContainer.t(LifeCycle.PERNNIAL, Ensemble.TRIO);
}
}
```
|
Please help me generate a test for this class.
|
```package Chap6_EnumTypeAndAnnotation.item37;
public class CustomContainer<K extends Enum<K>> {
public K[] universe;
public CustomContainer(K... hi) {
this.universe = hi;
}
public void t(Enum... a) {
universe[0] = (K) a[0];
universe[1] = (K) a[1];
}
public void hi() {
System.out.println(universe);
}
}
```
|
```package Chap7_LambdaAndStream.item47;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class SubLists {
public static <E> Stream<List<E>> of(List<E> list) {
return Stream.concat(Stream.of(Collections.emptyList()), // EMPTY_LIST๋ก ํ๋ฉด unchecked, ํ๋ณํ๊น์ง ํด์ฃผ๋ emptyList() ์ฐ์
prefixes(list)
.flatMap(SubLists::suffixes));
}
// (a, b, c)
public static <E> Stream<List<E>> prefixes(List<E> list) {
return IntStream.rangeClosed(1, list.size()) // list.size() ํฌํจ
.mapToObj(end -> list.subList(0, end)); // (a) (a, b) (a, b, c)
}
// (a, b, c)
public static <E> Stream<List<E>> suffixes(List<E> list) {
return IntStream.rangeClosed(0, list.size()) // list.size() ํฌํจ
.mapToObj(start -> list.subList(start, list.size())); // (a,b,c) (b,c) (c)
}
@Test
void test() {
of(Arrays.asList("a", "b", "c"));
}
}
```
|
Please help me generate a test for this class.
|
```package Chap12_Serialization.item86.proxy;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
public class ProxySub extends Super implements Serializable {
private int subValue;
public ProxySub(final int subValue) {
super(subValue - 1);
this.subValue = subValue;
}
public int getSubValue() {
return subValue;
}
//์ง๋ ฌํ ํ๊ธฐ์ ๋ฐ๊นฅ ํด๋์ค๋ฅผ ๋ด๋ถ ์ง๋ ฌํ ํ๋ก์ ํด๋์ค๋ก ๋ณํ
private Object writeReplace() {
return new SerializationProxy(this);
}
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("ํ๋ก์๊ฐ ํ์ํฉ๋๋ค.");
}
private static class SerializationProxy implements Serializable {
private static final long serialVersionUID = 12341515436436L;
private int subValue;
public SerializationProxy(ProxySub proxySub) {
this.subValue = proxySub.subValue;
}
//์ญ์ง๋ ฌํ ์ ๋ฐ๊นฅ ํด๋์ค๋ก ๋ฐํ
private Object readResolve() {
return new ProxySub(subValue);
}
}
}
```
|
```package Chap6_EnumTypeAndAnnotation.item34;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class OperationTest {
@DisplayName("์์๋ณ ๋ฉ์๋ ๊ตฌํ์ ์ถ์ ๋ฉ์๋๋ฅผ ์์์ ๋ง๊ฒ ์ฌ์ ์ํ์ฌ ์ฌ์ฉํ ์ ์๊ฒํ๋ค.")
@Test
void name() {
int x = 8;
int y = 4;
assertThat(Operation.PLUS.apply(x, y)).isEqualTo(12);
assertThat(Operation.MINUS.apply(x, y)).isEqualTo(4);
}
@DisplayName("์ด๊ฑฐ ํ์
์ valueOf ๋ฉ์๋๋ ์์ ์ด๋ฆ์ ๋ง๋ ์ด๊ฑฐ ํ์
๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ค.")
@Test
void name1() {
assertThat(Operation.valueOf("PLUS")).isEqualTo(Operation.PLUS);
}
@DisplayName("fromString ๋ฉ์๋๋ ์ฐ์ฐ์ ๊ธฐํธ์ ๋ง๋ ์ด๊ฑฐ ํ์
๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ค.")
@Test
void name2() {
assertThat(Operation.fromString("-").get()).isEqualTo(Operation.MINUS);
}
@Test
void name3() {
assertThat(Operation.PLUS.fromString2("*")).isEqualTo(Operation.TIMES);
}
@Test
void name4() {
assertThat(Operation.fromString("*")).isEqualTo(Operation.TIMES);
}
}
```
|
Please help me generate a test for this class.
|
```package Chap6_EnumTypeAndAnnotation.item34;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public enum Operation {
PLUS("+") {
public double apply(double x, double y) {
return x + y;
}
},
MINUS("-") {
public double apply(double x, double y) {
return x - y;
}
},
TIMES("*") {
public double apply(double x, double y) {
return x * y;
}
},
DIVDE("/") {
public double apply(double x, double y) {
return x / y;
}
};
private static final Map<String, Operation> s = new HashMap<>();
private static final int VALUE = 1;
private static final Map<String, Operation> stringToEnum =
Stream.of(Operation.values())
.collect(Collectors.toMap(Operation::toString, operation -> operation));
private final String symbol;
private final Map<String, Operation> test = new HashMap<>();
// static {
// for (Operation operation : values()) {
// test.put(operation.symbol,operation);
// }
// System.out.println("static ํ๋");
// }
Operation(String symbol) {
this.symbol = symbol;
putString(symbol, this);
}
public static Operation fromString2(String symbol) {
return s.get(symbol);
}
public static Optional<Operation> fromString(String symbol) {
return Optional.ofNullable(stringToEnum.get(symbol));
}
public static Operation inverse(Operation operation) {
switch (operation) {
case PLUS:
return Operation.MINUS;
case MINUS:
return Operation.PLUS;
case TIMES:
return Operation.DIVDE;
case DIVDE:
return Operation.TIMES;
}
throw new AssertionError("์ ์ ์๋ ์ฐ์ฐ : " + operation);
}
@Override
public String toString() {
return symbol;
}
public void putString(String symbol, Operation operation) {
stringToEnum.put(symbol, operation);
}
public abstract double apply(double x, double y);
}
```
|
```package Chap12_Serialization.item89.readresolve;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Base64;
import java.util.Date;
import static org.assertj.core.api.Assertions.assertThat;
class PeriodTest {
@DisplayName("readResolve๊ฐ readObject๋ฅผ ๋ฎ์ด ์ฐ๋ ๊ฒฐ๊ณผ๋ฅผ ๋ด๋๋๋ค.")
@Test
void name() throws IOException, ClassNotFoundException {
byte[] serializedPeriodBytes;
Period period = new Period(new Date(1), new Date(2));
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(period);
serializedPeriodBytes = baos.toByteArray();
}
}
byte[] deserializedPeriodBytes = Base64.getDecoder().decode(Base64.getEncoder().encodeToString(serializedPeriodBytes));
Period deserializedPeriod;
try (ByteArrayInputStream bais = new ByteArrayInputStream(deserializedPeriodBytes)) {
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
Object objectMember = ois.readObject();
deserializedPeriod = (Period) objectMember;
}
}
assertThat(deserializedPeriod).isNotEqualTo(period);
assertThat(deserializedPeriod).isEqualTo(Period.INSTANCE);
}
}```
|
Please help me generate a test for this class.
|
```package Chap12_Serialization.item89.readresolve;
import lombok.Getter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Date;
@Getter
public class Period implements Serializable {
public static final transient Period INSTANCE = new Period(new Date(0), new Date(0));
private transient Date start;
private transient Date end;
public Period(final Date start, final Date end) {
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
}
private void readObject(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
objectInputStream.defaultReadObject();
System.out.println("READ OBJECT");
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
}
private Object readResolve() {
return Period.INSTANCE;
}
}
```
|
```package Chap5_Generic.item30;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class ToStringTest {
@DisplayName("ToString Test")
@Test
void toStringTest() {
Car car = new Car();
assertThat(ToString.identityFunction().apply(car)).isEqualTo(car.toString());
}
class Car {
private String name = "this is car";
@Override
public String toString() {
return "Car{" +
"name='" + name + '\'' +
'}';
}
}
}
```
|
Please help me generate a test for this class.
|
```package Chap5_Generic.item30;
import java.util.function.UnaryOperator;
public class ToString {
private static UnaryOperator<Object> IDENTITY_FN = Object::toString;
@SuppressWarnings("unchecked")
public static <T> UnaryOperator<T> identityFunction() {
return (UnaryOperator<T>) IDENTITY_FN;
}
}
```
|
```package Chap6_EnumTypeAndAnnotation.item37;
import Chap6_EnumTypeAndAnnotation.item35.Ensemble;
import org.junit.jupiter.api.Test;
import java.util.EnumMap;
import java.util.Map;
class LifeCycleTest {
@Test
void name() {
test(Ensemble.TRIO);
}
public <K extends Enum<K>> void test(Enum... enumerate) {
Map<LifeCycle, String> map = new EnumMap<LifeCycle, String>(LifeCycle.class);
map.put((LifeCycle) enumerate[0], "hi");
}
}
```
|
Please help me generate a test for this class.
|
```package Chap6_EnumTypeAndAnnotation.item37;
public enum LifeCycle {
ANNUAL, PERNNIAL, BIENNIAL
}
```
|
```package Chap6_EnumTypeAndAnnotation.item36;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class TextTest {
@DisplayName("Collections์ unmodifiableSet ๋ฉ์๋๋ฅผ ์ด์ฉํ์ฌ ๋ถ๋ณ EnumSet์ ๋ง๋ค ์ ์๋ค.")
@Test
void name() {
Set unmodifiableSet = Collections.unmodifiableSet(EnumSet.of(Text.Style.BOLD, Text.Style.UNDERLINE));
assertThatThrownBy(() -> unmodifiableSet.add(Text.Style.ITALIC))
.isInstanceOf(UnsupportedOperationException.class);
}
}
```
|
Please help me generate a test for this class.
|
```package Chap6_EnumTypeAndAnnotation.item36;
import java.util.Set;
public class Text {
public void applyStyles(Set<Style> styles) {
// applyStyles(EnumSet.of(Style.BOLD, Style.UNDERLINE));
}
public enum Style {
BOLD, ITALIC, UNDERLINE, STRIKETHROUGH
}
}
```
|
```package Chap3_CommonMethodOfObject.item14.point.view;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class PointTest {
@DisplayName("๊ตฌ์ฒด ํด๋์ค์ธ Point ์ ์ผ๋ฐ ๊ท์ฝ์ ์งํฌ ์ ์๋ค.")
@Test
void test() {
Point point = new Point(1, 3);
ColorPoint colorPoint = new ColorPoint(new Point(1, 2), 1);
assertThat(point.compareTo(colorPoint.asPoint())).isEqualTo(1);
assertThat(colorPoint.asPoint().compareTo(point)).isEqualTo(-1);
}
}
```
|
Please help me generate a test for this class.
|
```package Chap3_CommonMethodOfObject.item14.point.view;
public class Point implements Comparable<Point> {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point point) {
int result = Integer.compare(x, point.x);
if (result == 0) {
return Integer.compare(y, point.y);
}
return result;
}
}
/**
* ์ถ์ํ์ ์ด์ ์ ํฌ๊ธฐํ๊ณ view ๋ฉ์๋(asPoint)๋ฅผ ์ ๊ณตํ์ฌ compareTo์ ์ผ๋ฐ ๊ท์ฝ์ ์งํฌ ์ ์๋ค.
*/
class ColorPoint implements Comparable<ColorPoint> {
private Point point;
private int color;
public ColorPoint(Point point, int color) {
this.point = point;
this.color = color;
}
public Point asPoint() {
return point;
}
@Override
public int compareTo(ColorPoint colorPoint) {
int result = point.compareTo(colorPoint.point);
if (result == 0) {
return Integer.compare(color, colorPoint.color);
}
return result;
}
}
```
|
```package Chap4_ClassAndInterface.item17;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
/**
* Created by jyami on 2020/02/22
*/
class BigBigIntegerTest {
@Test
void unReliableMethod() {
BigInteger bigInteger = new BigBigInteger("1234");
assertThat(bigInteger.getClass()).isNotEqualTo(BigInteger.class);
assertThat(bigInteger.getClass()).isEqualTo(BigBigInteger.class);
}
}
```
|
Please help me generate a test for this class.
|
```package Chap4_ClassAndInterface.item17;
import java.math.BigInteger;
/**
* Created by jyami on 2020/02/22
*/
public class BigBigInteger extends BigInteger {
// BigInteger ํ์ ํธํ์ฑ์ผ๋ก ์ธํ ๋ณด์ ๋ฌธ์
private int number;
public BigBigInteger(String val) {
super(val);
}
@Override
public BigInteger add(BigInteger val) {
number = number + val.bitCount(); // ๊ฐ๋ณ์ํ ๋ณ์
return super.add(val); // ๋ถ๋ณ์ํ์
}
}
```
|
```package Chap5_Generic;
import Chap5_Generic.item29.ArrayStack;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class ArrayStackTest {
@DisplayName("Object๋ฆฌ์คํธํ์
์ ์คํ์ ๋งค๋ฒ ํ๋ณํ์ด ํ์ํ๋ค")
@Test
void basExample() {
Bad bad = new Bad("BadExample1");
ArrayStack arrayStack = new ArrayStack();
arrayStack.push(bad);
// Bad findBad = arrayStack.pop(); CompileError!
// String maybeBad = (String) arrayStack.pop(); RunTimeError!
}
class Bad {
private String value;
public Bad(String value) {
this.value = value;
}
}
}
```
|
Please help me generate a test for this class.
|
```package Chap5_Generic.item29;
public class ArrayStack {
private Object[] elements;
private int size;
public ArrayStack() {
this.elements = new Object[10];
}
public void push(Object obj) {
elements[size++] = obj;
}
public Object pop() {
if (size == 0) {
throw new IllegalArgumentException("์คํ์ ์๋ฌด๊ฒ๋ ์์ต๋๋ค");
}
Object result = elements[--size];
elements[size] = null;
return result;
}
}
```
|
```package Chap3_CommonMethodOfObject.item14.relation;
import Chap3_CommonMethodOfObject.item14.relation.MyInteger.CompareMyInteger;
import Chap3_CommonMethodOfObject.item14.relation.MyInteger.RelationalMyInteger;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* ์ ์ํ ๊ธฐ๋ณธํ์
ํ๋๊ฐ ๊ด๊ณ์ฐ์ฐ์๋ฅผ ์ด์ฉํ์ฌ ๋น๊ต๋ฅผ ํ๋๊ฒฝ์ฐ == ์ฐ์ฐ์๋ ์์ ์๋์น ์์ ๊ฒฐ๊ณผ๊ฐ ์ ๋ฐ๋ ์ ์๋ค.
*/
class MyIntegerTest {
@DisplayName("compare ๋ก ๋น๊ตํ๋ฉด NullPointerException ์ด ๋ฐ์ํ๋ค.")
@Test
void compareTo1() {
CompareMyInteger compareMyInteger1 = new CompareMyInteger();
CompareMyInteger compareMyInteger2 = new CompareMyInteger();
assertThatThrownBy(() -> compareMyInteger1.compareTo(compareMyInteger2))
.isInstanceOf(NullPointerException.class);
}
@DisplayName("๊ด๊ณ์ฐ์ฐ์๋ก ๋น๊ตํ๋ฉด ๋ ๊ฐ์ฒด์ ๋น๊ต ํ๋๊ฐ null ์ผ๋ ์๋์น ์์ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ์ ์ํฌ ์ ์๋ค.")
@Test
void compareTo2() {
RelationalMyInteger relationalMyInteger1 = new RelationalMyInteger();
RelationalMyInteger relationalMyInteger2 = new RelationalMyInteger();
assertThat(relationalMyInteger1.compareTo(relationalMyInteger2)).isEqualTo(0);
}
}
```
|
Please help me generate a test for this class.
|
```package Chap3_CommonMethodOfObject.item14.relation;
public class MyInteger {
public static class CompareMyInteger implements Comparable<CompareMyInteger> {
private Integer integer;
@Override
public int compareTo(CompareMyInteger compareMyInteger) {
return Integer.compare(integer, compareMyInteger.integer);
}
}
public static class RelationalMyInteger implements Comparable<RelationalMyInteger> {
private Integer integer;
@Override
public int compareTo(RelationalMyInteger relationalMyInteger) {
if (integer == relationalMyInteger.integer) {
return 0;
}
if (integer > relationalMyInteger.integer) {
return 1;
} else {
return -1;
}
}
}
}
```
|
```package Chap3_CommonMethodOfObject.item14.point.extend;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class PointTest {
@DisplayName("์ฌ๋ฐ๋ฅธ ๋ค์ด ์บ์คํ
์ผ๋๋ ์ผ๋ฐ ๊ท์ฝ์ ์งํค๋ฉฐ ๋์ํ๋ ๊ฒ ์ฒ๋ผ ๋ณด์ธ๋ค.")
@Test
void test() {
Point point = new ColorPoint(1, 2, 4);
ColorPoint colorPoint = new ColorPoint(1, 2, 3);
assertThat(point.compareTo(colorPoint)).isEqualTo(1);
assertThat(colorPoint.compareTo(point)).isEqualTo(-1);
}
@DisplayName("์๋ชป๋ ๋ค์ด ์บ์คํ
์ผ๋ก ClassCastException ์ด ๋ฐ์ํ๋ค.")
@Test
void test1() {
Point point = new Point(1, 2);
ColorPoint colorPoint = new ColorPoint(1, 2, 3);
assertThat(point.compareTo(colorPoint)).isEqualTo(0);
assertThatThrownBy(() -> colorPoint.compareTo(point))
.isInstanceOf(ClassCastException.class);
}
}
```
|
Please help me generate a test for this class.
|
```package Chap3_CommonMethodOfObject.item14.point.extend;
public class Point implements Comparable<Point> {
protected Integer x;
protected Integer y;
public Point(Integer x, Integer y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point point) {
int result = Integer.compare(x, point.x);
if (result == 0) {
return Integer.compare(y, point.y);
}
return result;
}
}
/**
* ๊ธฐ๋ฐ ํด๋์ค๋ฅผ ์์๋ฐ์ ๊ตฌํ ํด๋์ค๊ฐ ๊ฐ ์ปดํฌ๋ํธ๋ฅผ ์ถ๊ฐํ์๋ ์ผ๋ฐ ๊ท์ฝ์ ์งํฌ์ ์๊ฒ๋๋ค.
* compareTo๋ type casting ์ด ๋ถํ์ํ๋ค.
* ์๋ชป๋ ์ฌ์ ์๋ฅผ ๊ตฌํํ ์์ ์ด๋ค.
*/
class ColorPoint extends Point implements Comparable<Point> {
private Integer color;
public ColorPoint(Integer x, Integer y, Integer color) {
super(x, y);
this.color = color;
}
@Override
public int compareTo(Point point) {
int result = super.compareTo(point);
if (result == 0) {
return Integer.compare(color, ((ColorPoint) point).color); // ์๋ชป๋ ๊ตฌํ
}
return result;
}
}
```
|
```package Chap5_Generic.item30;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static Chap5_Generic.item30.LottePayCard.Sale.LOTTE_DEPT;
class LottePayCardTest {
@DisplayName("์๋ฎฌ๋ ์ดํธํ ์
ํํ์
๊ด์ฉ๊ตฌ")
@Test
void simulate() {
LottePayCard lottePayCard = new LottePayCard.Builder(LOTTE_DEPT)
.addBenefit(PayCard.Benefit.POINT)
.build();
}
}
```
|
Please help me generate a test for this class.
|
```package Chap5_Generic.item30;
public class LottePayCard extends PayCard {
private final Sale sale;
LottePayCard(Builder builder) {
super(builder);
sale = builder.sale;
}
public enum Sale {
LOTTE_WORLD("๋กฏ๋ฐ์๋"), LOTTE_DEPT("๋กฏ๋ฐ๋ฐฑํ์ ");
Sale(String sale) {
}
}
public static class Builder extends PayCard.Builder<Builder> {
private final Sale sale;
public Builder(Sale sale) {
this.sale = sale;
}
@Override
LottePayCard build() {
return new LottePayCard(this);
}
@Override
protected Builder self() {
return this;
}
}
}
```
|
```package Chap12_Serialization.item86.readNoData;
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;
class SubTest {
// Sub sub = new Sub("3.0.2");
//
// ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(SOURCE));
// outputStream.writeObject(sub);
// outputStream.close();
private static final String SOURCE = "./src/test/java/Chap12_Serialization/item86/readNoData/serializeSub.txt";
@Test
void name() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(SOURCE));
Sub deserialized = (Sub) objectInputStream.readObject();
objectInputStream.close();
assertAll(
() -> assertThat(deserialized.version).isEqualTo("3.0.2"),
() -> assertThat(deserialized.defaultVersion).isEqualTo("1.0.0")
);
}
}```
|
Please help me generate a test for this class.
|
```package Chap12_Serialization.item86.readNoData;
import java.io.Serializable;
public class Sub extends Super implements Serializable {
String version;
public Sub(final String version) {
this.version = version;
}
}
```
|
```package Chap4_ClassAndInterface.item19;
import org.junit.jupiter.api.Test;
class SubTest {
@Test
void name() {
Sub sub = new Sub();
}
}
```
|
Please help me generate a test for this class.
|
```package Chap4_ClassAndInterface.item19;
public class Sub extends Super{
private String str;
public Sub() {
str = "Sub String";
}
@Override
public void overrideMe() {
System.out.println(str);
}
public static void main(String[] args) {
Sub sub = new Sub();
sub.overrideMe();
}
}
```
|
```package com.javabom.toby.chapter6.term;
import com.javabom.toby.chapter6.term.AopTestInterface;
import com.javabom.toby.chapter6.term.AopUserService;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
class AopUserServiceTest {
@DisplayName("ํํ์์ผ๋ก ํฌ์ธํธ์ปท์ ์ง์ ํ ์ ์๋ค")
@Test
void methodSignature() throws NoSuchMethodException {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("execution(* hello(..))");
/**
* ํฌ์ธํธ์ปท์ ํด๋์คํํฐ์ ๋งค์๋๋งค์ฒ๋ฅผ ๋๋ค ์ง์ ํ ์ ์๋ค.
*/
assertThat(pointcut.getClassFilter().matches(AopUserService.class)).isTrue();
assertThat(pointcut.getMethodMatcher().matches(AopUserService.class.getMethod("bye"), AopUserService.class)).isFalse();
}
@DisplayName("ํฌ์ธํธ์ปท์ผ๋ก ์ธํฐํ์ด์ค๋ฅผ ์ง์ ํ๋ฉด ํด๋น ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ ๋ฉ์๋๋ง ์ ์ฉ๋๋ค")
@Test
void interfacePointcut() throws NoSuchMethodException {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("execution(* *..AopTestInterface.*(..))");
assertThat(pointcut.getClassFilter().matches(AopUserService.class)).isTrue();
assertThat(pointcut.getMethodMatcher().matches(AopUserService.class.getMethod("test"), AopUserService.class)).isTrue();
assertThat(pointcut.getMethodMatcher().matches(AopUserService.class.getMethod("hello"), AopUserService.class)).isFalse();
}
@DisplayName("ํฌ์ธํธ์ปท ํํ์์ ํด๋์ค ์ด๋ฆ์ ์ ์ฉ๋๋ ํจํด์ ํ์
ํจํด์ด๋ค")
@Test
void typePattern() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("execution(* *..AnotherAopUserService.*(..))");
assertThat(pointcut.getClassFilter().matches(AopUserService.class)).isTrue();
}
@Test
void advice() {
AbstractApplicationContext ctx =
new ClassPathXmlApplicationContext("classpath:applicationContext-test.xml");
AopTestInterface aopUserService = ctx.getBean("aopUserService", AopTestInterface.class);
aopUserService.test();
}
}
```
|
Please help me generate a test for this class.
|
```package com.javabom.toby.chapter6.term;
import org.springframework.stereotype.Service;
@Service(value = "aopUserService")
public class AopUserService implements AopTestInterface {
public void hello() {
System.out.println("Hello!");
}
public void bye() {
System.out.println("bye~!");
}
@Override
public void test() {
System.out.println("Test");
}
}
```
|
```package Chap5_Generic.item32;
import org.junit.jupiter.api.Test;
/**
* Created by jyami on 2020/04/05
*/
class DontSaveTest {
@Test
void hello() {
DontSave.hello(1, 2);
}
}
```
|
Please help me generate a test for this class.
|
```package Chap5_Generic.item32;
/**
* Created by jyami on 2020/04/05
*/
public class DontSave {
public static void hello(Object... objects){
objects[0] = 1;
objects[1] = "String";
}
}
```
|
```package Chap5_Generic.item33;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by jyami on 2020/04/05
*/
class FavoritesTest {
@Test
void name() {
Favorites favorites = new Favorites();
favorites.putFavorite((Class) Integer.class, "Integer์ธํ
String instance๋ก ๋๊ฒจ ๋ณด์!");
favorites.getFavorite(Integer.class);
}
@Test
@DisplayName("HashSet Raw Type")
void name2() {
HashSet<Integer> set = new HashSet<>();
((HashSet) set).add("๋ฌธ์์ด ์
๋๋ค.");
}
@Test
@DisplayName("HashSet Raw Type")
void name3() {
HashSet<Integer> set = new HashSet<>();
((HashSet)set).add("๋ฌธ์์ด ์
๋๋ค.");
boolean contains1 = ((HashSet) set).contains("๋ฌธ์์ด ์
๋๋ค.");
assertThat(contains1).isTrue();
boolean contains = set.contains("๋ฌธ์์ด ์
๋๋ค.");
assertThat(contains).isTrue();
}
}
```
|
Please help me generate a test for this class.
|
```package Chap5_Generic.item33;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* Created by jyami on 2020/04/05
*/
public class Favorites {
private Map<Class<?>, Object> favorites = new HashMap<>();
public <T> void putFavorite(Class<T> type, T instance) {
favorites.put(Objects.requireNonNull(type), instance);
}
public <T> T getFavorite(Class<T> type) {
return type.cast(favorites.get(type));
}
// // Achieving runtime type safety with a dynamic cast
// public <T> void putFavorite(Class<T> type, T instance) {
// favorites.put(Objects.requireNonNull(type), type.cast(instance));
// }
public static void main(String[] args) {
Favorites f = new Favorites();
f.putFavorite(String.class, "Java");
f.putFavorite(Integer.class, 0xcafebabe);
f.putFavorite(Class.class, Favorites.class);
String favoriteString = f.getFavorite(String.class);
int favoriteInteger = f.getFavorite(Integer.class);
Class<?> favoriteClass = f.getFavorite(Class.class);
System.out.printf("%s %x %s%n", favoriteString,
favoriteInteger, favoriteClass.getName());
}
}
```
|
```package Chap12_Serialization.item88;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Base64;
import java.util.Date;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class ObjectInputValidationTest {
@DisplayName("ObjectInputValidation์ ์ด์ฉํด์ ์๋ชป๋ ์ง๋ ฌํ ๊ฐ์ ํํฐ๋งํ ์ ์๋ค.")
@Test
void name() throws IOException {
byte[] serializedValidationBytes;
//start๊ฐ end ๋ณด๋ค ๋ ๋ค์ ์๋ ์๋ชป๋ ๊ฐ์ฒด์ ์ง๋ ฌํ ๋ฐ์ดํธ๊ฐ ์๋ค๊ณ ๊ฐ์ ํ๋ค๋ฉด
ObjectInputValidation objectInputValidation = new ObjectInputValidation(new Date(2), new Date(1));
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(objectInputValidation);
serializedValidationBytes = baos.toByteArray();
}
}
byte[] deserializedValidationBytes = Base64.getDecoder().decode(Base64.getEncoder().encodeToString(serializedValidationBytes));
try (ByteArrayInputStream bais = new ByteArrayInputStream(deserializedValidationBytes)) {
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
// readObject ํ๋ ๋จ๊ณ์์ register ํ validation์ ๊ฑธ๋ฆฐ๋ค.
assertThatThrownBy(ois::readObject)
.isInstanceOf(IllegalArgumentException.class);
}
}
}
}```
|
Please help me generate a test for this class.
|
```package Chap12_Serialization.item88;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Date;
public class ObjectInputValidation implements Serializable {
private Date start;
private Date end;
public ObjectInputValidation(final Date start, final Date end) {
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
// ์๋์ ๊ฐ์ ์ฝ๋๊ฐ ์ฃผ์์ฒ๋ฆฌ๊ฐ ๋์ด ์์ง ์๋ค๊ณ ๊ฐ์ ํ ๋
// if (start.getTime() > end.getTime()) {
// throw new IllegalArgumentException();
// }
}
private void readObject(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
objectInputStream.defaultReadObject();
objectInputStream.registerValidation(
() -> {
if (start.getTime() > end.getTime()) {
throw new IllegalArgumentException();
}
}
, 0);
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
}
}
```
|
```package Chap6_EnumTypeAndAnnotation.item34;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class PlanetTest {
@DisplayName("์ด๊ฑฐ ํ์
์ values ๋ฉ์๋๋ ์์ ์ ์์๋ค์ ๋ฐฐ์ด์ ๋ด์ ๋ฐํํ๋ค.")
@Test
void name() {
Planet[] planets = Planet.values();
assertThat(planets.length).isEqualTo(8);
assertThat(planets[0]).isEqualTo(Planet.MERCURY);
}
@DisplayName("์ด๊ฑฐ ํ์
์ toString ๋ฉ์๋๋ ์ฌ์ ์ ํ์ฌ ์ฌ์ฉํ ์ ์๋ค.")
@Test
void name1() {
assertThat(Planet.JUPITER.toString()).isEqualTo("jupiter");
}
}
```
|
Please help me generate a test for this class.
|
```package Chap6_EnumTypeAndAnnotation.item34;
public enum Planet {
MERCURY(3.302e+23, 2.439e6),
VENUS(4.869e+24, 6.052e6),
EARTH(5.975e+24, 6.378e6),
MARS(6.419e+23, 3.393e6),
JUPITER(1.899e+27, 7.149e7),
SATURN(5.685e+26, 6.027e7),
URAUS(8.683e+25, 2.556e7),
NEPTUNE(1.024e+26, 2.477e7);
//์ค๋ ฅ์์
private static final double G = 6.67300E-11;
private final double mass;
private final double radius;
//ํ๋ฉด์ค๋ ฅ
private final double surfaceGravity;
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
this.surfaceGravity = G * mass / (radius * radius);
}
public double mass() {
return mass;
}
public double radius() {
return radius;
}
public double surfaceGravity() {
return surfaceGravity;
}
public double surfaceWeight(double mass) {
return mass * surfaceGravity;
}
@Override
public String toString() {
return this.name().toLowerCase();
}
}
```
|
```package Chap6_EnumTypeAndAnnotation.item35;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class EnsembleTest {
@DisplayName("์ด๊ฑฐ ํ์
์ ordinal ๋ฉ์๋๋ ์ด๊ฑฐ ํ์
์์์ ์ ์ธ ์์น๋ฅผ ๋ฐํํ๋ค.")
@Test
void name() {
assertThat(Ensemble.TRIO.ordinal()).isEqualTo(2);
}
}
```
|
Please help me generate a test for this class.
|
```package Chap6_EnumTypeAndAnnotation.item35;
public enum Ensemble {
SOLO, DUET, TRIO, QUARTET, QUINTET,
SEXTET, SEPTET, OCTET, NONET, DECTET;
}
```
|
```package Chap4_ClassAndInterface.item17;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
/**
* Created by jyami on 2020/02/22
*/
class AlbumTest {
@Test
void titleChange() {
Album album = new Album("์จ๋ฒํ์ดํ");
album.getTitle().name = "์จ๋ฒํ์ดํ ๋ณ๊ฒฝ";
assertThat(album.getTitle().name).isEqualTo("์จ๋ฒํ์ดํ ๋ณ๊ฒฝ");
}
}
```
|
Please help me generate a test for this class.
|
```package Chap4_ClassAndInterface.item17;
/**
* Created by jyami on 2020/02/22
*/
public class Album {
private final Title title;
public Album(String title) {
this.title = new Title(title);
}
public Title getTitle() {
return title;
}
static class Title {
String name;
public Title(String name) {
this.name = name;
}
}
}
```
|
```package Chap6_EnumTypeAndAnnotation.item39.repeatable;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import static org.assertj.core.api.Java6Assertions.assertThat;
class RepeatableTest {
@DisplayName("๋๊ฐ์ด์, ๋ฐ๋ณต๊ฐ๋ฅ ์ ๋ํ
์ด์
์ด ๋ฌ๋ ค์๋ค๋ฉด Container๋ฅผ ์ธ์ํ๋ค.")
@Test
void name() throws NoSuchMethodException {
//given
Method repeatAnnotationMethod = Repeatable.class.getMethod("repeatAnnotationMethod");
//when
boolean annotationPresent = repeatAnnotationMethod.isAnnotationPresent(java.lang.annotation.Repeatable.class);
boolean exceptionTestAnnotationPresent = repeatAnnotationMethod.isAnnotationPresent(ExceptionTest.class);
boolean exceptionTestContainerAnnotationPresent = repeatAnnotationMethod.isAnnotationPresent(ExceptionTestContainer.class);
//then
assertThat(repeatAnnotationMethod).isNotNull();
assertThat(annotationPresent).isFalse();
assertThat(exceptionTestAnnotationPresent).isFalse();
assertThat(exceptionTestContainerAnnotationPresent).isTrue();
}
@DisplayName("๋จ ํ๊ฐ์ ๋ฐ๋ณต๊ฐ๋ฅ ์ ๋ํ
์ด์
์ด ๋ฌ๋ ค์๋ค๋ฉด Container๋ฅผ ์ธ์ํ์ง ์๋๋ค..")
@Test
void name2() throws NoSuchMethodException {
//given
Method notRepeatAnnotationMethod = Repeatable.class.getMethod("notRepeatAnnotationMethod");
//when
boolean annotationPresent = notRepeatAnnotationMethod.isAnnotationPresent(java.lang.annotation.Repeatable.class);
boolean exceptionTestAnnotationPresent = notRepeatAnnotationMethod.isAnnotationPresent(ExceptionTest.class);
boolean exceptionTestContainerAnnotationPresent = notRepeatAnnotationMethod.isAnnotationPresent(ExceptionTestContainer.class);
//then
assertThat(notRepeatAnnotationMethod).isNotNull();
assertThat(annotationPresent).isFalse();
assertThat(exceptionTestAnnotationPresent).isTrue();
assertThat(exceptionTestContainerAnnotationPresent).isFalse();
}
}```
|
Please help me generate a test for this class.
|
```package Chap6_EnumTypeAndAnnotation.item39.repeatable;
public class Repeatable {
@ExceptionTest(IllegalArgumentException.class)
@ExceptionTest(NullPointerException.class)
public void repeatAnnotationMethod() {
}
@ExceptionTest(IllegalArgumentException.class)
public void notRepeatAnnotationMethod() {
}
}
```
|
```package Chap3_CommonMethodOfObject.item11;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
class PhoneNumberTest {
@Test
@DisplayName("eqauls๋ง ์ฌ์ ์ํด์ ์ฐธ์ ๋ฐํํ๋ค.")
void name() {
PhoneNumber phoneNumber = new PhoneNumber(1,2,3);
PhoneNumber phoneNumber1 = new PhoneNumber(1,2,3);
assertThat(phoneNumber.equals(phoneNumber1)).isTrue();
}
@Test
@DisplayName("eqauls๋ง ์ฌ์ ์ํด์ hashMap์ ๋ฃ์ผ๋ฉด ์๋ก๋ค๋ฅธ๊ฐ์ ๋ฐํํ๋ค.")
void name2() {
PhoneNumber phoneNumber = new PhoneNumber(1,2,3);
PhoneNumber phoneNumber1 = new PhoneNumber(1,2,3);
Map<PhoneNumber,String> map = new HashMap<>();
map.put(phoneNumber,"์ ์ฑ");
map.put(phoneNumber1,"๋ฏผํ");
assertThat(phoneNumber.hashCode() == phoneNumber1.hashCode()).isFalse();
assertThat(map.get(phoneNumber)).isEqualTo("์ ์ฑ");
assertThat(map.get(phoneNumber1)).isEqualTo("๋ฏผํ");
}
@Test
@DisplayName("hashMap๋ ์ฌ์ ์ํด์ hashMap์ ๋ฃ์ผ๋ฉด ์๋ก ๊ฐ์๊ฐ์ ๋ฐํํ๋ค.")
void name3() {
PhoneNumberOverrideHash phoneNumber = new PhoneNumberOverrideHash(1,2,3);
PhoneNumberOverrideHash phoneNumber2 = new PhoneNumberOverrideHash(1,2,3);
Map<PhoneNumber,String> map = new HashMap<>();
map.put(phoneNumber,"์ ์ฑ");
map.put(phoneNumber2,"๋ฏผํ");
assertThat(phoneNumber.hashCode()).isEqualTo(phoneNumber2.hashCode());
assertThat(map.get(phoneNumber)).isEqualTo("๋ฏผํ");
assertThat(map.get(phoneNumber2)).isEqualTo("๋ฏผํ");
}
}
```
|
Please help me generate a test for this class.
|
```package Chap3_CommonMethodOfObject.item11;
public class PhoneNumber {
int areaCode;
int prefix;
int lineNum;
public PhoneNumber(int areaCode, int prefix, int lineNum) {
this.areaCode = areaCode;
this.prefix = prefix;
this.lineNum = lineNum;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PhoneNumber address = (PhoneNumber) o;
return areaCode == address.areaCode &&
prefix == address.prefix &&
lineNum == address.lineNum;
}
}
```
|
```package Chap9_GeneralProgrammingPrinciple.item64;
import org.junit.jupiter.api.Test;
class ValueObjectTest {
@Test
void name() {
ValueObject valueObject = new ValueObject();
valueObject.number();
}
}```
|
Please help me generate a test for this class.
|
```package Chap9_GeneralProgrammingPrinciple.item64;
import Chap9_GeneralProgrammingPrinciple.item64.vo.Name;
import Chap9_GeneralProgrammingPrinciple.item64.vo.Player;
public class ValueObject {
public Player makePlayer() {
Name name = new Name("Minsu");
return new Player(name);
}
public void number() {
Number number = 10000000;
Integer integer = 10000000;
}
}
```
|
```package Chap6_EnumTypeAndAnnotation.item34;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.*;
import static org.assertj.core.api.Assertions.assertThat;
class WeekDayTest {
@DisplayName("์ด๊ฑฐ ํ์
์ Comparable์ ๊ตฌํํ์๊ณ ์ด๊ฑฐ ์์๊ฐ ์ ์ธ๋ ์์๋ก ๊ฒฐ์ ํ๋ค.")
@Test
void name() {
WeekDay monday = WeekDay.MONDAY;
WeekDay monday2 = WeekDay.MONDAY;
WeekDay wednesday = WeekDay.WEDNESDAY;
assertThat(monday.compareTo(wednesday)).isEqualTo(-2);
assertThat(monday.compareTo(monday2)).isEqualTo(0);
}
@DisplayName("์ด๊ฑฐ ํ์
์ Serializable ์ ๊ตฌํํ์๋ค")
@Test
void name1() throws IOException {
WeekDay monday = WeekDay.MONDAY;
byte[] serialized = serialization(monday);
WeekDay deserialized = deserialization(serialized);
assertThat(monday).isEqualTo(deserialized);
assertThat(monday.getValue()).isEqualTo(deserialized.getValue());
assertThat(monday.getVar()).isNotEqualTo(deserialized.getVar());
}
public byte[] serialization(WeekDay weekDay) throws IOException {
byte[] serialized;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(weekDay);
serialized = baos.toByteArray();
}
}
return serialized;
}
public WeekDay deserialization(byte[] serialized) throws IOException {
WeekDay deserialized = WeekDay.TUESDAY;
try (ByteArrayInputStream bais = new ByteArrayInputStream(serialized)) {
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
Object object = ois.readObject();
deserialized = (WeekDay) object;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return deserialized;
}
}
```
|
Please help me generate a test for this class.
|
```package Chap6_EnumTypeAndAnnotation.item34;
public enum WeekDay {
MONDAY(0),
TUESDAY(1),
WEDNESDAY(2),
THURSDAY(3),
FRIDAY(4),
SATURDAY(5),
SUNDAY(6);
private final int value;
private int var;
WeekDay(int value) {
this.value = value;
this.var = 1;
}
public int getValue() {
return value;
}
public int getVar() {
return var;
}
public void setVar(int var) {
this.var = var;
}
public void printHi() {
System.out.println("Hi! This is " + this.name());
}
}
```
|
```package Chap8_Method.item55;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Java6Assertions.assertThat;
class MemberRepositoryTest {
@DisplayName("orElse ๋ Optional์ ๊ฐ๊ณผ ๊ด๊ณ ์์ด ์คํ๋๋ค.")
@Test
void orElseExample() {
//given
MemberRepository memberRepository = new MemberRepository();
Member member = new Member("๋ฐ์ฐฌ์ธ");
memberRepository.save(member);
//when
Member persistMember = memberRepository.findByName(member.getName())
.orElse(memberRepository.save(member));
//then
List<Member> memberList = memberRepository.findAll();
assertThat(memberList).hasSize(2);
}
@DisplayName("orElseGet ์ Optional์ ๊ฐ์ด ๋น์ด์์ด์ผ์ง ์คํ๋๋ค.")
@Test
void orElseGetExample() {
//given
MemberRepository memberRepository = new MemberRepository();
Member member = new Member("๋ฐ์ฐฌ์ธ");
memberRepository.save(member);
//when
Member persistMember = memberRepository.findByName(member.getName())
.orElseGet(() -> memberRepository.save(member));
//then
List<Member> memberList = memberRepository.findAll();
assertThat(memberList).hasSize(1);
}
}```
|
Please help me generate a test for this class.
|
```package Chap8_Method.item55;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class MemberRepository {
private final Map<Long, Member> memberList = new HashMap<>();
private Long id = 0L;
public Member save(Member member) {
id++;
member.setId(id);
memberList.put(id, member);
return member;
}
public List<Member> findAll() {
return new ArrayList<>(memberList.values());
}
public Optional<Member> findByName(String name) {
return memberList.values().stream()
.filter(member -> member.getName().equals(name))
.findFirst();
}
}
```
|
```package Chap3_CommonMethodOfObject.item14.hash;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class HashObjectTest {
@DisplayName("hashCode ๋ฅผ ์ด์ฉํ ๊ฒฝ์ฐ ํ๋๊ฐ์ ์ฐ์ ์์ ๋น๊ต๊ฐ ๋ถ๊ฐ๋ฅํด ์ง๋ค.")
@Test
void compareTo() {
// ๋ ๊ฐ์ฒด ๋ชจ๋ hash ๊ฐ์ด 1024๋ก ๊ฐ๋ค.
HashObject hashObject1 = new HashObject(1, 32);
HashObject hashObject2 = new HashObject(2, 1);
assertThat(hashObject1.hashCode() == 1024).isEqualTo(hashObject2.hashCode() == 1024);
assertThat(hashObject1.compareTo(hashObject2)).isEqualTo(0);
}
}
```
|
Please help me generate a test for this class.
|
```package Chap3_CommonMethodOfObject.item14.hash;
import java.util.Objects;
public class HashObject implements Comparable<HashObject> {
private int a;
private int b;
public HashObject(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HashObject that = (HashObject) o;
return a == that.a &&
b == that.b;
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
@Override
public int compareTo(HashObject hashObject) {
System.out.println(this.hashCode());
System.out.println(hashObject.hashCode());
return Integer.compare(this.hashCode(), hashObject.hashCode());
}
}
```
|
```package Chap5_Generic.item30;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class NotImmutableMapTest {
@DisplayName("๋ถ๋ณ์ด ์๋ ํด๋์ค๋ฅผ ์ ๋ค๋ฆญ์ฑ๊ธํดํฉํฐ๋ฆฌ๋ก ์ ๊ณตํ๋ฉด ์๋๋ค.")
@Test
void generic() {
NotImmutableMap integerNotImmutableMap = NotImmutableMap.getSingleton();
integerNotImmutableMap.put("key", "123");
integerNotImmutableMap.put(123, 123);
assertThat(integerNotImmutableMap.get("key")).isEqualTo("123");
int maybeInteger = (Integer) integerNotImmutableMap.get("key"); // castException
}
}
```
|
Please help me generate a test for this class.
|
```package Chap5_Generic.item30;
import java.util.HashMap;
import java.util.Map;
public class NotImmutableMap<K, V> {
private static final NotImmutableMap SINGLETON_MAP = new NotImmutableMap<>(); // ์ฑ๊ธํด๊ฐ์ฒด
private final Map<K, V> map = new HashMap<>();
@SuppressWarnings("unchecked")
public static <K, V> NotImmutableMap<K, V> getSingleton() { // ์ ๋ค๋ฆญ
return (NotImmutableMap<K, V>) SINGLETON_MAP;
}
public void put(K key, V value) { // ๋ถ๋ณ๊นจ์ง
map.put(key, value);
}
public V get(K key) {
return map.get(key);
}
}
```
|
```package com.javabom.toby.chapter7.oxm;
import com.javabom.toby.chapter7.resource.BookResourceLoader;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.oxm.Unmarshaller;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
import java.io.InputStream;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(classes = OxmConfig.class)
class OxmConfigTest {
@Autowired
private Unmarshaller unmarshaller;
@Autowired
private BookResourceLoader bookResourceLoader;
@Test
@DisplayName("jaxb xml ์ปจ๋ฒํ
ํ
์คํธ")
void name() throws IOException {
//given
InputStream stream = getClass().getResourceAsStream("/book.xml");
Source xmlSource = new StreamSource(stream);
//when
Book book= (Book) unmarshaller.unmarshal(xmlSource);
//then
assertThat(book.getId()).isEqualTo(1L);
assertThat(book.getName()).isEqualTo("Book1");
}
@Test
void resourceTest()throws IOException {
Book book = bookResourceLoader.load();
//then
assertThat(book.getId()).isEqualTo(1L);
assertThat(book.getName()).isEqualTo("Book1");
}
}
```
|
Please help me generate a test for this class.
|
```package com.javabom.toby.chapter7.oxm;
import com.javabom.toby.chapter7.resource.BookResourceLoader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
@Configuration
public class OxmConfig {
@Bean
public Unmarshaller unmarshaller(){
Jaxb2Marshaller jaxb2Marshaller=new Jaxb2Marshaller();
jaxb2Marshaller.setPackagesToScan("com.javabom.toby.chapter7.oxm");
return jaxb2Marshaller;
}
@Bean
public BookResourceLoader bookResourceLoader(Unmarshaller unmarshaller){
return new BookResourceLoader(unmarshaller, new ClassPathResource("book.xml"));
}
}
```
|
```package Chap3_CommonMethodOfObject.item13;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;
public class SubTest {
@Test
@DisplayName("์ฌ์ ์ ๊ฐ๋ฅํ ๋ฉ์๋๋ฅผ ์์ ํด๋์ค์ clone์์ ํธ์ถํ๋ฉด ํ์ ํด๋์ค์ ๋ฉ์๋๊ฐ ์คํ๋๋ค.")
void testClone() {
Sub sub = new Sub();
assertAll(
() -> assertThat(sub.type).isEqualTo("super"),
() -> {
Sub clone = sub.clone();
assertThat(sub.type).isEqualTo("sub");
}
);
}
}
```
|
Please help me generate a test for this class.
|
```package Chap3_CommonMethodOfObject.item13;
public class Sub extends Sup {
String temp;
@Override
public void overrideMe() {
System.out.println("sub mehtod");
System.out.println(temp);
type = "sub";
}
@Override
public Sub clone() {
Sub clone = (Sub) super.clone();
clone.temp = "temp";
return clone;
}
}
```
|
```package com.amazon.sample.carts.controllers;
import com.amazon.sample.carts.controllers.api.Item;
import com.amazon.sample.carts.repositories.CartEntity;
import com.amazon.sample.carts.repositories.ItemEntity;
import com.amazon.sample.carts.services.CartService;
import com.amazon.sample.carts.util.TestUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(CartsController.class)
public class CartsControllerTests {
@Autowired
private MockMvc mockMvc;
@MockBean
private CartService service;
private final static String EMPTY_CART_ID = "123";
private final static String POPULATED_CART_ID = "456";
@BeforeEach
void setup() {
CartEntity emptyCart = mock(CartEntity.class);
when(emptyCart.getCustomerId()).thenReturn(EMPTY_CART_ID);
CartEntity populatedCart = mock(CartEntity.class);
when(populatedCart.getCustomerId()).thenReturn(POPULATED_CART_ID);
ItemEntity item = mock(ItemEntity.class);
when(item.getItemId()).thenReturn("1");
when(item.getQuantity()).thenReturn(1);
when(item.getUnitPrice()).thenReturn(150);
List<ItemEntity> items = new ArrayList<ItemEntity>();
items.add(item);
doReturn(items).when(populatedCart).getItems();
given(this.service.get(EMPTY_CART_ID)).willReturn(emptyCart);
given(this.service.get(POPULATED_CART_ID)).willReturn(populatedCart);
doNothing().when(this.service).delete(EMPTY_CART_ID);
given(this.service.add("123", "1", 1, 150)).willReturn(item);
doNothing().when(this.service).deleteItem(POPULATED_CART_ID, "1");
}
@Test
void testGetEmptyCart() throws Exception {
ResultActions actions = mockMvc.perform(get("/carts/"+EMPTY_CART_ID)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
actions.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.customerId").value(EMPTY_CART_ID))
.andExpect(jsonPath("$.items", hasSize(0)));
}
@Test
void testGetPopulatedCart() throws Exception {
ResultActions actions = mockMvc.perform(get("/carts/"+POPULATED_CART_ID)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
actions.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.customerId").value(POPULATED_CART_ID))
.andExpect(jsonPath("$.items", hasSize(1)))
.andExpect(jsonPath("$.items[0].itemId").value("1"))
.andExpect(jsonPath("$.items[0].quantity").value(1))
.andExpect(jsonPath("$.items[0].unitPrice").value(150));
}
@Test
void testDeleteCart() throws Exception {
ResultActions actions = mockMvc.perform(delete("/carts/"+EMPTY_CART_ID)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isAccepted());
actions.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
@Test
void testAddItem() throws Exception {
ResultActions actions = mockMvc.perform(post("/carts/"+EMPTY_CART_ID+"/items")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtil.convertObjectToJsonBytes(new Item("1", 1, 150)))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated());
actions.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.itemId").value("1"))
.andExpect(jsonPath("$.quantity").value(1))
.andExpect(jsonPath("$.unitPrice").value(150));
}
@Test
void testDeleteItem() throws Exception {
mockMvc.perform(delete("/carts/"+POPULATED_CART_ID+"/items/1")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.accept(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isAccepted());
}
}
```
|
Please help me generate a test for this class.
|
```package com.amazon.sample.ui.services.carts.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@AllArgsConstructor
public class Cart {
private List<CartItem> items = new ArrayList<>();
public void addItem(CartItem item) {
boolean existing = false;
for(CartItem i : items) {
if(i.getId().equals(item.getId())) {
i.addQuantity(item.getQuantity());
existing = true;
}
}
if(!existing) {
this.items.add(item);
}
}
public void removeItem(String id) {
for(CartItem i : items) {
if(i.getId().equals(id)) {
this.items.remove(i);
}
}
}
public int getSubtotal() {
int subtotal = 0;
for(CartItem i : items) {
subtotal += i.getTotalPrice();
}
return subtotal;
}
public int getTotalPrice() {
return this.getSubtotal() + this.getShipping();
}
public int getShipping() {
return this.items.size() > 0 ? 10 : 0;
}
public int getNumItems() {
int total = 0;
for(CartItem i : items) {
total += i.getQuantity();
}
return total;
}
}
```
|
```package com.amazon.sample.orders.metrics;
import com.amazon.sample.events.orders.Order;
import com.amazon.sample.events.orders.OrderCreatedEvent;
import com.amazon.sample.orders.entities.OrderItemEntity;
import io.micrometer.core.instrument.*;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.BDDAssertions.then;
public class OrdersMetricsTest {
private MeterRegistry meterRegistry;
private final String PRODUCT_1 = "Product1";
private final String PRODUCT_2 = "Product2";
@BeforeEach
void setUp() {
meterRegistry = new SimpleMeterRegistry();
Metrics.globalRegistry.add(meterRegistry);
}
@AfterEach
void tearDown() {
meterRegistry.clear();
Metrics.globalRegistry.clear();
}
@Test
void testCreateCounterAndIncrement() {
OrdersMetrics ordersMetrics = new OrdersMetrics(meterRegistry);
OrderCreatedEvent event = new OrderCreatedEvent();
Order order = new Order();
order.setEmail("test@gmail.com");
order.setFirstName("John");
order.setId("id");
order.setLastName("Doe");
List<OrderItemEntity> orderItems = new ArrayList<>();
OrderItemEntity item = new OrderItemEntity();
item.setName("Pocket Watch");
item.setQuantity(5);
item.setPrice(100);
item.setTotalCost(500);
item.setProductId(PRODUCT_1);
orderItems.add(item);
item = new OrderItemEntity();
item.setName("Wood Watch");
item.setQuantity(2);
item.setPrice(50);
item.setTotalCost(100);
item.setProductId(PRODUCT_2);
orderItems.add(item);
order.setOrderItems(orderItems);
event.setOrder(order);
ordersMetrics.onOrderCreated(event);
var counter = meterRegistry.get("watch.orders").tags("productId","*").counter();
then(counter).isNotNull();
then(counter.count()).isEqualTo(1);
var woodWatchCounter = meterRegistry.get("watch.orders").tags("productId",PRODUCT_2).counter();
then(woodWatchCounter).isNotNull();
then(woodWatchCounter.count()).isEqualTo(2);
var pocketWatchCounter = meterRegistry.get("watch.orders").tags("productId",PRODUCT_1).counter();
then(pocketWatchCounter).isNotNull();
then(pocketWatchCounter.count()).isEqualTo(5);
var watchGauge = meterRegistry.find("watch.orderTotal").gauge();
then(watchGauge).isNotNull();
then(watchGauge.value()).isEqualTo(600.0);
ordersMetrics.onOrderCreated(event);
then(watchGauge.value()).isEqualTo(1200.0);
}
}
```
|
Please help me generate a test for this class.
|
```package com.amazon.sample.orders.metrics;
import com.amazon.sample.events.orders.OrderCreatedEvent;
import com.amazon.sample.orders.entities.OrderItemEntity;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
@Component
public class OrdersMetrics {
private Counter orderCreatedCounter;
private AtomicInteger orderTotal;
private MeterRegistry meterRegistry;
private Map<String,Counter> watchCounters = new HashMap<>();
public OrdersMetrics(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
this.orderCreatedCounter = Counter.builder("watch.orders")
.tag("productId", "*")
.description("The number of orders placed")
.register(meterRegistry);
this.orderTotal = new AtomicInteger(0);
meterRegistry.gauge("watch.orderTotal", orderTotal);
}
@TransactionalEventListener
public void onOrderCreated(OrderCreatedEvent event) {
this.orderCreatedCounter.increment();
for (OrderItemEntity orderentity : event.getOrder().getOrderItems()) {
getCounter(orderentity).increment(orderentity.getQuantity());
}
int totalPrice = event.getOrder().getOrderItems().stream().map(x -> x.getTotalCost()).reduce(0, Integer::sum);
this.orderTotal.getAndAdd(totalPrice);
}
private Counter getCounter(OrderItemEntity orderentity) {
if(null == watchCounters.get(orderentity.getProductId())){
Counter counter = Counter.builder("watch.orders")
.tag("productId", orderentity.getProductId())
.register(meterRegistry);
watchCounters.put(orderentity.getProductId(),counter);
}
return watchCounters.get(orderentity.getProductId());
}
}
```
|
```package cn.aberic.fabric.controller;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* ๆ่ฟฐ๏ผ
*
* @author : Aberic ใ2018/6/4 15:01ใ
*/
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("event")
public class EventTestController {
@PostMapping(value = "block")
public String blockListener(@RequestBody Map<String, Object> map) {
log.debug(String.format("event blockListener: %s", JSON.toJSONString(map)));
return JSON.toJSONString(map);
}
}
```
|
Please help me generate a test for this class.
|
```package cn.aberic.fabric.controller;
import cn.aberic.fabric.dao.entity.CA;
import cn.aberic.fabric.service.CAService;
import cn.aberic.fabric.utils.SpringUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import javax.annotation.Resource;
/**
* ไฝ่
๏ผAberic on 2018/7/13 00:05
* ้ฎ็ฎฑ๏ผabericyang@gmail.com
*/
@CrossOrigin
@RestController
@RequestMapping("ca")
public class CaController {
@Resource
private CAService caService;
@PostMapping(value = "submit")
public ModelAndView submit(@ModelAttribute CA ca,
@RequestParam("intent") String intent,
@RequestParam("skFile") MultipartFile skFile,
@RequestParam("certificateFile") MultipartFile certificateFile) {
switch (intent) {
case "add":
caService.add(ca, skFile, certificateFile);
break;
case "edit":
caService.update(ca, skFile, certificateFile);
break;
}
return new ModelAndView(new RedirectView("list"));
}
@GetMapping(value = "add")
public ModelAndView add() {
ModelAndView modelAndView = new ModelAndView("caSubmit");
modelAndView.addObject("intentLittle", SpringUtil.get("enter"));
modelAndView.addObject("submit", SpringUtil.get("submit"));
modelAndView.addObject("intent", "add");
modelAndView.addObject("ca", new CA());
modelAndView.addObject("peers", caService.getFullPeers());
return modelAndView;
}
@GetMapping(value = "edit")
public ModelAndView edit(@RequestParam("id") int id) {
ModelAndView modelAndView = new ModelAndView("caSubmit");
modelAndView.addObject("intentLittle", SpringUtil.get("edit"));
modelAndView.addObject("submit", SpringUtil.get("modify"));
modelAndView.addObject("intent", "edit");
CA ca = caService.get(id);
modelAndView.addObject("ca", ca);
modelAndView.addObject("peers", caService.getPeersByCA(ca));
return modelAndView;
}
@GetMapping(value = "list")
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView("cas");
modelAndView.addObject("cas", caService.listFullCA());
return modelAndView;
}
@GetMapping(value = "delete")
public ModelAndView delete(@RequestParam("id") int id) {
caService.delete(id);
return new ModelAndView(new RedirectView("list"));
}
}
```
|
```package com.sk89q.worldguard.protection;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldguard.TestPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.association.RegionOverlapAssociation;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public abstract class RegionOverlapTest {
static String COURTYARD_ID = "courtyard";
static String FOUNTAIN_ID = "fountain";
static String NO_FIRE_ID = "nofire";
static String MEMBER_GROUP = "member";
static String COURTYARD_GROUP = "courtyard";
BlockVector3 inFountain = BlockVector3.at(2, 2, 2);
BlockVector3 inCourtyard = BlockVector3.at(7, 7, 7);
BlockVector3 outside = BlockVector3.at(15, 15, 15);
BlockVector3 inNoFire = BlockVector3.at(150, 150, 150);
RegionManager manager;
ProtectedRegion globalRegion;
ProtectedRegion courtyard;
ProtectedRegion fountain;
TestPlayer player1;
TestPlayer player2;
/* @Parameterized.Parameters(name = "{index}: useMaxPrio = {0}")
public static Iterable<Object[]> params() {
return Arrays.asList(new Object[][]{{true}, {false}});
}*/
// public boolean useMaxPriorityAssociation;
protected FlagRegistry getFlagRegistry() {
return WorldGuard.getInstance().getFlagRegistry();
}
protected abstract RegionManager createRegionManager() throws Exception;
@BeforeAll
public void setUp() throws Exception {
setUpGlobalRegion();
manager = createRegionManager();
setUpPlayers();
setUpCourtyardRegion();
setUpFountainRegion();
setUpNoFireRegion();
}
void setUpPlayers() {
player1 = new TestPlayer("tetsu");
player1.addGroup(MEMBER_GROUP);
player1.addGroup(COURTYARD_GROUP);
player2 = new TestPlayer("alex");
player2.addGroup(MEMBER_GROUP);
}
void setUpGlobalRegion() {
globalRegion = new GlobalProtectedRegion("__global__");
}
void setUpCourtyardRegion() {
DefaultDomain domain = new DefaultDomain();
domain.addGroup(COURTYARD_GROUP);
ArrayList<BlockVector2> points = new ArrayList<>();
points.add(BlockVector2.ZERO);
points.add(BlockVector2.at(10, 0));
points.add(BlockVector2.at(10, 10));
points.add(BlockVector2.at(0, 10));
//ProtectedRegion region = new ProtectedCuboidRegion(COURTYARD_ID, new BlockVector(0, 0, 0), new BlockVector(10, 10, 10));
ProtectedRegion region = new ProtectedPolygonalRegion(COURTYARD_ID, points, 0, 10);
region.setOwners(domain);
region.setPriority(5);
manager.addRegion(region);
courtyard = region;
}
void setUpFountainRegion() throws Exception {
DefaultDomain domain = new DefaultDomain();
domain.addGroup(MEMBER_GROUP);
ProtectedRegion region = new ProtectedCuboidRegion(FOUNTAIN_ID,
BlockVector3.ZERO, BlockVector3.at(5, 5, 5));
region.setMembers(domain);
region.setPriority(10);
manager.addRegion(region);
fountain = region;
fountain.setParent(courtyard);
fountain.setFlag(Flags.FIRE_SPREAD, StateFlag.State.DENY);
}
void setUpNoFireRegion() throws Exception {
ProtectedRegion region = new ProtectedCuboidRegion(NO_FIRE_ID,
BlockVector3.at(100, 100, 100), BlockVector3.at(200, 200, 200));
manager.addRegion(region);
region.setFlag(Flags.FIRE_SPREAD, StateFlag.State.DENY);
}
@Test
public void testNonBuildFlag() {
ApplicableRegionSet appl;
// Outside
appl = manager.getApplicableRegions(outside);
assertTrue(appl.testState(null, Flags.FIRE_SPREAD));
// Inside courtyard
appl = manager.getApplicableRegions(inCourtyard);
assertTrue(appl.testState(null, Flags.FIRE_SPREAD));
// Inside fountain
appl = manager.getApplicableRegions(inFountain);
assertFalse(appl.testState(null, Flags.FIRE_SPREAD));
// Inside no fire zone
appl = manager.getApplicableRegions(inNoFire);
assertFalse(appl.testState(null, Flags.FIRE_SPREAD));
}
@Test
public void testPlayer1BuildAccess() {
ApplicableRegionSet appl;
// Outside
appl = manager.getApplicableRegions(outside);
assertTrue(appl.testState(player1, Flags.BUILD));
// Inside courtyard
appl = manager.getApplicableRegions(inCourtyard);
assertTrue(appl.testState(player1, Flags.BUILD));
// Inside fountain
appl = manager.getApplicableRegions(inFountain);
assertTrue(appl.testState(player1, Flags.BUILD));
}
@Test
public void testPlayer2BuildAccess() {
ApplicableRegionSet appl;
// Outside
appl = manager.getApplicableRegions(outside);
assertTrue(appl.testState(player2, Flags.BUILD));
// Inside courtyard
appl = manager.getApplicableRegions(inCourtyard);
assertFalse(appl.testState(player2, Flags.BUILD));
// Inside fountain
appl = manager.getApplicableRegions(inFountain);
assertTrue(appl.testState(player2, Flags.BUILD));
}
@ParameterizedTest(name = "useMaxPriorityAssociation={0}")
@ValueSource(booleans = { false, true })
public void testNonPlayerBuildAccessInOneRegion(boolean useMaxPriorityAssociation) {
ApplicableRegionSet appl;
HashSet<ProtectedRegion> source = new HashSet<>();
source.add(courtyard);
RegionOverlapAssociation assoc = new RegionOverlapAssociation(source, useMaxPriorityAssociation);
// Outside
appl = manager.getApplicableRegions(outside);
assertTrue(appl.testState(assoc, Flags.BUILD));
// Inside courtyard
appl = manager.getApplicableRegions(inCourtyard);
assertTrue(appl.testState(assoc, Flags.BUILD));
// Inside fountain
appl = manager.getApplicableRegions(inFountain);
assertTrue(appl.testState(assoc, Flags.BUILD));
}
@ParameterizedTest(name = "useMaxPriorityAssociation={0}")
@ValueSource(booleans = { false, true })
public void testNonPlayerBuildAccessInBothRegions(boolean useMaxPriorityAssociation) {
ApplicableRegionSet appl;
HashSet<ProtectedRegion> source = new HashSet<>();
source.add(fountain);
source.add(courtyard);
RegionOverlapAssociation assoc = new RegionOverlapAssociation(source, useMaxPriorityAssociation);
// Outside
appl = manager.getApplicableRegions(outside);
assertTrue(appl.testState(assoc, Flags.BUILD));
// Inside courtyard
appl = manager.getApplicableRegions(inCourtyard);
assertTrue(useMaxPriorityAssociation ^ appl.testState(assoc, Flags.BUILD));
// Inside fountain
appl = manager.getApplicableRegions(inFountain);
assertTrue(appl.testState(assoc, Flags.BUILD));
}
@ParameterizedTest(name = "useMaxPriorityAssociation={0}")
@ValueSource(booleans = { false, true })
public void testNonPlayerBuildAccessInNoRegions(boolean useMaxPriorityAssociation) {
ApplicableRegionSet appl;
HashSet<ProtectedRegion> source = new HashSet<>();
RegionOverlapAssociation assoc = new RegionOverlapAssociation(source, useMaxPriorityAssociation);
// Outside
appl = manager.getApplicableRegions(outside);
assertTrue(appl.testState(assoc, Flags.BUILD));
// Inside courtyard
appl = manager.getApplicableRegions(inCourtyard);
assertFalse(appl.testState(assoc, Flags.BUILD));
// Inside fountain
appl = manager.getApplicableRegions(inFountain);
assertFalse(appl.testState(assoc, Flags.BUILD));
}
}
```
|
Please help me generate a test for this class.
|
```package com.sk89q.worldguard.protection.association;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import com.sk89q.worldguard.protection.regions.RegionQuery.QueryOption;
import java.util.List;
/**
* Determines that the association to a region is {@code OWNER} if the input
* region is in a set of source regions.
*
* <p>This class only performs a spatial query if its
* {@link #getAssociation(List)} method is called.</p>
*/
public class DelayedRegionOverlapAssociation extends AbstractRegionOverlapAssociation {
private final RegionQuery query;
private final Location location;
/**
* Create a new instance.
* @param query the query
* @param location the location
*/
public DelayedRegionOverlapAssociation(RegionQuery query, Location location) {
this(query, location, false);
}
/**
* Create a new instance.
* @param query the query
* @param location the location
* @param useMaxPriorityAssociation whether to use the max priority from regions to determine association
*/
public DelayedRegionOverlapAssociation(RegionQuery query, Location location, boolean useMaxPriorityAssociation) {
super(null, useMaxPriorityAssociation);
checkNotNull(query);
checkNotNull(location);
this.query = query;
this.location = location;
}
@Override
public Association getAssociation(List<ProtectedRegion> regions) {
if (source == null) {
ApplicableRegionSet result = query.getApplicableRegions(location, QueryOption.NONE);
source = result.getRegions();
calcMaxPriority();
}
return super.getAssociation(regions);
}
}
```
|
```package com.sk89q.worldguard.protection;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.managers.index.HashMapIndex;
import com.sk89q.worldguard.protection.managers.storage.MemoryRegionDatabase;
public class HashMapIndexTest extends RegionOverlapTest {
@Override
protected RegionManager createRegionManager() throws Exception {
return new RegionManager(new MemoryRegionDatabase(), new HashMapIndex.Factory(), getFlagRegistry());
}
}
```
|
Please help me generate a test for this class.
|
```package com.sk89q.worldguard.protection.managers.index;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.worldguard.util.Normal.normalize;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.managers.RegionDifference;
import com.sk89q.worldguard.protection.managers.RemovalStrategy;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Level;
/**
* An index that stores regions in a hash map, which allows for fast lookup
* by ID but O(n) performance for spatial queries.
*
* <p>This implementation supports concurrency to the extent that
* a {@link ConcurrentMap} does.</p>
*/
public class HashMapIndex extends AbstractRegionIndex implements ConcurrentRegionIndex {
private final ConcurrentMap<String, ProtectedRegion> regions = new ConcurrentHashMap<>();
private Set<ProtectedRegion> removed = new HashSet<>();
private final Object lock = new Object();
/**
* Called to rebuild the index after changes.
*/
protected void rebuildIndex() {
// Can be implemented by subclasses
}
/**
* Perform the add operation.
*
* @param region the region
*/
private void performAdd(ProtectedRegion region) {
checkNotNull(region);
region.setDirty(true);
synchronized (lock) {
String normalId = normalize(region.getId());
ProtectedRegion existing = regions.get(normalId);
if (existing != null) {
removeAndReplaceParents(existing.getId(), RemovalStrategy.UNSET_PARENT_IN_CHILDREN, region, false);
// Casing / form of ID has not changed
if (existing.getId().equals(region.getId())) {
removed.remove(existing);
}
}
regions.put(normalId, region);
removed.remove(region);
ProtectedRegion parent = region.getParent();
if (parent != null) {
performAdd(parent);
}
}
}
@Override
public void addAll(Collection<ProtectedRegion> regions) {
checkNotNull(regions);
synchronized (lock) {
for (ProtectedRegion region : regions) {
performAdd(region);
}
rebuildIndex();
}
}
@Override
public void bias(BlockVector2 chunkPosition) {
// Nothing to do
}
@Override
public void biasAll(Collection<BlockVector2> chunkPositions) {
// Nothing to do
}
@Override
public void forget(BlockVector2 chunkPosition) {
// Nothing to do
}
@Override
public void forgetAll() {
// Nothing to do
}
@Override
public void add(ProtectedRegion region) {
synchronized (lock) {
performAdd(region);
rebuildIndex();
}
}
@Override
public Set<ProtectedRegion> remove(String id, RemovalStrategy strategy) {
return removeAndReplaceParents(id, strategy, null, true);
}
private Set<ProtectedRegion> removeAndReplaceParents(String id, RemovalStrategy strategy, @Nullable ProtectedRegion replacement, boolean rebuildIndex) {
checkNotNull(id);
checkNotNull(strategy);
Set<ProtectedRegion> removedSet = new HashSet<>();
synchronized (lock) {
ProtectedRegion removed = regions.remove(normalize(id));
if (removed != null) {
removedSet.add(removed);
while (true) {
int lastSize = removedSet.size();
Iterator<ProtectedRegion> it = regions.values().iterator();
// Handle children
while (it.hasNext()) {
ProtectedRegion current = it.next();
ProtectedRegion parent = current.getParent();
if (parent != null && removedSet.contains(parent)) {
switch (strategy) {
case REMOVE_CHILDREN:
removedSet.add(current);
it.remove();
break;
case UNSET_PARENT_IN_CHILDREN:
try {
current.setParent(replacement);
} catch (CircularInheritanceException e) {
WorldGuard.logger.log(Level.WARNING, "Failed to replace parent '" + parent.getId() + "' of child '" + current.getId() + "' with replacement '" + replacement.getId() + "'", e);
current.clearParent();
}
}
}
}
if (strategy == RemovalStrategy.UNSET_PARENT_IN_CHILDREN
|| removedSet.size() == lastSize) {
break;
}
}
}
this.removed.addAll(removedSet);
if (rebuildIndex) {
rebuildIndex();
}
}
return removedSet;
}
@Override
public boolean contains(String id) {
return regions.containsKey(normalize(id));
}
@Nullable
@Override
public ProtectedRegion get(String id) {
return regions.get(normalize(id));
}
@Override
public void apply(Predicate<ProtectedRegion> consumer) {
for (ProtectedRegion region : regions.values()) {
if (!consumer.test(region)) {
break;
}
}
}
@Override
public void applyContaining(final BlockVector3 position, final Predicate<ProtectedRegion> consumer) {
apply(region -> !region.contains(position) || consumer.test(region));
}
@Override
public void applyIntersecting(ProtectedRegion region, Predicate<ProtectedRegion> consumer) {
for (ProtectedRegion found : region.getIntersectingRegions(regions.values())) {
if (!consumer.test(found)) {
break;
}
}
}
@Override
public int size() {
return regions.size();
}
@Override
public RegionDifference getAndClearDifference() {
synchronized (lock) {
Set<ProtectedRegion> changed = new HashSet<>();
Set<ProtectedRegion> removed = this.removed;
for (ProtectedRegion region : regions.values()) {
if (region.isDirty()) {
changed.add(region);
region.setDirty(false);
}
}
this.removed = new HashSet<>();
return new RegionDifference(changed, removed);
}
}
@Override
public void setDirty(RegionDifference difference) {
synchronized (lock) {
for (ProtectedRegion changed : difference.getChanged()) {
changed.setDirty(true);
}
removed.addAll(difference.getRemoved());
}
}
@Override
public Collection<ProtectedRegion> values() {
return Collections.unmodifiableCollection(regions.values());
}
@Override
public boolean isDirty() {
synchronized (lock) {
if (!removed.isEmpty()) {
return true;
}
for (ProtectedRegion region : regions.values()) {
if (region.isDirty()) {
return true;
}
}
}
return false;
}
@Override
public void setDirty(boolean dirty) {
synchronized (lock) {
if (!dirty) {
removed.clear();
}
for (ProtectedRegion region : regions.values()) {
region.setDirty(dirty);
}
}
}
/**
* A factory for new instances using this index.
*/
public static final class Factory implements Function<String, HashMapIndex> {
@Override
public HashMapIndex apply(String name) {
return new HashMapIndex();
}
}
}
```
|
```package com.sk89q.worldguard.domains;
import com.sk89q.worldguard.TestPlayer;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class DefaultDomainTest {
@Test
public void testContains() throws Exception {
TestPlayer player1 = new TestPlayer("test1");
TestPlayer player2 = new TestPlayer("test2");
player2.addGroup("group1");
player2.addGroup("group2");
TestPlayer player3 = new TestPlayer("test3");
player3.addGroup("group1");
player3.addGroup("group3");
DefaultDomain domain;
domain = new DefaultDomain();
domain.addGroup("group1");
assertFalse(domain.contains(player1));
assertTrue(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group1");
domain.addGroup("group2");
assertFalse(domain.contains(player1));
assertTrue(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group1");
domain.addGroup("group3");
assertFalse(domain.contains(player1));
assertTrue(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group3");
assertFalse(domain.contains(player1));
assertFalse(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addPlayer(player1.getName());
assertTrue(domain.contains(player1));
assertFalse(domain.contains(player2));
assertFalse(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group3");
domain.addPlayer(player1.getName());
assertTrue(domain.contains(player1));
assertFalse(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group3");
domain.addPlayer(player1.getUniqueId());
assertTrue(domain.contains(player1));
assertFalse(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group3");
domain.addPlayer(player1.getName());
domain.addPlayer(player1.getUniqueId());
assertTrue(domain.contains(player1));
assertFalse(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group3");
domain.addPlayer(player1);
assertTrue(domain.contains(player1));
assertFalse(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addPlayer(player1);
assertTrue(domain.contains(player1));
assertFalse(domain.contains(player2));
assertFalse(domain.contains(player3));
domain = new DefaultDomain();
domain.addPlayer(player2);
domain.addPlayer(player3);
assertFalse(domain.contains(player1));
assertTrue(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addCustomDomain(new CustomUUIDDomain("test", player2.getUniqueId()));
assertTrue(domain.contains(player2));
assertFalse(domain.contains(player2.getName()));
assertFalse(domain.contains(player3));
}
}```
|
Please help me generate a test for this class.
|
```package com.sk89q.worldguard.domains;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.event.ClickEvent;
import com.sk89q.worldedit.util.formatting.text.event.HoverEvent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.util.ChangeTracked;
import com.sk89q.worldguard.util.profile.Profile;
import com.sk89q.worldguard.util.profile.cache.ProfileCache;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A combination of a {@link PlayerDomain} and a {@link GroupDomain}.
*/
public class DefaultDomain implements Domain, ChangeTracked {
private PlayerDomain playerDomain = new PlayerDomain();
private GroupDomain groupDomain = new GroupDomain();
private final Map<String, CustomDomain> customDomains = new ConcurrentHashMap<>();
private boolean customDomainsChanged = false;
/**
* Create a new domain.
*/
public DefaultDomain() {
}
/**
* Create a new domain from an existing one, making a copy of all values.
*
* @param existing the other domain to copy values from
*/
public DefaultDomain(DefaultDomain existing) {
setPlayerDomain(existing.getPlayerDomain());
setGroupDomain(existing.getGroupDomain());
setCustomDomains(existing.customDomains);
}
/**
* Get the domain that holds the players.
*
* @return a domain
*/
public PlayerDomain getPlayerDomain() {
return playerDomain;
}
/**
* Set a new player domain.
*
* @param playerDomain a domain
*/
public void setPlayerDomain(PlayerDomain playerDomain) {
checkNotNull(playerDomain);
this.playerDomain = new PlayerDomain(playerDomain);
}
/**
* Set the domain that holds the groups.
*
* @return a domain
*/
public GroupDomain getGroupDomain() {
return groupDomain;
}
/**
* Set a new group domain.
*
* @param groupDomain a domain
*/
public void setGroupDomain(GroupDomain groupDomain) {
checkNotNull(groupDomain);
this.groupDomain = new GroupDomain(groupDomain);
}
/**
* Add new custom domains
*
* @param customDomain a domain
*/
public void addCustomDomain(CustomDomain customDomain) {
checkNotNull(customDomain);
this.customDomains.put(customDomain.getName(), customDomain);
this.customDomainsChanged = true;
}
/**
* Remove a custom domain matched by the name
*
* @param name the name
*/
public void removeCustomDomain(String name) {
checkNotNull(name);
if (this.customDomains.remove(name) != null) {
this.customDomainsChanged = true;
}
}
/**
* Remove a custom domain
*
* @param customDomain a domain
*/
public void removeCustomDomain(CustomDomain customDomain) {
checkNotNull(customDomain);
if (this.customDomains.remove(customDomain.getName()) != null) {
this.customDomainsChanged = true;
}
}
/**
* Set the api domains to a specified value
*
* @param customDomains the domains
*/
public void setCustomDomains(Map<String, CustomDomain> customDomains) {
checkNotNull(customDomains);
this.customDomains.clear();
this.customDomains.putAll(customDomains);
this.customDomainsChanged = true;
}
/**
* Get all api domains
*
* @return a unmodifiable copy of the domains
*/
public Collection<CustomDomain> getCustomDomains() {
return Collections.unmodifiableCollection(this.customDomains.values());
}
/**
* Get the api domain specified by its name
*
* @param name the name of the domain
* @return the custom domain
*/
public @Nullable CustomDomain getCustomDomain(String name) {
return this.customDomains.get(name);
}
/**
* Add the given player to the domain, identified by the player's name.
*
* @param name the name of the player
*/
public void addPlayer(String name) {
playerDomain.addPlayer(name);
}
/**
* Remove the given player from the domain, identified by the player's name.
*
* @param name the name of the player
*/
public void removePlayer(String name) {
playerDomain.removePlayer(name);
}
/**
* Remove the given player from the domain, identified by the player's UUID.
*
* @param uuid the UUID of the player
*/
public void removePlayer(UUID uuid) {
playerDomain.removePlayer(uuid);
}
/**
* Add the given player to the domain, identified by the player's UUID.
*
* @param uniqueId the UUID of the player
*/
public void addPlayer(UUID uniqueId) {
playerDomain.addPlayer(uniqueId);
}
/**
* Remove the given player from the domain, identified by either the
* player's name, the player's unique ID, or both.
*
* @param player the player
*/
public void removePlayer(LocalPlayer player) {
playerDomain.removePlayer(player);
}
/**
* Add the given player to the domain, identified by the player's UUID.
*
* @param player the player
*/
public void addPlayer(LocalPlayer player) {
playerDomain.addPlayer(player);
}
/**
* Add all the entries from another domain.
*
* @param other the other domain
*/
public void addAll(DefaultDomain other) {
checkNotNull(other);
for (String player : other.getPlayers()) {
addPlayer(player);
}
for (UUID uuid : other.getUniqueIds()) {
addPlayer(uuid);
}
for (String group : other.getGroups()) {
addGroup(group);
}
for (CustomDomain domain : other.getCustomDomains()) {
addCustomDomain(domain);
}
}
/**
* Remove all the entries from another domain.
*
* @param other the other domain
*/
public void removeAll(DefaultDomain other) {
checkNotNull(other);
for (String player : other.getPlayers()) {
removePlayer(player);
}
for (UUID uuid : other.getUniqueIds()) {
removePlayer(uuid);
}
for (String group : other.getGroups()) {
removeGroup(group);
}
for (CustomDomain domain : other.getCustomDomains()) {
removeCustomDomain(domain.getName());
}
}
/**
* Get the set of player names.
*
* @return the set of player names
*/
public Set<String> getPlayers() {
return playerDomain.getPlayers();
}
/**
* Get the set of player UUIDs.
*
* @return the set of player UUIDs
*/
public Set<UUID> getUniqueIds() {
return playerDomain.getUniqueIds();
}
/**
* Add the name of the group to the domain.
*
* @param name the name of the group.
*/
public void addGroup(String name) {
groupDomain.addGroup(name);
}
/**
* Remove the given group from the domain.
*
* @param name the name of the group
*/
public void removeGroup(String name) {
groupDomain.removeGroup(name);
}
/**
* Get the set of group names.
*
* @return the set of group names
*/
public Set<String> getGroups() {
return groupDomain.getGroups();
}
@Override
public boolean contains(LocalPlayer player) {
return playerDomain.contains(player) || groupDomain.contains(player) || customDomains.values().stream().anyMatch(d -> d.contains(player));
}
@Override
public boolean contains(UUID uniqueId) {
return playerDomain.contains(uniqueId) || customDomains.values().stream().anyMatch(d -> d.contains(uniqueId));
}
@Override
public boolean contains(String playerName) {
return playerDomain.contains(playerName);
}
@Override
public int size() {
return groupDomain.size() + playerDomain.size() + customDomains.size();
}
@Override
public void clear() {
playerDomain.clear();
groupDomain.clear();
}
public void removeAll() {
clear();
}
public String toPlayersString() {
return toPlayersString(null);
}
public String toPlayersString(@Nullable ProfileCache cache) {
List<String> output = new ArrayList<>();
for (String name : playerDomain.getPlayers()) {
output.add("name:" + name);
}
if (cache != null) {
ImmutableMap<UUID, Profile> results = cache.getAllPresent(playerDomain.getUniqueIds());
for (UUID uuid : playerDomain.getUniqueIds()) {
Profile profile = results.get(uuid);
if (profile != null) {
output.add(profile.getName() + "*");
} else {
output.add("uuid:" + uuid);
}
}
} else {
for (UUID uuid : playerDomain.getUniqueIds()) {
output.add("uuid:" + uuid);
}
}
output.sort(String.CASE_INSENSITIVE_ORDER);
return String.join(", ", output);
}
public String toGroupsString() {
StringBuilder str = new StringBuilder();
for (Iterator<String> it = groupDomain.getGroups().iterator(); it.hasNext(); ) {
str.append("g:");
str.append(it.next());
if (it.hasNext()) {
str.append(", ");
}
}
return str.toString();
}
public String toCustomDomainsString() {
List<String> output = new ArrayList<>();
for (CustomDomain customDomain : customDomains.values()) {
output.add(customDomain.getName() + ":" + customDomain.toString());
}
output.sort(String.CASE_INSENSITIVE_ORDER);
return String.join(", ", output);
}
public String toUserFriendlyString() {
return toUserFriendlyString(null);
}
public String toUserFriendlyString(@Nullable ProfileCache cache) {
StringBuilder str = new StringBuilder();
if (playerDomain.size() > 0) {
str.append(toPlayersString(cache));
}
if (groupDomain.size() > 0) {
if (str.length() > 0) {
str.append("; ");
}
str.append(toGroupsString());
}
if (!customDomains.isEmpty()) {
if (str.length() > 0) {
str.append("; ");
}
str.append(toCustomDomainsString());
}
return str.toString();
}
public Component toUserFriendlyComponent(@Nullable ProfileCache cache) {
final TextComponent.Builder builder = TextComponent.builder("");
if (playerDomain.size() > 0) {
builder.append(toPlayersComponent(cache));
}
if (groupDomain.size() > 0) {
if (playerDomain.size() > 0) {
builder.append(TextComponent.of("; "));
}
builder.append(toGroupsComponent());
}
if (!customDomains.isEmpty()) {
if (playerDomain.size() > 0 || groupDomain.size() > 0) {
builder.append(TextComponent.of("; "));
}
builder.append(toCustomDomainsComponent());
}
return builder.build();
}
private Component toGroupsComponent() {
final TextComponent.Builder builder = TextComponent.builder("");
for (Iterator<String> it = groupDomain.getGroups().iterator(); it.hasNext(); ) {
builder.append(TextComponent.of("g:", TextColor.GRAY))
.append(TextComponent.of(it.next(), TextColor.GOLD));
if (it.hasNext()) {
builder.append(TextComponent.of(", "));
}
}
return builder.build().hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("Groups")));
}
private Component toPlayersComponent(ProfileCache cache) {
List<String> uuids = Lists.newArrayList();
Map<String, UUID> profileMap = Maps.newHashMap();
for (String name : playerDomain.getPlayers()) {
profileMap.put(name, null);
}
if (cache != null) {
ImmutableMap<UUID, Profile> results = cache.getAllPresent(playerDomain.getUniqueIds());
for (UUID uuid : playerDomain.getUniqueIds()) {
Profile profile = results.get(uuid);
if (profile != null) {
profileMap.put(profile.getName(), uuid);
} else {
uuids.add(uuid.toString());
}
}
} else {
for (UUID uuid : playerDomain.getUniqueIds()) {
uuids.add(uuid.toString());
}
}
final TextComponent.Builder builder = TextComponent.builder("");
final Iterator<TextComponent> profiles = profileMap.keySet().stream().sorted().map(name -> {
final UUID uuid = profileMap.get(name);
if (uuid == null) {
return TextComponent.of(name, TextColor.YELLOW)
.hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("Name only", TextColor.GRAY)
.append(TextComponent.newline()).append(TextComponent.of("Click to copy"))))
.clickEvent(ClickEvent.of(ClickEvent.Action.COPY_TO_CLIPBOARD, name));
} else {
return TextComponent.of(name, TextColor.YELLOW)
.hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("Last known name of uuid: ", TextColor.GRAY)
.append(TextComponent.of(uuid.toString(), TextColor.WHITE))
.append(TextComponent.newline()).append(TextComponent.of("Click to copy"))))
.clickEvent(ClickEvent.of(ClickEvent.Action.COPY_TO_CLIPBOARD, uuid.toString()));
}
}).iterator();
while (profiles.hasNext()) {
builder.append(profiles.next());
if (profiles.hasNext() || !uuids.isEmpty()) {
builder.append(TextComponent.of(", "));
}
}
if (!uuids.isEmpty()) {
builder.append(TextComponent.of(uuids.size() + " unknown uuid" + (uuids.size() == 1 ? "" : "s"), TextColor.GRAY)
.hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("Unable to resolve the name for:", TextColor.GRAY)
.append(TextComponent.newline())
.append(TextComponent.of(String.join("\n", uuids), TextColor.WHITE))
.append(TextComponent.newline().append(TextComponent.of("Click to copy")))))
.clickEvent(ClickEvent.of(ClickEvent.Action.COPY_TO_CLIPBOARD, String.join(",", uuids))));
}
return builder.build();
}
private Component toCustomDomainsComponent() {
final TextComponent.Builder builder = TextComponent.builder("");
for (Iterator<CustomDomain> it = customDomains.values().iterator(); it.hasNext(); ) {
CustomDomain domain = it.next();
builder.append(TextComponent.of(domain.getName() + ":", TextColor.LIGHT_PURPLE))
.append(TextComponent.of(domain.toString(), TextColor.GOLD));
if (it.hasNext()) {
builder.append(TextComponent.of(", "));
}
}
return builder.build().hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("CustomDomain")));
}
@Override
public boolean isDirty() {
return playerDomain.isDirty() || groupDomain.isDirty() ||
customDomainsChanged || customDomains.values().stream().anyMatch(ChangeTracked::isDirty);
}
@Override
public void setDirty(boolean dirty) {
playerDomain.setDirty(dirty);
groupDomain.setDirty(dirty);
customDomainsChanged = dirty;
customDomains.values().forEach(d -> d.setDirty(dirty));
}
@Override
public String toString() {
return "{players=" + playerDomain +
", groups=" + groupDomain +
", custom=" + customDomains +
'}';
}
}
```
|
```package com.sk89q.worldguard.protection;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.managers.index.PriorityRTreeIndex;
import com.sk89q.worldguard.protection.managers.storage.MemoryRegionDatabase;
public class PriorityRTreeIndexTest extends RegionOverlapTest {
@Override
protected RegionManager createRegionManager() throws Exception {
return new RegionManager(new MemoryRegionDatabase(), new PriorityRTreeIndex.Factory(), getFlagRegistry());
}
}
```
|
Please help me generate a test for this class.
|
```package com.sk89q.worldguard.protection.managers.index;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegionMBRConverter;
import org.khelekore.prtree.MBR;
import org.khelekore.prtree.MBRConverter;
import org.khelekore.prtree.PRTree;
import org.khelekore.prtree.SimpleMBR;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* An implementation of an index that uses {@link HashMapIndex} for queries
* by region name and a priority R-tree for spatial queries.
*
* <p>At the moment, the R-tree is only utilized for the
* {@link #applyContaining(BlockVector3, Predicate)} method, and the underlying
* hash map-based index is used for the other spatial queries. In addition,
* every modification to the index requires the entire R-tree to be rebuilt,
* although this operation is reasonably quick.</p>
*
* <p>This implementation is as thread-safe as the underlying
* {@link HashMapIndex}, although spatial queries may lag behind changes
* for very brief periods of time as the tree is rebuilt.</p>
*/
public class PriorityRTreeIndex extends HashMapIndex {
private static final int BRANCH_FACTOR = 30;
private static final MBRConverter<ProtectedRegion> CONVERTER = new ProtectedRegionMBRConverter();
private PRTree<ProtectedRegion> tree;
public PriorityRTreeIndex() {
tree = new PRTree<>(CONVERTER, BRANCH_FACTOR);
tree.load(Collections.emptyList());
}
@Override
protected void rebuildIndex() {
PRTree<ProtectedRegion> newTree = new PRTree<>(CONVERTER, BRANCH_FACTOR);
newTree.load(values());
this.tree = newTree;
}
@Override
public void applyContaining(BlockVector3 position, Predicate<ProtectedRegion> consumer) {
Set<ProtectedRegion> seen = new HashSet<>();
MBR pointMBR = new SimpleMBR(position.getX(), position.getX(), position.getY(), position.getY(), position.getZ(), position.getZ());
for (ProtectedRegion region : tree.find(pointMBR)) {
if (region.contains(position) && !seen.contains(region)) {
seen.add(region);
if (!consumer.test(region)) {
break;
}
}
}
}
@Override
public void applyIntersecting(ProtectedRegion region, Predicate<ProtectedRegion> consumer) {
BlockVector3 min = region.getMinimumPoint().floor();
BlockVector3 max = region.getMaximumPoint().ceil();
Set<ProtectedRegion> candidates = new HashSet<>();
MBR pointMBR = new SimpleMBR(min.getX(), max.getX(), min.getY(), max.getY(), min.getZ(), max.getZ());
for (ProtectedRegion found : tree.find(pointMBR)) {
candidates.add(found);
}
for (ProtectedRegion found : region.getIntersectingRegions(candidates)) {
if (!consumer.test(found)) {
break;
}
}
}
/**
* A factory for new instances using this index.
*/
public static final class Factory implements Function<String, PriorityRTreeIndex> {
@Override
public PriorityRTreeIndex apply(String name) {
return new PriorityRTreeIndex();
}
}
}```
|
```package com.sk89q.worldguard.protection;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.MapFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StringFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SuppressWarnings({"UnusedDeclaration"})
public class FlagValueCalculatorMapFlagTest {
@Test
public void testGetEffectiveMapFlagWithFallback() throws Exception {
MockApplicableRegionSet mock = new MockApplicableRegionSet();
ProtectedRegion global = mock.global();
global.setFlag(Flags.BUILD, StateFlag.State.DENY);
MapFlag<String, StateFlag.State> mapFlag =
new MapFlag<>("test", new StringFlag(null), new StateFlag(null, true));
Map<String, StateFlag.State> map = new HashMap<>();
map.put("allow", StateFlag.State.ALLOW);
map.put("deny", StateFlag.State.DENY);
global.setFlag(mapFlag, map);
ApplicableRegionSet applicableSet = mock.getApplicableSet();
assertEquals(applicableSet.queryMapValue(null, mapFlag, "allow", Flags.BUILD),
StateFlag.State.ALLOW);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "deny", Flags.BUILD),
StateFlag.State.DENY);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "undefined", Flags.BUILD),
StateFlag.State.DENY);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "allow", null),
StateFlag.State.ALLOW);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "deny", null),
StateFlag.State.DENY);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "undefined", null),
StateFlag.State.ALLOW);
}
@Test
public void testGetEffectiveMapFlagWithSamePriority() throws Exception {
MockApplicableRegionSet mock = new MockApplicableRegionSet();
ProtectedRegion region1 = mock.add(0);
ProtectedRegion region2 = mock.add(0);
MapFlag<String, StateFlag.State> mapFlag =
new MapFlag<>("test", new StringFlag(null), new StateFlag(null, true));
Map<String, StateFlag.State> map1 = new HashMap<>();
Map<String, StateFlag.State> map2 = new HashMap<>();
map1.put("should-deny", StateFlag.State.ALLOW);
map2.put("should-deny", StateFlag.State.DENY);
map1.put("should-allow", StateFlag.State.ALLOW);
map1.put("should-allow2", StateFlag.State.ALLOW);
map2.put("should-allow2", StateFlag.State.ALLOW);
region1.setFlag(mapFlag, map1);
region2.setFlag(mapFlag, map2);
ApplicableRegionSet applicableSet = mock.getApplicableSet();
assertEquals(applicableSet.queryMapValue(null, mapFlag, "should-deny", null),
StateFlag.State.DENY);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "should-allow", null),
StateFlag.State.ALLOW);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "should-allow2", null),
StateFlag.State.ALLOW);
}
@Test
public void testGetEffectiveMapFlagWithInheritance() throws Exception {
MockApplicableRegionSet mock = new MockApplicableRegionSet();
ProtectedRegion parent = mock.add(0);
ProtectedRegion child = mock.add(0, parent);
MapFlag<String, StateFlag.State> mapFlag =
new MapFlag<>("test", new StringFlag(null), new StateFlag(null, true));
Map<String, StateFlag.State> parentMap = new HashMap<>();
Map<String, StateFlag.State> childMap = new HashMap<>();
parentMap.put("useChildValue", StateFlag.State.ALLOW);
childMap.put("useChildValue", StateFlag.State.DENY);
parentMap.put("useParentValue", StateFlag.State.ALLOW);
parent.setFlag(mapFlag, parentMap);
child.setFlag(mapFlag, childMap);
ApplicableRegionSet applicableSet = mock.getApplicableSet();
assertEquals(applicableSet.queryMapValue(null, mapFlag, "useChildValue", null),
StateFlag.State.DENY);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "useParentValue", null),
StateFlag.State.ALLOW);
}
}
```
|
Please help me generate a test for this class.
|
```package com.sk89q.worldguard.protection.flags;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.Iterators;
import com.sk89q.worldguard.protection.FlagValueCalculator;
import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
import java.util.Collection;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* A flag carries extra data on a region.
*
* <p>Each flag implementation is a singleton and must be registered with a
* {@link FlagRegistry} to be useful. Flag values are stored as their
* proper data type, but they are first "loaded" by calling
* {@link #unmarshal(Object)}. On save, the objects are fed
* through {@link #marshal(Object)} and then saved.</p>
*/
public abstract class Flag<T> {
private static final Pattern VALID_NAME = Pattern.compile("^[:A-Za-z0-9\\-]{1,40}$");
private final String name;
private final RegionGroupFlag regionGroup;
/**
* Create a new flag.
*
* <p>Flag names should match the regex {@code ^[:A-Za-z0-9\-]{1,40}$}.</p>
*
* @param name The name of the flag
* @param defaultGroup The default group
* @throws IllegalArgumentException Thrown if the name is invalid
*/
protected Flag(String name, @Nullable RegionGroup defaultGroup) {
if (name != null && !isValidName(name)) {
throw new IllegalArgumentException("Invalid flag name used");
}
this.name = name;
this.regionGroup = defaultGroup != null ? new RegionGroupFlag(name + "-group", defaultGroup) : null;
}
/**
* Create a new flag with {@link RegionGroup#ALL} as the default group.
*
* <p>Flag names should match the regex {@code ^[:A-Za-z0-9\-]{1,40}$}.</p>
*
* @param name The name of the flag
* @throws IllegalArgumentException Thrown if the name is invalid
*/
protected Flag(String name) {
this(name, RegionGroup.ALL);
}
/**
* Get the name of the flag.
*
* @return The name of the flag
*/
public final String getName() {
return name;
}
/**
* Get the default value.
*
* @return The default value, if one exists, otherwise {@code null} may be returned
*/
@Nullable
public T getDefault() {
return null;
}
/**
* Given a list of values, choose the best one.
*
* <p>If there is no "best value" defined, then the first value should
* be returned. The default implementation returns the first value. If
* an implementation does have a strategy defined, then
* {@link #hasConflictStrategy()} should be overridden too.</p>
*
* @param values A collection of values
* @return The chosen value
*/
@Nullable
public T chooseValue(Collection<T> values) {
return Iterators.getNext(values.iterator(), null);
}
/**
* Whether the flag can take a list of values and choose a "best one."
*
* <p>This is the case with the {@link StateFlag} where {@code DENY}
* overrides {@code ALLOW}, but most flags just return the
* first result from a list.</p>
*
* <p>This flag is primarily used to optimize flag lookup in
* {@link FlagValueCalculator}.</p>
*
* @return Whether a best value can be chosen
*/
public boolean hasConflictStrategy() {
return false;
}
/**
* Whether the flag implicitly has a value set as long as
* {@link Flags#PASSTHROUGH} is not set.
*
* <p>This value is only changed, at least in WorldGuard, for the
* {@link Flags#BUILD} flag.</p>
*
* @return Whether the flag is ignored
*/
public boolean implicitlySetWithMembership() {
return false;
}
/**
* Whether, if the flag is not set at all, the value should be derived
* from membership.
*
* <p>This value is only changed, at least in WorldGuard, for the
* {@link Flags#BUILD} flag.</p>
*
* @return Whether membership is used
*/
public boolean usesMembershipAsDefault() {
return false;
}
/**
* Whether the flag requires that a subject is specified in
* {@link FlagValueCalculator}.
*
* <p>This value is only changed, at least in WorldGuard, for the
* {@link Flags#BUILD} flag.</p>
*
* @return Whether a subject is required
*/
public boolean requiresSubject() {
return false;
}
/**
* Get the region group flag.
*
* <p>Every group has a region group flag except for region group flags
* themselves.</p>
*
* @return The region group flag
*/
public final RegionGroupFlag getRegionGroupFlag() {
return regionGroup;
}
/**
* Parse a given input to coerce it to a type compatible with the flag.
*
* @param context the {@link FlagContext}
* @return The coerced type
* @throws InvalidFlagFormatException Raised if the input is invalid
*/
public abstract T parseInput(FlagContext context) throws InvalidFlagFormatException;
/**
* Convert a raw type that was loaded (from a YAML file, for example)
* into the type that this flag uses.
*
* @param o The object
* @return The unmarshalled type
*/
public abstract T unmarshal(@Nullable Object o);
/**
* Convert the value stored for this flag into a type that can be
* serialized into YAML.
*
* @param o The object
* @return The marshalled type
*/
public abstract Object marshal(T o);
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"name='" + name + '\'' +
'}';
}
/**
* Test whether a flag name is valid.
*
* @param name The flag name
* @return Whether the name is valid
*/
public static boolean isValidName(String name) {
checkNotNull(name, "name");
return VALID_NAME.matcher(name).matches();
}
}
```
|
```package com.graphaware.module.uuid;
import com.graphaware.runtime.bootstrap.RuntimeExtensionFactory;
import com.graphaware.test.integration.GraphAwareNeo4jBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Result;
import org.neo4j.graphdb.Transaction;
import org.neo4j.harness.Neo4j;
import org.neo4j.harness.Neo4jBuilders;
import java.util.ArrayList;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class UuidModuleMultipleModulesTest {
private Neo4j neo4j;
private GraphDatabaseService database;
@BeforeEach
public void setUp() {
neo4j = GraphAwareNeo4jBuilder.builder(Neo4jBuilders.newInProcessBuilder())
.withDisabledServer()
.withExtensionFactories(new ArrayList<>(Collections.singleton(new RuntimeExtensionFactory())))
.withGAConfig("com.graphaware.module.neo4j.UID1.1", "com.graphaware.module.uuid.UuidBootstrapper")
.withGAConfig("com.graphaware.module.neo4j.UID1.uuidProperty", "customerId")
.withGAConfig("com.graphaware.module.neo4j.UID1.node", "hasLabel('Customer')")
.withGAConfig("com.graphaware.module.neo4j.UID2.2", "com.graphaware.module.uuid.UuidBootstrapper")
.withGAConfig("com.graphaware.module.neo4j.UID2.uuidProperty", "userId")
.withGAConfig("com.graphaware.module.neo4j.UID2.node", "hasLabel('User')")
.build();
database = neo4j.defaultDatabaseService();
}
@AfterEach
public void tearDown() {
neo4j.close();
GraphAwareNeo4jBuilder.cleanup();
}
@Test
public void testProcedures() {
//Create & Assign
String cid, uid;
try (Transaction tx = database.beginTx()) {
cid = singleValue(tx.execute("CREATE (c:Customer {name:'c1'}) RETURN id(c)"));
uid = singleValue(tx.execute("CREATE (u:User {name:'u1'}) RETURN id(u)"));
tx.commit();
}
database.executeTransactionally("CREATE (:SomethingElse {name:'s1'})");
String uuid;
try (Transaction tx = database.beginTx()) {
uuid = singleValue(tx.execute("MATCH (c:Customer) RETURN c.customerId"));
tx.commit();
}
//Retrieve
assertEquals(cid, findNodeByUuid("Customer", "customerId", uuid));
try (Transaction tx = database.beginTx()) {
uuid = singleValue(tx.execute("MATCH (u:User) RETURN u.userId"));
tx.commit();
}
//Retrieve
assertEquals(uid, findNodeByUuid("User", "userId", uuid));
}
private String findNodeByUuid(String label, String property, String uuid) {
try (Transaction tx = database.beginTx()) {
return singleValue(tx.execute("MATCH (n:" + label + " {" + property + ":'" + uuid + "'}) RETURN id(n) as id"));
}
}
private String singleValue(Result result) {
return result.next().values().iterator().next().toString();
}
}
```
|
Please help me generate a test for this class.
|
```package com.graphaware.module.uuid;
import com.graphaware.common.util.Change;
import com.graphaware.common.uuid.UuidGenerator;
import com.graphaware.runtime.GraphAwareRuntime;
import com.graphaware.runtime.module.BaseModule;
import com.graphaware.runtime.module.DeliberateTransactionRollbackException;
import com.graphaware.tx.event.improved.api.ImprovedTransactionData;
import org.neo4j.graphdb.Entity;
import org.springframework.util.ClassUtils;
import java.util.Collection;
/**
* {@link com.graphaware.runtime.module.Module} that assigns UUID's to nodes in the graph.
*/
public class UuidModule extends BaseModule<Void> {
private final UuidConfiguration uuidConfiguration;
private UuidGenerator uuidGenerator;
/**
* Construct a new UUID module.
*
* @param moduleId ID of the module.
*/
public UuidModule(String moduleId, UuidConfiguration configuration) {
super(moduleId);
this.uuidConfiguration = configuration;
}
@Override
public void start(GraphAwareRuntime runtime) {
this.uuidGenerator = instantiateUuidGenerator(uuidConfiguration);
}
protected UuidGenerator instantiateUuidGenerator(UuidConfiguration uuidConfiguration) {
String uuidGeneratorClassString = uuidConfiguration.getUuidGenerator();
try {
// Instantiate the configured/supplied class
@SuppressWarnings("unchecked")
Class<UuidGenerator> uuidGeneratorClass = (Class<UuidGenerator>) ClassUtils.forName(uuidGeneratorClassString, getClass().getClassLoader());
return uuidGeneratorClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("Unable to instantiate UuidGenerator of type '" + uuidGeneratorClassString + "'", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public UuidConfiguration getConfiguration() {
return uuidConfiguration;
}
/**
* {@inheritDoc}
*/
@Override
public Void beforeCommit(ImprovedTransactionData transactionData) throws DeliberateTransactionRollbackException {
processEntities(transactionData.getAllCreatedNodes(), transactionData.getAllDeletedNodes(), transactionData.getAllChangedNodes());
processEntities(transactionData.getAllCreatedRelationships(), transactionData.getAllDeletedRelationships(), transactionData.getAllChangedRelationships());
return null;
}
private <E extends Entity> void processEntities(Collection<E> created, Collection<E> deleted, Collection<Change<E>> updated) {
for (E entity : created) {
assignUuid(entity);
}
for (Change<E> change : updated) {
if (uuidHasBeenRemoved(change)) {
if (isImmutable()) {
throw new DeliberateTransactionRollbackException("You are not allowed to remove the " + uuidConfiguration.getUuidProperty() + " property");
} else {
continue;
}
}
if (uuidHasChanged(change)) {
if (isImmutable()) {
throw new DeliberateTransactionRollbackException("You are not allowed to modify the " + uuidConfiguration.getUuidProperty() + " property");
} else {
continue;
}
}
if (!hadUuid(change) && hasNoUuid(change)) {
assignUuid(change.getCurrent());
}
}
}
private void assignUuid(Entity entity) {
String uuidProperty = uuidConfiguration.getUuidProperty();
if (!entity.hasProperty(uuidProperty)) {
assignNewUuid(entity, uuidProperty);
}
}
private void assignNewUuid(Entity entity, String uuidProperty) {
String uuid = uuidGenerator.generateUuid();
if (uuidConfiguration.shouldStripHyphens()) {
uuid = uuid.replaceAll("-", "");
}
entity.setProperty(uuidProperty, uuid);
}
private boolean isImmutable() {
return uuidConfiguration.getImmutable();
}
private boolean uuidHasBeenRemoved(Change<? extends Entity> changed) {
return hadUuid(changed) && hasNoUuid(changed);
}
private boolean uuidHasChanged(Change<? extends Entity> change) {
return hadUuid(change) && (!change.getPrevious().getProperty(uuidConfiguration.getUuidProperty()).equals(change.getCurrent().getProperty(uuidConfiguration.getUuidProperty())));
}
private boolean hasUuid(Entity entity) {
return entity.hasProperty(uuidConfiguration.getUuidProperty());
}
private boolean hasNoUuid(Change<? extends Entity> change) {
return !hasUuid(change.getCurrent());
}
private boolean hadUuid(Change<? extends Entity> change) {
return hasUuid(change.getPrevious());
}
}```
|
```package com.oppo.shuttle.rss.clients;
import com.oppo.shuttle.rss.common.AppTaskInfo;
import com.oppo.shuttle.rss.common.Ors2ServerGroup;
import com.oppo.shuttle.rss.common.Ors2WorkerDetail;
import com.oppo.shuttle.rss.messages.ShuffleMessage;
import com.oppo.shuttle.rss.messages.ShufflePacket;
import com.google.protobuf.ByteString;
import org.apache.spark.SparkConf;
import org.apache.spark.shuffle.Ors2Config;
import org.apache.spark.shuffle.Ors2ShuffleTestEnv;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class NettyClientTest {
private Ors2ShuffleTestEnv env;
@BeforeClass
public void beforeClass() {
env = Ors2ShuffleTestEnv.zkService();
env.startCluster();
}
@AfterClass
public void afterClass() {
env.stopCluster();
}
@Test
public void testBuild() throws Exception {
ArrayList<Ors2WorkerDetail> details = new ArrayList<>();
Ors2WorkerDetail workerDetail = env.getCluster().serverList().get(0);
details.add(workerDetail);
Ors2ServerGroup ors2ServerGroup = new Ors2ServerGroup(details);
SparkConf conf = new SparkConf();
conf.set(Ors2Config.networkTimeout(), 10 * 1000L);
ArrayList<Ors2ServerGroup> groups = new ArrayList<>();
groups.add(ors2ServerGroup);
AppTaskInfo taskInfo = new AppTaskInfo("1", "0", 1, 1, 0, 1, 0, 0);
NettyClient nettyClient = new NettyClient(groups, conf, taskInfo, new Ors2ClientFactory(conf));
List<byte[]> bytes = Collections.singletonList(new byte[]{1, 1, 1});
String id1 = NettyClient.requestId();
String id2 = NettyClient.requestId();
nettyClient.send(0, ShufflePacket.create(build(id1), createPackageRequest(id1), bytes));
nettyClient.send(0, ShufflePacket.create(build(id2), createPackageRequest(id2), bytes));
nettyClient.waitFinish();
Thread.sleep(5 * 1000);
String id3 = NettyClient.requestId();
String id4 = NettyClient.requestId();
nettyClient.send(0, ShufflePacket.create(build(id3), createPackageRequest(id3), bytes));
nettyClient.send(0, ShufflePacket.create(build(id4), createPackageRequest(id4), bytes));
nettyClient.waitFinish();
nettyClient.getClientFactory().stop();
}
public ShuffleMessage.BuildConnectionRequest.Builder build(String id) {
return ShuffleMessage
.BuildConnectionRequest.newBuilder().setVersion(1).setMessageId(id)
.setJobPriority(1).setRetryIdx(0);
}
public ShuffleMessage.UploadPackageRequest.Builder createPackageRequest(String id) {
byte[] data = new byte[] {1, 1, 1};
ShuffleMessage.UploadPackageRequest.PartitionBlockData partitionBlock = ShuffleMessage
.UploadPackageRequest
.PartitionBlockData
.newBuilder()
.setPartitionId(1)
.setDataLength(data.length)
.setData(ByteString.copyFrom(data))
.build();
ShuffleMessage.UploadPackageRequest.Builder uploadPackageRequestBuilder = ShuffleMessage.UploadPackageRequest
.newBuilder()
.setAppId("app_test")
.setAppAttempt("1")
.setShuffleId(1)
.setMapId(1)
.setAttemptId(1)
.setNumMaps(0)
.setNumPartitions(1)
.setMessageId(id)
.setSeqId(1);
return uploadPackageRequestBuilder;
}
}
```
|
Please help me generate a test for this class.
|
```package com.oppo.shuttle.rss.clients;
import com.oppo.shuttle.rss.clients.handler.Request;
import com.oppo.shuttle.rss.clients.handler.ResponseCallback;
import com.oppo.shuttle.rss.common.*;
import com.oppo.shuttle.rss.exceptions.Ors2Exception;
import com.oppo.shuttle.rss.exceptions.Ors2NetworkException;
import com.oppo.shuttle.rss.messages.ShufflePacket;
import org.apache.commons.lang3.RandomUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.shuffle.Ors2Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Tuple2;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* netty nio client
*/
public class NettyClient {
private static final Logger logger = LoggerFactory.getLogger(NettyClient.class);
private final Ors2ServerSwitchGroup serverGroup;
private final AppTaskInfo taskInfo;
private final boolean mapWriteDispersion;
private final AtomicInteger readySend = new AtomicInteger(0);
private final AtomicInteger sendFinish = new AtomicInteger(0);
private final Semaphore semaphore;
private final long netWorkTimeout;
private final int ioMaxRetry;
private final long retryBaseWaitTime;
private final boolean flowControlEnable;
private final ResponseCallback callback;
private final Ors2ClientFactory clientFactory;
public NettyClient(List<Ors2ServerGroup> groupList, SparkConf conf, AppTaskInfo taskInfo, Ors2ClientFactory clientFactory) {
netWorkTimeout = clientFactory.getNetWorkTimeout();
ioMaxRetry = Math.max((int) conf.get(Ors2Config.sendDataMaxRetries()), 1);
retryBaseWaitTime = (long) conf.get(Ors2Config.retryBaseWaitTime());
flowControlEnable = (boolean) conf.get(Ors2Config.flowControlEnable());
long networkSlowTime = (long) conf.get(Ors2Config.networkSlowTime());
mapWriteDispersion = (boolean) conf.get(Ors2Config.mapWriteDispersion());
int workerRetryNumber = (int) conf.get(Ors2Config.workerRetryNumber());
this.taskInfo = taskInfo;
semaphore = new Semaphore((int) conf.get(Ors2Config.maxFlyingPackageNum()));
this.clientFactory = clientFactory;
logger.info("NettyClient create success. ioThreads = {} , netWorkTimeout = {} ms, ioMaxRetry = {} times, retryBaseWaitTime = {} ms, networkSlowTime = {} ms",
clientFactory.getIoThreads(), netWorkTimeout, ioMaxRetry, retryBaseWaitTime, networkSlowTime);
this.serverGroup = new Ors2ServerSwitchGroup(groupList, taskInfo.getMapId(), workerRetryNumber, mapWriteDispersion);
callback = new ResponseCallback() {
@Override
public void onSuccess(Request request) {
semaphore.release();
sendFinish.incrementAndGet();
}
public boolean exceedMaxRetryNumber(int retry) {
if (retry >= ioMaxRetry) {
String msg = String.format("write for task %s data send fail, retries exceeding the maximum limit of %s times",
taskInfo.getMapId(), ioMaxRetry);
clientFactory.setException(new Ors2NetworkException(msg));
sendFinish.incrementAndGet();
semaphore.release();
return true;
} else {
return false;
}
}
@Override
public void onFailure(Request request, Throwable e) {
if (exceedMaxRetryNumber(request.getRetry())) {
return;
}
Request retryRequest = createRetryRequest(request, false);
long wait = getWaitTime(retryRequest.getRetry());
logger.warn("write for task {} data send fail: {}, retry the {} time, wait {} mills, id {}",
taskInfo.getMapId(), e.getMessage(), retryRequest.getRetry(), wait, request.id());
clientFactory.schedule(retryRequest::writeBuild, wait, TimeUnit.MILLISECONDS);
}
@Override
public void onError(Request request, Throwable e) {
if (exceedMaxRetryNumber(request.getRetry())) {
return;
}
Request retryRequest = createRetryRequest(request, true);
logger.warn("write for task {} data send network error: {}, retry the {} time , id {}",
taskInfo.getMapId(), e.getMessage(), retryRequest.getRetry(), request.id());
retryRequest.writeBuild();
}
};
}
public ShuffleClient getBuildClient(Ors2WorkerDetail server) {
return clientFactory.getBuildClient(server);
}
public ShuffleClient getDataClient(Ors2WorkerDetail server) {
return clientFactory.getDataClient(server);
}
public void send(int workerId, ShufflePacket packet) {
try {
while (!semaphore.tryAcquire(Constants.CLIENT_TOKEN_WAIT_MS, TimeUnit.MILLISECONDS)) {
clientFactory.checkNetworkException();
logger.warn(String.format("The network request is blocked, " +
"and the idle token cannot be obtained for more than %s ms ", Constants.CLIENT_TOKEN_WAIT_MS));
}
Tuple2<ShuffleClient, ShuffleClient> tuple2 = getClient(workerId, 0, Optional.empty());
Request request = new Request(flowControlEnable, packet, workerId, tuple2._1, tuple2._2, callback);
readySend.incrementAndGet();
request.writeBuild();
}catch (Exception e) {
logger.error("Send package to shuffle worker failed: ", e);
throw new Ors2Exception(e);
}
}
public void close() {
// pass
}
public void waitFinish() {
int v = getRemainPackageNum();
SleepWaitTimeout waitTimeout = new SleepWaitTimeout(netWorkTimeout);
int waitNumber = 0;
while (v != 0) {
clientFactory.checkNetworkException();
try {
long sleepTime = Math.min(Constants.POLL_WAIT_MS, ((++waitNumber / 5) + 1) * 50L);
waitTimeout.sleepAdd(sleepTime);
v = getRemainPackageNum();
} catch (TimeoutException e) {
throw new RuntimeException("Waiting for the request to complete timed out", e);
}
}
logger.info("Wait for the data packet send finish, cost {} ms(times {})",
waitTimeout.getDurationMs(), waitNumber);
}
public int getFinishPackageNum() {
return sendFinish.get();
}
public int getRemainPackageNum() {
return readySend.get() - sendFinish.get();
}
public long getWaitTime(int nextRetry) {
int i = RandomUtils.nextInt(1, 11);
return i * retryBaseWaitTime;
}
public static String requestId() {
return "ors2_" + Math.abs(UUID.randomUUID().getLeastSignificantBits());
}
public Request createRetryRequest(Request request, boolean channelError) {
int retry = request.addRetry();
Optional<Ors2WorkerDetail> errorServer;
if (channelError) {
errorServer = Optional.of(request.getServer());
} else {
errorServer = Optional.empty();
}
Tuple2<ShuffleClient, ShuffleClient> tuple2 = getClient(request.getWorkerId(), retry, errorServer);
return new Request(flowControlEnable, request.getPacket(), request.getWorkerId(),
tuple2._1, tuple2._2, request.getCallback());
}
public Ors2ClientFactory getClientFactory() {
return clientFactory;
}
public Tuple2<ShuffleClient, ShuffleClient> getClient(int workerId, int retry, Optional<Ors2WorkerDetail> errorServer) {
int loopTimes = serverGroup.availableSize(workerId);
RuntimeException lastException = null;
Ors2WorkerDetail useServer = serverGroup.getServer(workerId, retry, errorServer);
for (int i = 0; i < loopTimes; i++) {
try {
ShuffleClient buildClient = null;
if (flowControlEnable) {
buildClient = getBuildClient(useServer);
}
ShuffleClient dataClient = getDataClient(useServer);
return Tuple2.apply(buildClient, dataClient);
} catch (RuntimeException e) {
lastException = e;
logger.error("connect server {} fail: {}", useServer, e.getMessage());
useServer = serverGroup.getServer(workerId, retry, Optional.of(useServer));
}
}
if (lastException != null) {
clientFactory.setException(lastException);
throw lastException;
} else {
return null;
}
}
}
```
|
```package com.oppo.shuttle.rss.common;
import org.testng.annotations.Test;
import java.util.Base64;
/**
* Test for ShuffleInfo class serialize&deserialize
*/
public class ShuffleInfoTest {
@Test
public void serializeToString() throws Exception {
ShuffleInfo.MapShuffleInfo.Builder builder = ShuffleInfo.MapShuffleInfo.newBuilder();
builder.setMapId(1);
builder.setAttemptId(1);
builder.setShuffleWorkerGroupNum(3);
String st = Base64.getEncoder().encodeToString(builder.build().toByteArray());
byte[] bytes = Base64.getDecoder().decode(st);
ShuffleInfo.MapShuffleInfo mapShuffleInfo = ShuffleInfo.MapShuffleInfo.parseFrom(bytes);
String deStr = Base64.getEncoder().encodeToString(mapShuffleInfo.toByteArray());
assert st.equals(deStr) : "ShuffleInfo protobuf serialize&deserialize test failed";
}
}
```
|
Please help me generate a test for this class.
|
```package com.oppo.shuttle.rss.common;
public final class ShuffleInfo {
private ShuffleInfo() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
public interface MapShuffleInfoOrBuilder extends
// @@protoc_insertion_point(interface_extends:shuffle.MapShuffleInfo)
com.google.protobuf.MessageOrBuilder {
/**
* <code>int32 mapId = 1;</code>
* @return The mapId.
*/
int getMapId();
/**
* <code>int64 attemptId = 2;</code>
* @return The attemptId.
*/
long getAttemptId();
/**
* <code>int32 shuffleWorkerGroupNum = 3;</code>
* @return The shuffleWorkerGroupNum.
*/
int getShuffleWorkerGroupNum();
}
/**
* Protobuf type {@code shuffle.MapShuffleInfo}
*/
public static final class MapShuffleInfo extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:shuffle.MapShuffleInfo)
MapShuffleInfoOrBuilder {
private static final long serialVersionUID = 0L;
// Use MapShuffleInfo.newBuilder() to construct.
private MapShuffleInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MapShuffleInfo() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new MapShuffleInfo();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private MapShuffleInfo(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 8: {
mapId_ = input.readInt32();
break;
}
case 16: {
attemptId_ = input.readInt64();
break;
}
case 24: {
shuffleWorkerGroupNum_ = input.readInt32();
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return ShuffleInfo.internal_static_shuffle_MapShuffleInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return ShuffleInfo.internal_static_shuffle_MapShuffleInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
ShuffleInfo.MapShuffleInfo.class, ShuffleInfo.MapShuffleInfo.Builder.class);
}
public static final int MAPID_FIELD_NUMBER = 1;
private int mapId_;
/**
* <code>int32 mapId = 1;</code>
* @return The mapId.
*/
@java.lang.Override
public int getMapId() {
return mapId_;
}
public static final int ATTEMPTID_FIELD_NUMBER = 2;
private long attemptId_;
/**
* <code>int64 attemptId = 2;</code>
* @return The attemptId.
*/
@java.lang.Override
public long getAttemptId() {
return attemptId_;
}
public static final int SHUFFLEWORKERGROUPNUM_FIELD_NUMBER = 3;
private int shuffleWorkerGroupNum_;
/**
* <code>int32 shuffleWorkerGroupNum = 3;</code>
* @return The shuffleWorkerGroupNum.
*/
@java.lang.Override
public int getShuffleWorkerGroupNum() {
return shuffleWorkerGroupNum_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (mapId_ != 0) {
output.writeInt32(1, mapId_);
}
if (attemptId_ != 0L) {
output.writeInt64(2, attemptId_);
}
if (shuffleWorkerGroupNum_ != 0) {
output.writeInt32(3, shuffleWorkerGroupNum_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (mapId_ != 0) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(1, mapId_);
}
if (attemptId_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(2, attemptId_);
}
if (shuffleWorkerGroupNum_ != 0) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(3, shuffleWorkerGroupNum_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof ShuffleInfo.MapShuffleInfo)) {
return super.equals(obj);
}
ShuffleInfo.MapShuffleInfo other = (ShuffleInfo.MapShuffleInfo) obj;
if (getMapId()
!= other.getMapId()) return false;
if (getAttemptId()
!= other.getAttemptId()) return false;
if (getShuffleWorkerGroupNum()
!= other.getShuffleWorkerGroupNum()) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + MAPID_FIELD_NUMBER;
hash = (53 * hash) + getMapId();
hash = (37 * hash) + ATTEMPTID_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getAttemptId());
hash = (37 * hash) + SHUFFLEWORKERGROUPNUM_FIELD_NUMBER;
hash = (53 * hash) + getShuffleWorkerGroupNum();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static ShuffleInfo.MapShuffleInfo parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static ShuffleInfo.MapShuffleInfo parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static ShuffleInfo.MapShuffleInfo parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static ShuffleInfo.MapShuffleInfo parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static ShuffleInfo.MapShuffleInfo parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static ShuffleInfo.MapShuffleInfo parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static ShuffleInfo.MapShuffleInfo parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static ShuffleInfo.MapShuffleInfo parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static ShuffleInfo.MapShuffleInfo parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static ShuffleInfo.MapShuffleInfo parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static ShuffleInfo.MapShuffleInfo parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static ShuffleInfo.MapShuffleInfo parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(ShuffleInfo.MapShuffleInfo prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code shuffle.MapShuffleInfo}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:shuffle.MapShuffleInfo)
ShuffleInfo.MapShuffleInfoOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return ShuffleInfo.internal_static_shuffle_MapShuffleInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return ShuffleInfo.internal_static_shuffle_MapShuffleInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
ShuffleInfo.MapShuffleInfo.class, ShuffleInfo.MapShuffleInfo.Builder.class);
}
// Construct using com.andes.ors2.common.ShuffleInfo.MapShuffleInfo.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
mapId_ = 0;
attemptId_ = 0L;
shuffleWorkerGroupNum_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return ShuffleInfo.internal_static_shuffle_MapShuffleInfo_descriptor;
}
@java.lang.Override
public ShuffleInfo.MapShuffleInfo getDefaultInstanceForType() {
return ShuffleInfo.MapShuffleInfo.getDefaultInstance();
}
@java.lang.Override
public ShuffleInfo.MapShuffleInfo build() {
ShuffleInfo.MapShuffleInfo result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public ShuffleInfo.MapShuffleInfo buildPartial() {
ShuffleInfo.MapShuffleInfo result = new ShuffleInfo.MapShuffleInfo(this);
result.mapId_ = mapId_;
result.attemptId_ = attemptId_;
result.shuffleWorkerGroupNum_ = shuffleWorkerGroupNum_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof ShuffleInfo.MapShuffleInfo) {
return mergeFrom((ShuffleInfo.MapShuffleInfo)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(ShuffleInfo.MapShuffleInfo other) {
if (other == ShuffleInfo.MapShuffleInfo.getDefaultInstance()) return this;
if (other.getMapId() != 0) {
setMapId(other.getMapId());
}
if (other.getAttemptId() != 0L) {
setAttemptId(other.getAttemptId());
}
if (other.getShuffleWorkerGroupNum() != 0) {
setShuffleWorkerGroupNum(other.getShuffleWorkerGroupNum());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
ShuffleInfo.MapShuffleInfo parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (ShuffleInfo.MapShuffleInfo) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int mapId_ ;
/**
* <code>int32 mapId = 1;</code>
* @return The mapId.
*/
@java.lang.Override
public int getMapId() {
return mapId_;
}
/**
* <code>int32 mapId = 1;</code>
* @param value The mapId to set.
* @return This builder for chaining.
*/
public Builder setMapId(int value) {
mapId_ = value;
onChanged();
return this;
}
/**
* <code>int32 mapId = 1;</code>
* @return This builder for chaining.
*/
public Builder clearMapId() {
mapId_ = 0;
onChanged();
return this;
}
private long attemptId_ ;
/**
* <code>int64 attemptId = 2;</code>
* @return The attemptId.
*/
@java.lang.Override
public long getAttemptId() {
return attemptId_;
}
/**
* <code>int64 attemptId = 2;</code>
* @param value The attemptId to set.
* @return This builder for chaining.
*/
public Builder setAttemptId(long value) {
attemptId_ = value;
onChanged();
return this;
}
/**
* <code>int64 attemptId = 2;</code>
* @return This builder for chaining.
*/
public Builder clearAttemptId() {
attemptId_ = 0L;
onChanged();
return this;
}
private int shuffleWorkerGroupNum_ ;
/**
* <code>int32 shuffleWorkerGroupNum = 3;</code>
* @return The shuffleWorkerGroupNum.
*/
@java.lang.Override
public int getShuffleWorkerGroupNum() {
return shuffleWorkerGroupNum_;
}
/**
* <code>int32 shuffleWorkerGroupNum = 3;</code>
* @param value The shuffleWorkerGroupNum to set.
* @return This builder for chaining.
*/
public Builder setShuffleWorkerGroupNum(int value) {
shuffleWorkerGroupNum_ = value;
onChanged();
return this;
}
/**
* <code>int32 shuffleWorkerGroupNum = 3;</code>
* @return This builder for chaining.
*/
public Builder clearShuffleWorkerGroupNum() {
shuffleWorkerGroupNum_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:shuffle.MapShuffleInfo)
}
// @@protoc_insertion_point(class_scope:shuffle.MapShuffleInfo)
private static final ShuffleInfo.MapShuffleInfo DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new ShuffleInfo.MapShuffleInfo();
}
public static ShuffleInfo.MapShuffleInfo getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<MapShuffleInfo>
PARSER = new com.google.protobuf.AbstractParser<MapShuffleInfo>() {
@java.lang.Override
public MapShuffleInfo parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new MapShuffleInfo(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<MapShuffleInfo> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<MapShuffleInfo> getParserForType() {
return PARSER;
}
@java.lang.Override
public ShuffleInfo.MapShuffleInfo getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_shuffle_MapShuffleInfo_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_shuffle_MapShuffleInfo_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\031shuffle_common_info.proto\022\007shuffle\"Q\n\016" +
"MapShuffleInfo\022\r\n\005mapId\030\001 \001(\005\022\021\n\tattempt" +
"Id\030\002 \001(\003\022\035\n\025shuffleWorkerGroupNum\030\003 \001(\005B" +
"$\n\025com.andes.ors2.commonB\013ShuffleInfob\006p" +
"roto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
});
internal_static_shuffle_MapShuffleInfo_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_shuffle_MapShuffleInfo_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_shuffle_MapShuffleInfo_descriptor,
new java.lang.String[] { "MapId", "AttemptId", "ShuffleWorkerGroupNum", });
}
// @@protoc_insertion_point(outer_class_scope)
}
```
|
```package com.oppo.shuttle.rss;
import com.oppo.shuttle.rss.common.ServerListDir;
import com.oppo.shuttle.rss.server.master.ShuffleDataDirClear;
import com.oppo.shuttle.rss.storage.ShuffleFileStorage;
import com.oppo.shuttle.rss.storage.fs.FileStatus;
import com.oppo.shuttle.rss.testutil.TestShuffleMaster;
import org.testng.annotations.Test;
import java.util.List;
public class ShuffleMasterTest {
@Test
public void startAndShutdown() {
TestShuffleMaster runningServer = TestShuffleMaster.createRunningServer();
runningServer.shutdown();
}
@Test
public void clearShuffleDirTest() throws InterruptedException {
ShuffleDataDirClear shuffleDataDirClear = new ShuffleDataDirClear(10000);
ShuffleFileStorage storage = new ShuffleFileStorage("ors2-data");
storage.createDirectories("ors2-data/clear/a");
storage.createDirectories("ors2-data/clear/b");
storage.createDirectories("ors2-data/clear/c");
Thread.sleep(9000);
shuffleDataDirClear.execute(new ServerListDir("ors2-data/clear", null));
List<FileStatus> list = storage.listStatus("ors2-data/clear");
assert (list.size() == 3);
Thread.sleep(1000);
shuffleDataDirClear.execute(new ServerListDir("ors2-data/clear", null));
list = storage.listStatus("ors2-data/clear");
assert (list.size() == 0);
}
}
```
|
Please help me generate a test for this class.
|
```package com.oppo.shuttle.rss.server.master;
import com.oppo.shuttle.rss.BuildVersion;
import com.oppo.shuttle.rss.ShuffleServerConfig;
import com.oppo.shuttle.rss.common.Constants;
import com.oppo.shuttle.rss.exceptions.Ors2Exception;
import com.oppo.shuttle.rss.metadata.ZkShuffleServiceManager;
import com.oppo.shuttle.rss.metrics.Ors2MetricsExport;
import com.oppo.shuttle.rss.server.ShuffleServer;
import com.oppo.shuttle.rss.util.NetworkUtils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoopGroup;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.parquet.Strings;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
/**
* ShuffleMaster supplies three main functions:
* 1. manage ShuffleWorker, add ShuffleWorker to or release it from blacklist
* 2. dispatch shuffle workers for job requesting, using plugin dispatch strategy (default RoundRobin)
* 3. route job to request different shuffle cluster resources, update shuffle service gracefully
*
* @author oppo
*/
public class ShuffleMaster extends ShuffleServer {
private static final Logger logger = LoggerFactory.getLogger(ShuffleMaster.class);
private final ShuffleServerConfig masterConfig;
private final String localIp;
private String serverId;
private EventLoopGroup shuffleMasterEventLoopGroup;
private EventLoopGroup httpEventLoopGroup;
private ZkShuffleServiceManager zkManager;
private int masterPort;
private int httpPort;
private static final AtomicBoolean isLeader = new AtomicBoolean(true);
private static String masterWatchPath;
private List<Channel> channels = new ArrayList<>(2);
private ShuffleWorkerStatusManager shuffleWorkerStatusManager;
private ShuffleMasterClusterManager shuffleMasterClusterManager;
public ShuffleMaster(ShuffleServerConfig masterConfig) {
this(masterConfig, null);
}
public ShuffleMaster(ShuffleServerConfig masterConfig, ZkShuffleServiceManager zkManager) {
this.masterConfig = masterConfig;
this.localIp = NetworkUtils.getLocalIp();
this.zkManager = zkManager;
init();
}
public int getMasterPort() {
return masterPort;
}
@Override
public String getServerId() {
if (Strings.isNullOrEmpty(serverId)) {
serverId = String.format("%s:%d", NetworkUtils.getLocalIp(), getMasterPort());
}
return serverId;
}
@Override
protected void init() {
this.masterPort = masterConfig.getMasterPort();
this.httpPort = masterConfig.getHttpPort();
this.serverId = getServerId();
shuffleMasterEventLoopGroup = initEventLoopGroups(masterConfig.isUseEpoll(),
masterConfig.getHeartBeatThreads(), "io-master-event");
httpEventLoopGroup = initEventLoopGroups(masterConfig.isUseEpoll(),
Constants.MASTER_HTTP_SERVER_THREADS, "io-master-http");
if (zkManager == null) {
this.zkManager = new ZkShuffleServiceManager(
masterConfig.getZooKeeperServers(),
masterConfig.getNetworkTimeout(),
masterConfig.getNetworkRetries());
}
}
@Override
protected void initChannel(String serverId, ChannelType type) throws InterruptedException {
switch (type) {
case MASTER_HTTP_CHANNEL:
String leaderAddr = createLeaderLatch();
Supplier<ChannelHandler[]> httpSupplierHandlers = () -> new ChannelHandler[] {
new HttpServerCodec(),
new HttpObjectAggregator(512 * 1024),
new ShuffleMasterHttpHandler(isLeader, leaderAddr)
};
ServerBootstrap httpBootstrap = initServerBootstrap(
httpEventLoopGroup,
httpEventLoopGroup,
masterConfig,
httpSupplierHandlers);
Channel httpChannel = bindPort(httpBootstrap, httpPort);
channels.add(httpChannel);
logger.info("Init master http channel finished, port: {}:{}.", localIp, httpPort);
break;
case MASTER_AGGREGATE_CHANNEL:
ShuffleMasterDispatcher shuffleMasterDispatcher = getShuffleMasterDispatcher();
// request controller
ApplicationRequestController applicationRequestController =
new ApplicationRequestController(
masterConfig.getNumAppResourcePerInterval(),
masterConfig.getAppControlInterval(),
masterConfig.getUpdateDelay(),
masterConfig.getAppNamePreLen(),
masterConfig.getFilterExcludes());
Supplier<ChannelHandler[]> masterSupplierHandlers = () -> new ChannelHandler[] {
new LengthFieldBasedFrameDecoder(134217728, 4, 4),
new ShuffleMasterHandler(shuffleMasterDispatcher, shuffleWorkerStatusManager, applicationRequestController)
};
ServerBootstrap masterBootstrap = initServerBootstrap(
shuffleMasterEventLoopGroup,
shuffleMasterEventLoopGroup,
masterConfig, masterSupplierHandlers);
Channel masterChannel = bindPort(masterBootstrap, masterPort);
channels.add(masterChannel);
logger.info("Init master aggregate channel finished, port: {}:{}.", localIp, masterPort);
break;
default:
logger.warn("InitChannel for shuffle master, invalid channel type: {}", type);
break;
}
}
public ShuffleMasterDispatcher getShuffleMasterDispatcher() {
String shuffleMasterDispatcher = masterConfig.getDispatchStrategy();
try {
Class<?> clazz = Class.forName(masterConfig.getDispatchStrategy());
Constructor<?> constructor = clazz.getConstructor(ShuffleServerConfig.class);
return (ShuffleMasterDispatcher) constructor.newInstance(masterConfig);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
throw new Ors2Exception(String.format("Failed to create ShuffleMasterDispatcher instance from class name %s", shuffleMasterDispatcher), e);
}
}
@Override
public void run() throws InterruptedException {
logger.info("Starting shuffle master : {}", this.serverId);
BlackListRefresher blackListRefresher =
new BlackListRefresher(masterConfig.getUpdateDelay(), masterConfig.getBlackListRefreshInterval());
shuffleWorkerStatusManager = new ShuffleWorkerStatusManager(masterConfig, blackListRefresher);
shuffleWorkerStatusManager.updateStart();
// watch dagId and storage type
shuffleMasterClusterManager = new ShuffleMasterClusterManager(zkManager);
masterWatchPath = this.zkManager.getMasterWatchPath(masterConfig.getMasterName());
String dataCenter = masterConfig.getDataCenter();
String cluster = masterConfig.getCluster();
logger.info("Registering shuffle master, data center: {}, cluster: {}, server id: {}, ",
dataCenter, cluster, serverId);
this.zkManager.createNode(
masterWatchPath,
serverId.getBytes(StandardCharsets.UTF_8),
CreateMode.PERSISTENT);
logger.info("Create master watch path succeed : {}", masterWatchPath);
initChannel(serverId, ChannelType.MASTER_AGGREGATE_CHANNEL);
initChannel(serverId, ChannelType.MASTER_HTTP_CHANNEL);
}
private String createLeaderLatch() {
LeaderLatch leaderLatch = this.zkManager.createLeaderLatcher(masterConfig.getMasterName(), serverId);
String leaderHostAndPort = new String(zkManager.getZkNodeData(masterWatchPath), StandardCharsets.UTF_8);
try {
leaderLatch.start();
} catch (Exception e) {
throw new RuntimeException("start leaderLatch Exception: " + e.getCause());
}
isLeader.getAndSet(leaderLatch.hasLeadership());
leaderLatch.addListener(new LeaderLatchListener() {
@Override
public void isLeader() {
// set current server data to zk node
logger.info("Current host is leader");
for (int i = 0; i < 3; i++) {
try {
zkManager.setData(masterWatchPath, serverId.getBytes());
isLeader.getAndSet(true);
return;
} catch (Exception e) {
logger.warn(e.getMessage());
}
}
// todo: shutdown current master?
logger.error("shutdown master since it cannot work properly");
ShuffleMaster.this.shutdown();
}
@Override
public void notLeader() {
}
});
return String.format("%s:%s", leaderHostAndPort.split(":")[0], masterConfig.getHttpPort());
}
@Override
public void shutdown() {
super.shutdown();
shutdown(false);
}
public void shutdown(boolean wait) {
try {
zkManager.close();
} catch (Throwable e) {
logger.warn("Unable to shutdown metadata store:", e);
}
try {
shuffleMasterClusterManager.close();
} catch (IOException e) {
logger.warn("Close shuffleWorkerClusterManager error, ", e);
}
closeChannels(channels);
shutdownEventLoopGroup(shuffleMasterEventLoopGroup, "ShuffleMasterGroup");
shutdownEventLoopGroup(httpEventLoopGroup, "ShuffleMasterHttpGroup");
logger.info("ShuffleMaster shutdown finished: {}", serverId);
}
public static void main(String[] args) throws Exception {
ShuffleServerConfig masterConfig = ShuffleServerConfig.buildFromArgs(args);
logger.info("Starting master project version: {}, git commit version: {}) with config: {}",
BuildVersion.projectVersion, BuildVersion.gitCommitVersion, masterConfig.getShuffleMasterConfig());
ShuffleMaster master = new ShuffleMaster(masterConfig);
try {
master.run();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
addShutdownHook(master);
Ors2MetricsExport.initialize(master.getServerId());
}
}
```
|
```package com.oppo.shuttle.rss.master;
import com.oppo.shuttle.rss.server.master.ApplicationRequestController;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ApplicationRequestControllerTest {
@Test
public void testOneAppRequest() throws ExecutionException, InterruptedException {
ApplicationRequestController applicationRequestController =
new ApplicationRequestController(3, 10000L, 5000, 10,"");
applicationRequestController.updateStart();
ExecutorService executorService = Executors.newFixedThreadPool(2);
for (int i = 0; i < 5; i++) {
Future<Object> result =
executorService.submit(() -> applicationRequestController.requestCome("TEST1", "application_166859_2765"));
Assert.assertTrue((Boolean) result.get());
}
}
@Test
public void testMultiAppRequest() {
ApplicationRequestController applicationRequestController =
new ApplicationRequestController(2, 3000L, 5000, 4, "");
applicationRequestController.updateStart();
boolean result1 = applicationRequestController.requestCome("TEST1", "application_16359_275");
Assert.assertTrue(result1);
boolean result2 = applicationRequestController.requestCome("TEST2", "application_16359_276");
Assert.assertTrue(result2);
boolean result3 = applicationRequestController.requestCome("TEST3", "application_16359_277");
Assert.assertFalse(result3);
}
@Test
public void testControllerRefresh() throws InterruptedException {
ApplicationRequestController applicationRequestController =
new ApplicationRequestController(2, 1000L, 2000, 4, "");
applicationRequestController.updateStart();
boolean result1 = applicationRequestController.requestCome("TEST1", "application_164359_275");
Assert.assertTrue(result1);
boolean result2 = applicationRequestController.requestCome("TEST2", "application_164359_276");
Assert.assertTrue(result2);
Thread.sleep(5000);
boolean result3 = applicationRequestController.requestCome("TEST3", "application_164359_277");
Assert.assertTrue(result3);
}
}
```
|
Please help me generate a test for this class.
|
```package com.oppo.shuttle.rss.server.master;
import com.oppo.shuttle.rss.util.ScheduledThreadPoolUtils;
import com.oppo.shuttle.rss.util.SimilarityUtils;
import io.netty.util.internal.ConcurrentSet;
import org.apache.commons.lang3.StringUtils;
import org.apache.directory.api.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class ApplicationRequestController {
private static final Logger logger = LoggerFactory.getLogger(ApplicationRequestController.class);
private final Map<String, ResourceHolder> appMap = new ConcurrentHashMap<>(10);
private final long appControlInterval;
private final int resourceNum;
private final int appNamePreLen;
private final String filterExcludes;
private final String[] excludePrefixes;
private final long updateDelay;
private static final long WAIT_RESOURCE_TIMEOUT = 10L;
private static final String FILTER_SEPARATOR = ",";
public ApplicationRequestController(
int resourceNum,
long appControlInterval,
long updateDelay,
int appNamePreLen,
String filterExcludes) {
this.resourceNum = resourceNum;
this.appControlInterval = appControlInterval;
this.updateDelay = updateDelay;
this.filterExcludes = filterExcludes;
this.appNamePreLen = appNamePreLen;
excludePrefixes = parseFilterExcludes();
updateStart();
}
public void updateStart() {
ScheduledThreadPoolUtils.scheduleAtFixedRate(
this::clearAppMap,
updateDelay,
appControlInterval);
}
private void clearAppMap() {
long currentTimeMillis = System.currentTimeMillis();
if (appMap.size() > 0) {
for (Map.Entry<String, ResourceHolder> appResource : appMap.entrySet()) {
if (appResource.getValue().isResourceExpired(currentTimeMillis, appControlInterval)) {
appMap.remove(appResource.getKey());
}
}
}
}
public boolean requestCome(String appName, String appId) {
for (String excludePrefix : excludePrefixes) {
if (appName.startsWith(excludePrefix.trim())) {
return true;
}
}
String appSpace = getMatching(appName);
ResourceHolder resourceHolder =
appSpace == null ?
appMap.computeIfAbsent(appName, t -> new ResourceHolder(resourceNum))
: appMap.get(appSpace);
if (resourceHolder.holderList.contains(appId)) {
return true;
} else {
Semaphore resource = resourceHolder.semaphore;
try {
logger.info("Current resource holders are: {}", resourceHolder.getHolderList());
if (resource.tryAcquire(WAIT_RESOURCE_TIMEOUT, TimeUnit.SECONDS)) {
resourceHolder.holderList.add(appId);
return true;
}
logger.info("{} request can't get resource in {} seconds, return fail.", appId, WAIT_RESOURCE_TIMEOUT);
return false;
} catch (InterruptedException e) {
logger.warn("Request can't get resource in {} seconds", WAIT_RESOURCE_TIMEOUT, e);
return false;
}
}
}
private String[] parseFilterExcludes() {
if (!Strings.isEmpty(filterExcludes)) {
if (filterExcludes.contains(FILTER_SEPARATOR)) {
return StringUtils.split(filterExcludes, FILTER_SEPARATOR);
} else {
return new String[]{filterExcludes};
}
} else {
return new String[0];
}
}
private String getMatching(String appName){
for (String as : appMap.keySet()) {
if (SimilarityUtils.judgeSimilarity(as, appName, appNamePreLen)) {
return as;
}
}
return null;
}
static class ResourceHolder {
private final Set<String> holderList;
private final Semaphore semaphore;
private final long startTimeMillis;
public ResourceHolder(int resourceNum) {
this.semaphore = new Semaphore(resourceNum, true);
startTimeMillis = System.currentTimeMillis();
holderList = new ConcurrentSet<>();
}
public boolean isResourceExpired(
long currentTimeMillis,
long appControlInterval) {
return currentTimeMillis - startTimeMillis > appControlInterval;
}
public Set<String> getHolderList() {
return holderList;
}
}
}
```
|
```package com.oppo.shuttle.rss.master;
import com.oppo.shuttle.rss.server.master.BlackListRefresher;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
public class BlackListRefresherTest {
@Test
public void testBlackListConf() throws InterruptedException {
BlackListRefresher blackListRefresher = new BlackListRefresher(0, 3000);
Thread.sleep(3000);
List<String> workerBlackList = blackListRefresher.getWorkerBlackList();
Assert.assertEquals(workerBlackList.size(), 1);
}
}
```
|
Please help me generate a test for this class.
|
```package com.oppo.shuttle.rss.server.master;
import com.oppo.shuttle.rss.util.ConfUtil;
import com.oppo.shuttle.rss.util.ScheduledThreadPoolUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class BlackListRefresher {
private static final Logger logger = LoggerFactory.getLogger(BlackListRefresher.class);
private List<String> workerBlackList;
private final long updateDelay;
private final long blackListRefreshInterval;
public BlackListRefresher(
long updateDelay,
long blackListRefreshInterval) {
this.updateDelay = updateDelay;
this.blackListRefreshInterval = blackListRefreshInterval;
refreshStart();
}
public void refreshStart(){
ScheduledThreadPoolUtils.scheduleAtFixedRate(
this::refreshBlackList,
updateDelay,
blackListRefreshInterval);
}
private void refreshBlackList(){
workerBlackList = ConfUtil.getWorkerBlackList();
logger.info("Refresh {} workers to black list from config", workerBlackList.size());
workerBlackList.forEach(ShuffleWorkerStatusManager::setToBlackStatus);
}
public List<String> getWorkerBlackList() {
return workerBlackList;
}
}
```
|
```package org.oscim.test;
import org.oscim.gdx.GdxMapApp;
import org.oscim.layers.tile.bitmap.BitmapTileLayer;
import org.oscim.layers.tile.buildings.S3DBLayer;
import org.oscim.tiling.TileSource;
import org.oscim.tiling.source.bitmap.DefaultSources;
import org.oscim.tiling.source.oscimap4.OSciMap4TileSource;
public class S3DBLayerTest extends GdxMapApp {
@Override
public void createLayers() {
//VectorTileLayer l = mMap.setBaseMap(new OSciMap4TileSource());
//mMap.setTheme(VtmThemes.DEFAULT);
mMap.setBaseMap(new BitmapTileLayer(mMap, DefaultSources.STAMEN_TONER.build()));
TileSource ts = OSciMap4TileSource
.builder()
.url("http://opensciencemap.org/tiles/s3db")
.build();
S3DBLayer tl = new S3DBLayer(mMap, ts);
mMap.layers().add(tl);
mMap.setMapPosition(53.08, 8.82, 1 << 17);
}
public static void main(String[] args) {
init();
run(new S3DBLayerTest(), null, 400);
}
}
```
|
Please help me generate a test for this class.
|
```package org.oscim.layers.tile.buildings;
import org.oscim.backend.canvas.Color;
import org.oscim.layers.tile.TileLayer;
import org.oscim.layers.tile.TileManager;
import org.oscim.layers.tile.TileRenderer;
import org.oscim.map.Map;
import org.oscim.renderer.GLViewport;
import org.oscim.renderer.LayerRenderer;
import org.oscim.renderer.OffscreenRenderer;
import org.oscim.renderer.OffscreenRenderer.Mode;
import org.oscim.tiling.TileSource;
import org.oscim.utils.ColorUtil;
import org.oscim.utils.ColorsCSS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class S3DBLayer extends TileLayer {
static final Logger log = LoggerFactory.getLogger(S3DBLayer.class);
private final static int MAX_CACHE = 32;
private final static int SRC_ZOOM = 16;
/* TODO get from theme */
private final static double HSV_S = 0.7;
private final static double HSV_V = 1.2;
private final TileSource mTileSource;
public S3DBLayer(Map map, TileSource tileSource) {
this(map, tileSource, true, false);
}
public S3DBLayer(Map map, TileSource tileSource, boolean fxaa, boolean ssao) {
super(map, new TileManager(map, MAX_CACHE));
setRenderer(new S3DBRenderer(fxaa, ssao));
mTileManager.setZoomLevel(SRC_ZOOM, SRC_ZOOM);
mTileSource = tileSource;
initLoader(2);
}
@Override
protected S3DBTileLoader createLoader() {
return new S3DBTileLoader(getManager(), mTileSource);
}
public static class S3DBRenderer extends TileRenderer {
LayerRenderer mRenderer;
public S3DBRenderer(boolean fxaa, boolean ssao) {
mRenderer = new BuildingRenderer(this, SRC_ZOOM, SRC_ZOOM, true, false);
if (fxaa || ssao) {
Mode mode = Mode.FXAA;
if (fxaa && ssao)
mode = Mode.SSAO_FXAA;
else if (ssao)
mode = Mode.SSAO;
mRenderer = new OffscreenRenderer(mode, mRenderer);
}
}
@Override
public synchronized void update(GLViewport v) {
super.update(v);
mRenderer.update(v);
setReady(mRenderer.isReady());
}
@Override
public synchronized void render(GLViewport v) {
mRenderer.render(v);
}
@Override
public boolean setup() {
mRenderer.setup();
return super.setup();
}
}
static int getColor(String color, boolean roof) {
if (color.charAt(0) == '#') {
int c = Color.parseColor(color, Color.CYAN);
/* hardcoded colors are way too saturated for my taste */
return ColorUtil.modHsv(c, 1.0, 0.4, HSV_V, true);
}
if (roof) {
if ("brown" == color)
return Color.get(120, 110, 110);
if ("red" == color)
return Color.get(235, 140, 130);
if ("green" == color)
return Color.get(150, 200, 130);
if ("blue" == color)
return Color.get(100, 50, 200);
}
if ("white" == color)
return Color.get(240, 240, 240);
if ("black" == color)
return Color.get(86, 86, 86);
if ("grey" == color || "gray" == color)
return Color.get(120, 120, 120);
if ("red" == color)
return Color.get(255, 190, 190);
if ("green" == color)
return Color.get(190, 255, 190);
if ("blue" == color)
return Color.get(190, 190, 255);
if ("yellow" == color)
return Color.get(255, 255, 175);
if ("darkgray" == color || "darkgrey" == color)
return Color.DKGRAY;
if ("lightgray" == color || "lightgrey" == color)
return Color.LTGRAY;
if ("transparent" == color)
return Color.get(0, 1, 1, 1);
Integer css = ColorsCSS.get(color);
if (css != null)
return ColorUtil.modHsv(css.intValue(), 1.0, HSV_S, HSV_V, true);
log.debug("unknown color:{}", color);
return 0;
}
static int getMaterialColor(String material, boolean roof) {
if (roof) {
if ("glass" == material)
return Color.fade(Color.get(130, 224, 255), 0.9f);
}
if ("roof_tiles" == material)
return Color.get(216, 167, 111);
if ("tile" == material)
return Color.get(216, 167, 111);
if ("concrete" == material ||
"cement_block" == material)
return Color.get(210, 212, 212);
if ("metal" == material)
return 0xFFC0C0C0;
if ("tar_paper" == material)
return 0xFF969998;
if ("eternit" == material)
return Color.get(216, 167, 111);
if ("tin" == material)
return 0xFFC0C0C0;
if ("asbestos" == material)
return Color.get(160, 152, 141);
if ("glass" == material)
return Color.get(130, 224, 255);
if ("slate" == material)
return 0xFF605960;
if ("zink" == material)
return Color.get(180, 180, 180);
if ("gravel" == material)
return Color.get(170, 130, 80);
if ("copper" == material)
// same as roof color:green
return Color.get(150, 200, 130);
if ("wood" == material)
return Color.get(170, 130, 80);
if ("grass" == material)
return 0xFF50AA50;
if ("stone" == material)
return Color.get(206, 207, 181);
if ("plaster" == material)
return Color.get(236, 237, 181);
if ("brick" == material)
return Color.get(255, 217, 191);
if ("stainless_steel" == material)
return Color.get(153, 157, 160);
if ("gold" == material)
return 0xFFFFD700;
log.debug("unknown material:{}", material);
return 0;
}
}
```
|
```package org.oscim.tiling.source.bitmap;
import static org.fest.assertions.api.Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.oscim.layers.tile.bitmap.BitmapTileLayer.FadeStep;
import org.oscim.tiling.ITileDataSource;
import org.oscim.tiling.source.HttpEngine;
import org.oscim.tiling.source.LwHttp;
import org.oscim.tiling.source.OkHttpEngine;
import org.oscim.tiling.source.UrlTileDataSource;
import org.oscim.tiling.source.UrlTileSource;
public class BitmapTileSourceTest {
private BitmapTileSource tileSource;
@Before
public void setUp() throws Exception {
tileSource = new BitmapTileSource("http://tile.openstreetmap.org", 0, 18);
}
@Test
public void shouldNotBeNull() throws Exception {
assertThat(tileSource).isNotNull();
}
@Test
public void shouldUseLwHttp() throws Exception {
LwHttp lwHttp = Mockito.mock(LwHttp.class);
tileSource.setHttpEngine(new TestHttpFactory(lwHttp));
ITileDataSource dataSource = tileSource.getDataSource();
dataSource.dispose();
Mockito.verify(lwHttp).close();
}
@Test
public void shouldUseOkHttp() throws Exception {
OkHttpEngine okHttp = Mockito.mock(OkHttpEngine.class);
tileSource.setHttpEngine(new TestHttpFactory(okHttp));
UrlTileDataSource dataSource = (UrlTileDataSource) tileSource.getDataSource();
dataSource.dispose();
Mockito.verify(okHttp).close();
}
@Test
public void shouldUseBuilderConfig() {
BitmapTileSource ts = BitmapTileSource.builder()
.url("http://example.com")
.zoomMax(42)
.zoomMin(23)
.fadeSteps(new FadeStep[] { new FadeStep(0, 10, 0.5f, 1.0f) })
.build();
assertThat(ts.getUrl().getHost()).isEqualTo("example.com");
assertThat(ts.getZoomLevelMin()).isEqualTo(23);
assertThat(ts.getZoomLevelMax()).isEqualTo(42);
assertThat(ts.getFadeSteps()).isNotNull();
}
/**
* Test factory that allows the specific {@link HttpEngine} instance to be
* set.
*/
class TestHttpFactory implements HttpEngine.Factory {
final HttpEngine engine;
public TestHttpFactory(HttpEngine engine) {
this.engine = engine;
}
@Override
public HttpEngine create(UrlTileSource tileSource) {
return engine;
}
}
}
```
|
Please help me generate a test for this class.
|
```package org.oscim.tiling.source.bitmap;
import java.io.IOException;
import java.io.InputStream;
import org.oscim.backend.CanvasAdapter;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.core.Tile;
import org.oscim.tiling.ITileDataSink;
import org.oscim.tiling.ITileDataSource;
import org.oscim.tiling.source.ITileDecoder;
import org.oscim.tiling.source.LwHttp;
import org.oscim.tiling.source.UrlTileDataSource;
import org.oscim.tiling.source.UrlTileSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BitmapTileSource extends UrlTileSource {
static final Logger log = LoggerFactory.getLogger(LwHttp.class);
public static class Builder<T extends Builder<T>> extends UrlTileSource.Builder<T> {
public Builder() {
super(null, "/{Z}/{X}/{Y}.png", 0, 17);
}
public BitmapTileSource build() {
return new BitmapTileSource(this);
}
}
protected BitmapTileSource(Builder<?> builder) {
super(builder);
}
@SuppressWarnings("rawtypes")
public static Builder<?> builder() {
return new Builder();
}
/**
* Create BitmapTileSource for 'url'
*
* By default path will be formatted as: url/z/x/y.png
* Use e.g. setExtension(".jpg") to overide ending or
* implement getUrlString() for custom formatting.
*/
public BitmapTileSource(String url, int zoomMin, int zoomMax) {
this(url, "/{Z}/{X}/{Y}.png", zoomMin, zoomMax);
}
public BitmapTileSource(String url, int zoomMin, int zoomMax, String extension) {
this(url, "/{Z}/{X}/{Y}" + extension, zoomMin, zoomMax);
}
public BitmapTileSource(String url, String tilePath, int zoomMin, int zoomMax) {
super(builder()
.url(url)
.tilePath(tilePath)
.zoomMin(zoomMin)
.zoomMax(zoomMax));
}
@Override
public ITileDataSource getDataSource() {
return new UrlTileDataSource(this, new BitmapTileDecoder(), getHttpEngine());
}
public class BitmapTileDecoder implements ITileDecoder {
@Override
public boolean decode(Tile tile, ITileDataSink sink, InputStream is)
throws IOException {
Bitmap bitmap = CanvasAdapter.decodeBitmap(is);
if (!bitmap.isValid()) {
log.debug("{} invalid bitmap", tile);
return false;
}
sink.setTileImage(bitmap);
return true;
}
}
}
```
|
```package org.oscim.tiling.source;
import static org.fest.assertions.api.Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.oscim.tiling.ITileDataSource;
public class UrlTileSourceTest {
private UrlTileSource tileSource;
@Before
public void setUp() throws Exception {
tileSource = new TestTileSource("http://example.org/tiles/vtm", "/{Z}/{X}/{Z}.vtm");
}
@Test
public void shouldNotBeNull() throws Exception {
assertThat(tileSource).isNotNull();
}
@Test
public void shouldUseDefaultHttpEngine() throws Exception {
TestTileDataSource dataSource = (TestTileDataSource) tileSource.getDataSource();
assertThat(dataSource.getConnection()).isInstanceOf(LwHttp.class);
}
@Test
public void shouldUseCustomHttpEngine() throws Exception {
tileSource.setHttpEngine(new OkHttpEngine.OkHttpFactory());
TestTileDataSource dataSource = (TestTileDataSource) tileSource.getDataSource();
assertThat(dataSource.getConnection()).isInstanceOf(OkHttpEngine.class);
}
class TestTileSource extends UrlTileSource {
public TestTileSource(String urlString, String tilePath) {
super(urlString, tilePath);
}
@Override
public ITileDataSource getDataSource() {
return new TestTileDataSource(this, null, getHttpEngine());
}
}
class TestTileDataSource extends UrlTileDataSource {
public TestTileDataSource(UrlTileSource tileSource, ITileDecoder tileDecoder,
HttpEngine conn) {
super(tileSource, tileDecoder, conn);
}
public HttpEngine getConnection() {
return mConn;
}
}
}
```
|
Please help me generate a test for this class.
|
```package org.oscim.tiling.source;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import org.oscim.core.Tile;
import org.oscim.tiling.TileSource;
import org.oscim.tiling.source.LwHttp.LwHttpFactory;
public abstract class UrlTileSource extends TileSource {
public abstract static class Builder<T extends Builder<T>> extends TileSource.Builder<T> {
protected String tilePath;
protected String url;
private HttpEngine.Factory engineFactory;
protected Builder() {
}
protected Builder(String url, String tilePath, int zoomMin, int zoomMax) {
this.url = url;
this.tilePath = tilePath;
this.zoomMin = zoomMin;
this.zoomMax = zoomMax;
}
public T tilePath(String tilePath) {
this.tilePath = tilePath;
return self();
}
public T url(String url) {
this.url = url;
return self();
}
public T httpFactory(HttpEngine.Factory factory) {
this.engineFactory = factory;
return self();
}
}
public final static TileUrlFormatter URL_FORMATTER = new DefaultTileUrlFormatter();
private final URL mUrl;
private final String[] mTilePath;
private HttpEngine.Factory mHttpFactory;
private Map<String, String> mRequestHeaders = Collections.emptyMap();
private TileUrlFormatter mTileUrlFormatter = URL_FORMATTER;
public interface TileUrlFormatter {
public String formatTilePath(UrlTileSource tileSource, Tile tile);
}
protected UrlTileSource(Builder<?> builder) {
super(builder);
mUrl = makeUrl(builder.url);
mTilePath = builder.tilePath.split("\\{|\\}");
mHttpFactory = builder.engineFactory;
}
protected UrlTileSource(String urlString, String tilePath) {
this(urlString, tilePath, 0, 17);
}
protected UrlTileSource(String urlString, String tilePath, int zoomMin, int zoomMax) {
super(zoomMin, zoomMax);
mUrl = makeUrl(urlString);
mTilePath = makeTilePath(tilePath);
}
private String[] makeTilePath(String tilePath) {
if (tilePath == null)
throw new IllegalArgumentException("tilePath cannot be null.");
return tilePath.split("\\{|\\}");
}
private URL makeUrl(String urlString) {
URL url = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
return url;
}
@Override
public OpenResult open() {
return OpenResult.SUCCESS;
}
@Override
public void close() {
}
public URL getUrl() {
return mUrl;
}
public String getTileUrl(Tile tile) {
return mUrl + mTileUrlFormatter.formatTilePath(this, tile);
}
public void setHttpEngine(HttpEngine.Factory httpFactory) {
mHttpFactory = httpFactory;
}
public void setHttpRequestHeaders(Map<String, String> options) {
mRequestHeaders = options;
}
public Map<String, String> getRequestHeader() {
return mRequestHeaders;
}
public String[] getTilePath() {
return mTilePath;
}
/**
*
*/
public void setUrlFormatter(TileUrlFormatter formatter) {
mTileUrlFormatter = formatter;
}
public TileUrlFormatter getUrlFormatter() {
return mTileUrlFormatter;
}
public HttpEngine getHttpEngine() {
if (mHttpFactory == null) {
mHttpFactory = new LwHttpFactory();
}
return mHttpFactory.create(this);
}
static class DefaultTileUrlFormatter implements TileUrlFormatter {
@Override
public String formatTilePath(UrlTileSource tileSource, Tile tile) {
StringBuilder sb = new StringBuilder();
for (String b : tileSource.getTilePath()) {
if (b.length() == 1) {
switch (b.charAt(0)) {
case 'X':
sb.append(tile.tileX);
continue;
case 'Y':
sb.append(tile.tileY);
continue;
case 'Z':
sb.append(tile.zoomLevel);
continue;
default:
break;
}
}
sb.append(b);
}
return sb.toString();
}
}
}
```
|
```package org.oscim.tiling.source;
import static org.fest.assertions.api.Assertions.assertThat;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.oscim.core.Tile;
import org.oscim.tiling.source.oscimap4.OSciMap4TileSource;
import com.squareup.okhttp.HttpResponseCache;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
public class OkHttpEngineTest {
private OkHttpEngine engine;
private MockWebServer server;
private MockResponse mockResponse;
private HttpResponseCache cache;
@Before
public void setUp() throws Exception {
mockResponse = new MockResponse();
mockResponse.setBody("TEST RESPONSE".getBytes());
server = new MockWebServer();
server.enqueue(mockResponse);
server.play();
engine = (OkHttpEngine) new OkHttpEngine.OkHttpFactory()
.create(new OSciMap4TileSource(server.getUrl("/tiles/vtm").toString()));
}
@After
public void tearDown() throws Exception {
server.shutdown();
}
@Test
public void shouldNotBeNull() throws Exception {
assertThat(engine).isNotNull();
}
@Test(expected = IllegalArgumentException.class)
public void sendRequest_shouldRejectNullTile() throws Exception {
engine.sendRequest(null);
}
@Test
public void sendRequest_shouldAppendXYZToPath() throws Exception {
engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue()));
RecordedRequest request = server.takeRequest();
assertThat(request.getPath()).isEqualTo("/tiles/vtm/3/1/2.vtm");
}
@Test
public void read_shouldReturnResponseStream() throws Exception {
engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue()));
InputStream responseStream = engine.read();
String response = new BufferedReader(new InputStreamReader(responseStream)).readLine();
assertThat(response).isEqualTo("TEST RESPONSE");
}
// @Test(expected = IOException.class)
// public void close_shouldCloseInputStream() throws Exception {
// engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue()));
// engine.close();
// // Calling read after the stream is closed should throw an exception.
// InputStream responseStream = engine.read();
// responseStream.read();
// }
//
// @Test(expected = IOException.class)
// public void requestCompleted_shouldCloseInputStream() throws Exception {
// engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue()));
// engine.requestCompleted(true);
// // Calling read after the stream is closed should throw an exception.
// InputStream responseStream = engine.read();
// responseStream.read();
// }
@Test
public void requestCompleted_shouldReturnValueGiven() throws Exception {
assertThat(engine.requestCompleted(true)).isTrue();
assertThat(engine.requestCompleted(false)).isFalse();
}
@Test
public void create_shouldUseTileSourceCache() throws Exception {
cache = new HttpResponseCache(new File("tmp"), 1024);
OSciMap4TileSource tileSource =
new OSciMap4TileSource(server.getUrl("/tiles/vtm").toString());
engine = (OkHttpEngine) new OkHttpEngine.OkHttpFactory(cache).create(tileSource);
engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue()));
engine.requestCompleted(true);
assertThat(cache.getRequestCount()).isEqualTo(1);
}
}
```
|
Please help me generate a test for this class.
|
```package org.oscim.tiling.source;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map.Entry;
import org.oscim.core.Tile;
import org.oscim.utils.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.squareup.okhttp.HttpResponseCache;
import com.squareup.okhttp.OkHttpClient;
public class OkHttpEngine implements HttpEngine {
static final Logger log = LoggerFactory.getLogger(OkHttpEngine.class);
private final OkHttpClient mClient;
private final UrlTileSource mTileSource;
public static class OkHttpFactory implements HttpEngine.Factory {
private final OkHttpClient mClient;
public OkHttpFactory() {
mClient = new OkHttpClient();
}
public OkHttpFactory(HttpResponseCache responseCache) {
mClient = new OkHttpClient();
mClient.setResponseCache(responseCache);
}
@Override
public HttpEngine create(UrlTileSource tileSource) {
return new OkHttpEngine(mClient, tileSource);
}
}
private InputStream inputStream;
public OkHttpEngine(OkHttpClient client, UrlTileSource tileSource) {
mClient = client;
mTileSource = tileSource;
}
@Override
public InputStream read() throws IOException {
return inputStream;
}
@Override
public void sendRequest(Tile tile) throws IOException {
if (tile == null) {
throw new IllegalArgumentException("Tile cannot be null.");
}
URL url = new URL(mTileSource.getTileUrl(tile));
HttpURLConnection conn = mClient.open(url);
for (Entry<String, String> opt : mTileSource.getRequestHeader().entrySet())
conn.addRequestProperty(opt.getKey(), opt.getValue());
try {
inputStream = conn.getInputStream();
} catch (FileNotFoundException e) {
throw new IOException("ERROR " + conn.getResponseCode()
+ ": " + conn.getResponseMessage());
}
}
@Override
public void close() {
if (inputStream == null)
return;
final InputStream is = inputStream;
inputStream = null;
new Thread(new Runnable() {
@Override
public void run() {
IOUtils.closeQuietly(is);
}
}).start();
}
@Override
public void setCache(OutputStream os) {
// OkHttp cache implented through tileSource setResponseCache
}
@Override
public boolean requestCompleted(boolean success) {
IOUtils.closeQuietly(inputStream);
inputStream = null;
return success;
}
}
```
|
```package org.oscim.tiling.source.oscimap4;
import static org.fest.assertions.api.Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.oscim.tiling.ITileDataSource;
import org.oscim.tiling.source.HttpEngine;
import org.oscim.tiling.source.LwHttp;
import org.oscim.tiling.source.OkHttpEngine;
import org.oscim.tiling.source.UrlTileSource;
public class OSciMap4TileSourceTest {
private OSciMap4TileSource tileSource;
@Before
public void setUp() throws Exception {
tileSource = new OSciMap4TileSource("http://www.example.org/tiles/vtm");
}
@Test
public void shouldNotBeNull() throws Exception {
assertThat(tileSource).isNotNull();
}
@Test
public void shouldUseLwHttp() throws Exception {
LwHttp lwHttp = Mockito.mock(LwHttp.class);
tileSource.setHttpEngine(new TestHttpFactory(lwHttp));
ITileDataSource dataSource = tileSource.getDataSource();
dataSource.dispose();
Mockito.verify(lwHttp).close();
}
@Test
public void shouldUseOkHttp() throws Exception {
OkHttpEngine okHttp = Mockito.mock(OkHttpEngine.class);
tileSource.setHttpEngine(new TestHttpFactory(okHttp));
ITileDataSource dataSource = tileSource.getDataSource();
dataSource.dispose();
Mockito.verify(okHttp).close();
}
/**
* Test factory that allows the specific {@link HttpEngine} instance to be
* set.
*/
class TestHttpFactory implements HttpEngine.Factory {
final HttpEngine engine;
public TestHttpFactory(HttpEngine engine) {
this.engine = engine;
}
@Override
public HttpEngine create(UrlTileSource tileSource) {
return engine;
}
}
}
```
|
Please help me generate a test for this class.
|
```package org.oscim.tiling.source.oscimap4;
import org.oscim.tiling.ITileDataSource;
import org.oscim.tiling.source.UrlTileDataSource;
import org.oscim.tiling.source.UrlTileSource;
public class OSciMap4TileSource extends UrlTileSource {
private final static String DEFAULT_URL = "http://opensciencemap.org/tiles/vtm";
private final static String DEFAULT_PATH = "/{Z}/{X}/{Y}.vtm";
public static class Builder<T extends Builder<T>> extends UrlTileSource.Builder<T> {
public Builder() {
super(DEFAULT_URL, DEFAULT_PATH, 1, 17);
}
public OSciMap4TileSource build() {
return new OSciMap4TileSource(this);
}
}
@SuppressWarnings("rawtypes")
public static Builder<?> builder() {
return new Builder();
}
protected OSciMap4TileSource(Builder<?> builder) {
super(builder);
}
public OSciMap4TileSource() {
this(builder());
}
public OSciMap4TileSource(String urlString) {
this(builder().url(urlString));
}
@Override
public ITileDataSource getDataSource() {
return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine());
}
}
```
|
```package org.oscim.test;
import org.oscim.gdx.GdxMapApp;
import org.oscim.layers.tile.buildings.BuildingLayer;
import org.oscim.layers.tile.vector.VectorTileLayer;
import org.oscim.layers.tile.vector.labeling.LabelLayer;
import org.oscim.map.Map;
import org.oscim.theme.VtmThemes;
import org.oscim.tiling.source.oscimap4.OSciMap4TileSource;
public class MapTest extends GdxMapApp {
@Override
public void createLayers() {
Map map = getMap();
VectorTileLayer l = map.setBaseMap(new OSciMap4TileSource());
map.layers().add(new BuildingLayer(map, l));
map.layers().add(new LabelLayer(map, l));
map.setTheme(VtmThemes.DEFAULT);
map.setMapPosition(53.075, 8.808, 1 << 17);
}
public static void main(String[] args) {
GdxMapApp.init();
GdxMapApp.run(new MapTest(), null, 400);
}
}
```
|
Please help me generate a test for this class.
|
```package org.oscim.map;
import org.oscim.core.MapPosition;
import org.oscim.event.Event;
import org.oscim.event.EventDispatcher;
import org.oscim.event.EventListener;
import org.oscim.event.Gesture;
import org.oscim.event.GestureDetector;
import org.oscim.event.MotionEvent;
import org.oscim.layers.MapEventLayer;
import org.oscim.layers.tile.TileLayer;
import org.oscim.layers.tile.vector.OsmTileLayer;
import org.oscim.layers.tile.vector.VectorTileLayer;
import org.oscim.renderer.MapRenderer;
import org.oscim.theme.IRenderTheme;
import org.oscim.theme.ThemeFile;
import org.oscim.theme.ThemeLoader;
import org.oscim.tiling.TileSource;
import org.oscim.utils.async.AsyncExecutor;
import org.oscim.utils.async.TaskQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class Map implements TaskQueue {
static final Logger log = LoggerFactory.getLogger(Map.class);
/**
* Listener interface for map update notifications.
* Layers implementing this interface they will be automatically register
* when the layer is added to the map and unregistered when the layer is
* removed. Otherwise use map.events.bind(UpdateListener).
*/
public interface UpdateListener extends EventListener {
void onMapEvent(Event e, MapPosition mapPosition);
}
/**
* Listener interface for input events.
* Layers implementing this interface they will be automatically register
* when the layer is added to the map and unregistered when the layer is
* removed.
*/
public interface InputListener extends EventListener {
void onInputEvent(Event e, MotionEvent motionEvent);
}
/**
* UpdateListener event. Map position has changed.
*/
public static Event POSITION_EVENT = new Event();
/**
* UpdateLister event. Delivered on main-thread when updateMap() was called
* and no CLEAR_EVENT or POSITION_EVENT was triggered.
*/
public static Event UPDATE_EVENT = new Event();
/**
* UpdateListerner event. Map state has changed in a way that all layers
* should clear their state e.g. the theme or the TilesSource has changed.
* TODO should have an event-source to only clear affected layers.
*/
public static Event CLEAR_EVENT = new Event();
public final EventDispatcher<InputListener, MotionEvent> input;
public final EventDispatcher<UpdateListener, MapPosition> events;
private final Layers mLayers;
private final ViewController mViewport;
private final Animator mAnimator;
private final MapPosition mMapPosition;
private final AsyncExecutor mAsyncExecutor;
protected final MapEventLayer mEventLayer;
protected GestureDetector mGestureDetector;
private TileLayer mBaseLayer;
protected boolean mClearMap = true;
public Map() {
mViewport = new ViewController();
mAnimator = new Animator(this);
mLayers = new Layers(this);
input = new EventDispatcher<InputListener, MotionEvent>() {
@Override
public void tell(InputListener l, Event e, MotionEvent d) {
l.onInputEvent(e, d);
}
};
events = new EventDispatcher<UpdateListener, MapPosition>() {
@Override
public void tell(UpdateListener l, Event e, MapPosition d) {
l.onMapEvent(e, d);
}
};
mAsyncExecutor = new AsyncExecutor(4, this);
mMapPosition = new MapPosition();
mEventLayer = new MapEventLayer(this);
mLayers.add(0, mEventLayer);
}
public MapEventLayer getEventLayer() {
return mEventLayer;
}
/**
* Create OsmTileLayer with given TileSource and
* set as base map (layer 1)
*
* TODO deprecate
*/
public VectorTileLayer setBaseMap(TileSource tileSource) {
VectorTileLayer l = new OsmTileLayer(this);
l.setTileSource(tileSource);
setBaseMap(l);
return l;
}
public TileLayer setBaseMap(TileLayer tileLayer) {
mLayers.add(1, tileLayer);
mBaseLayer = tileLayer;
return tileLayer;
}
/**
* Utility function to set theme of base vector-layer and
* use map background color from theme.
*/
public void setTheme(ThemeFile theme) {
if (mBaseLayer == null) {
log.error("No base layer set");
throw new IllegalStateException();
}
setTheme(ThemeLoader.load(theme));
}
public void setTheme(IRenderTheme theme) {
if (theme == null) {
throw new IllegalArgumentException("Theme cannot be null.");
}
if (mBaseLayer == null) {
log.warn("No base layer set.");
} else if (mBaseLayer instanceof VectorTileLayer) {
((VectorTileLayer) mBaseLayer).setRenderTheme(theme);
}
MapRenderer.setBackgroundColor(theme.getMapBackground());
clearMap();
}
public void destroy() {
mLayers.destroy();
mAsyncExecutor.dispose();
}
/**
* Request call to onUpdate for all layers. This function can
* be called from any thread. Request will be handled on main
* thread.
*
* @param redraw pass true to render next frame afterwards
*/
public abstract void updateMap(boolean redraw);
/**
* Request to render a frame. Request will be handled on main
* thread. Use this for animations in RenderLayers.
*/
public abstract void render();
/**
* Post a runnable to be executed on main-thread
*/
@Override
public abstract boolean post(Runnable action);
/**
* Post a runnable to be executed on main-thread. Execution is delayed for
* at least 'delay' milliseconds.
*/
public abstract boolean postDelayed(Runnable action, long delay);
/**
* Post a task to run on a shared worker-thread. Shoul only use for
* tasks running less than a second.
*/
@Override
public void addTask(Runnable task) {
mAsyncExecutor.post(task);
}
/**
* Return screen width in pixel.
*/
public abstract int getWidth();
/**
* Return screen height in pixel.
*/
public abstract int getHeight();
/**
* Request to clear all layers before rendering next frame
*/
public void clearMap() {
mClearMap = true;
updateMap(true);
}
/**
* Set {@link MapPosition} of {@link Viewport} and trigger a redraw.
*/
public void setMapPosition(MapPosition mapPosition) {
mViewport.setMapPosition(mapPosition);
updateMap(true);
}
public void setMapPosition(double latitude, double longitude, double scale) {
mViewport.setMapPosition(new MapPosition(latitude, longitude, scale));
updateMap(true);
}
/**
* Get current {@link MapPosition}.
*
* @return true when MapPosition was updated (has changed)
*/
public boolean getMapPosition(MapPosition mapPosition) {
return mViewport.getMapPosition(mapPosition);
}
/**
* Get current {@link MapPosition}. Consider using
* getViewport.getMapPosition(pos) instead to reuse
* MapPosition instance.
*/
public MapPosition getMapPosition() {
MapPosition pos = new MapPosition();
mViewport.getMapPosition(pos);
return pos;
}
/**
* @return Viewport instance
*/
public ViewController viewport() {
return mViewport;
}
/**
* @return Layers instance
*/
public Layers layers() {
return mLayers;
}
/**
* @return MapAnimator instance
*/
public Animator animator() {
return mAnimator;
}
/**
* This function is run on main-loop before rendering a frame.
* Caution: Do not call directly!
*/
protected void updateLayers() {
boolean changed = false;
MapPosition pos = mMapPosition;
changed |= mViewport.getMapPosition(pos);
if (mClearMap)
events.fire(CLEAR_EVENT, pos);
else if (changed)
events.fire(POSITION_EVENT, pos);
else
events.fire(UPDATE_EVENT, pos);
mClearMap = false;
}
public boolean handleGesture(Gesture g, MotionEvent e) {
return mLayers.handleGesture(g, e);
}
}
```
|
```package org.oscim.layers;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.oscim.event.Gesture;
import org.oscim.event.MotionEvent;
import org.oscim.map.Animator;
import org.oscim.map.Map;
import org.oscim.map.ViewController;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class MapEventLayerTest {
private MapEventLayer layer;
private Map mockMap;
private ViewController mockViewport;
private Animator mockAnimator;
private ArgumentCaptor<Float> argumentCaptor;
@Before
public void setUp() throws Exception {
mockMap = Mockito.mock(Map.class);
mockViewport = Mockito.mock(ViewController.class);
mockAnimator = Mockito.mock(Animator.class);
layer = new MapEventLayer(mockMap);
when(mockMap.viewport()).thenReturn(mockViewport);
when(mockMap.animator()).thenReturn(mockAnimator);
when(mockMap.getHeight()).thenReturn(6);
argumentCaptor = ArgumentCaptor.forClass(float.class);
}
@Test
public void shouldNotBeNull() throws Exception {
assertThat(layer).isNotNull();
}
@Test
public void doubleTap_shouldAnimateZoom() throws Exception {
simulateDoubleTap();
verify(mockAnimator).animateZoom(300, 2, 1.0f, -2.0f);
}
@Test
public void doubleTap_shouldAnimateZoomAfterDoubleTouchDrag() throws Exception {
simulateDoubleTouchDragUp();
simulateDoubleTap();
verify(mockAnimator).animateZoom(300, 2, 1.0f, -2.0f);
}
@Test
public void doubleTouchDrag_shouldNotAnimateZoom() throws Exception {
simulateDoubleTouchDragUp();
verify(mockAnimator, never()).animateZoom(any(long.class), any(double.class),
any(float.class), any(float.class));
}
@Test
public void doubleTouchDragUp_shouldDecreaseContentScale() throws Exception {
simulateDoubleTouchDragUp();
verify(mockViewport).scaleMap(argumentCaptor.capture(), any(float.class), any(float.class));
assertThat(argumentCaptor.getValue()).isLessThan(1);
}
@Test
public void doubleTouchDragDown_shouldIncreaseContentScale() throws Exception {
simulateDoubleTouchDragDown();
verify(mockViewport).scaleMap(argumentCaptor.capture(), any(float.class), any(float.class));
assertThat(argumentCaptor.getValue()).isGreaterThan(1);
}
private void simulateDoubleTap() {
layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_DOWN, 1, 1));
layer.onGesture(Gesture.DOUBLE_TAP, new TestMotionEvent(MotionEvent.ACTION_UP, 1, 1));
layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_UP, 1, 1));
}
private void simulateDoubleTouchDragUp() {
layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_DOWN, 1, 1));
layer.onGesture(Gesture.DOUBLE_TAP, new TestMotionEvent(MotionEvent.ACTION_MOVE, 1, 0));
layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_MOVE, -100, 0));
layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_UP, 1, 0));
}
private void simulateDoubleTouchDragDown() {
layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_DOWN, 1, 1));
layer.onGesture(Gesture.DOUBLE_TAP, new TestMotionEvent(MotionEvent.ACTION_MOVE, 1, 2));
layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_MOVE, 100, 2));
layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_UP, 1, 2));
}
class TestMotionEvent extends MotionEvent {
final int action;
final float x;
final float y;
public TestMotionEvent(int action, float x, float y) {
this.action = action;
this.x = x;
this.y = y;
}
@Override
public long getTime() {
return 0;
}
@Override
public int getAction() {
return action;
}
@Override
public float getX() {
return x;
}
@Override
public float getY() {
return y;
}
@Override
public float getX(int idx) {
return x;
}
@Override
public float getY(int idx) {
return y;
}
@Override
public int getPointerCount() {
return 0;
}
}
}
```
|
Please help me generate a test for this class.
|
```package org.oscim.layers;
import static org.oscim.backend.CanvasAdapter.dpi;
import static org.oscim.utils.FastMath.withinSquaredDist;
import org.oscim.core.Tile;
import org.oscim.event.Event;
import org.oscim.event.Gesture;
import org.oscim.event.GestureListener;
import org.oscim.event.MotionEvent;
import org.oscim.map.Map;
import org.oscim.map.Map.InputListener;
import org.oscim.map.ViewController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Changes Viewport by handling move, fling, scale, rotation and tilt gestures.
*
* TODO rewrite using gesture primitives to build more complex gestures:
* maybe something similar to this https://github.com/ucbvislab/Proton
*/
public class MapEventLayer extends Layer implements InputListener, GestureListener {
static final Logger log = LoggerFactory.getLogger(MapEventLayer.class);
private boolean mEnableRotate = true;
private boolean mEnableTilt = true;
private boolean mEnableMove = true;
private boolean mEnableScale = true;
private boolean mFixOnCenter = false;
/* possible state transitions */
private boolean mCanScale;
private boolean mCanRotate;
private boolean mCanTilt;
/* current gesture state */
private boolean mDoRotate;
private boolean mDoScale;
private boolean mDoTilt;
private boolean mDown;
private boolean mDoubleTap;
private boolean mDragZoom;
private float mPrevX1;
private float mPrevY1;
private float mPrevX2;
private float mPrevY2;
private double mAngle;
private double mPrevPinchWidth;
private long mStartMove;
/** 2mm as minimal distance to start move: dpi / 25.4 */
protected static final float MIN_SLOP = 25.4f / 2;
protected static final float PINCH_ZOOM_THRESHOLD = MIN_SLOP / 2;
protected static final float PINCH_TILT_THRESHOLD = MIN_SLOP / 2;
protected static final float PINCH_TILT_SLOPE = 0.75f;
protected static final float PINCH_ROTATE_THRESHOLD = 0.2f;
protected static final float PINCH_ROTATE_THRESHOLD2 = 0.5f;
/** 100 ms since start of move to reduce fling scroll */
protected static final float FLING_MIN_THREHSHOLD = 100;
private final VelocityTracker mTracker;
public MapEventLayer(Map map) {
super(map);
mTracker = new VelocityTracker();
}
@Override
public void onInputEvent(Event e, MotionEvent motionEvent) {
onTouchEvent(motionEvent);
}
public void enableRotation(boolean enable) {
mEnableRotate = enable;
}
public boolean rotationEnabled() {
return mEnableRotate;
}
public void enableTilt(boolean enable) {
mEnableTilt = enable;
}
public void enableMove(boolean enable) {
mEnableMove = enable;
}
public void enableZoom(boolean enable) {
mEnableScale = enable;
}
/**
* When enabled zoom- and rotation-gestures will not move the viewport.
*/
public void setFixOnCenter(boolean enable) {
mFixOnCenter = enable;
}
public boolean onTouchEvent(MotionEvent e) {
int action = getAction(e);
if (action == MotionEvent.ACTION_DOWN) {
mMap.animator().cancel();
mStartMove = -1;
mDoubleTap = false;
mDragZoom = false;
mPrevX1 = e.getX(0);
mPrevY1 = e.getY(0);
mDown = true;
return true;
}
if (!(mDown || mDoubleTap)) {
/* no down event received */
return false;
}
if (action == MotionEvent.ACTION_MOVE) {
onActionMove(e);
return true;
}
if (action == MotionEvent.ACTION_UP) {
mDown = false;
if (mDoubleTap && !mDragZoom) {
float pivotX = 0, pivotY = 0;
if (!mFixOnCenter) {
pivotX = mPrevX1 - mMap.getWidth() / 2;
pivotY = mPrevY1 - mMap.getHeight() / 2;
}
/* handle double tap zoom */
mMap.animator().animateZoom(300, 2, pivotX, pivotY);
} else if (mStartMove > 0) {
/* handle fling gesture */
mTracker.update(e.getX(), e.getY(), e.getTime());
float vx = mTracker.getVelocityX();
float vy = mTracker.getVelocityY();
/* reduce velocity for short moves */
float t = e.getTime() - mStartMove;
if (t < FLING_MIN_THREHSHOLD) {
t = t / FLING_MIN_THREHSHOLD;
vy *= t * t;
vx *= t * t;
}
doFling(vx, vy);
}
return true;
}
if (action == MotionEvent.ACTION_CANCEL) {
return false;
}
if (action == MotionEvent.ACTION_POINTER_DOWN) {
mStartMove = -1;
updateMulti(e);
return true;
}
if (action == MotionEvent.ACTION_POINTER_UP) {
updateMulti(e);
return true;
}
return false;
}
private static int getAction(MotionEvent e) {
return e.getAction() & MotionEvent.ACTION_MASK;
}
private void onActionMove(MotionEvent e) {
ViewController mViewport = mMap.viewport();
float x1 = e.getX(0);
float y1 = e.getY(0);
float mx = x1 - mPrevX1;
float my = y1 - mPrevY1;
float width = mMap.getWidth();
float height = mMap.getHeight();
if (e.getPointerCount() < 2) {
mPrevX1 = x1;
mPrevY1 = y1;
/* double-tap drag zoom */
if (mDoubleTap) {
/* just ignore first move event to set mPrevX/Y */
if (!mDown) {
mDown = true;
return;
}
if (!mDragZoom && !isMinimalMove(mx, my)) {
mPrevX1 -= mx;
mPrevY1 -= my;
return;
}
// TODO limit scale properly
mDragZoom = true;
mViewport.scaleMap(1 + my / (height / 6), 0, 0);
mMap.updateMap(true);
mStartMove = -1;
return;
}
/* simple move */
if (!mEnableMove)
return;
if (mStartMove < 0) {
if (!isMinimalMove(mx, my)) {
mPrevX1 -= mx;
mPrevY1 -= my;
return;
}
mStartMove = e.getTime();
mTracker.start(x1, y1, mStartMove);
return;
}
mViewport.moveMap(mx, my);
mTracker.update(x1, y1, e.getTime());
mMap.updateMap(true);
return;
}
mStartMove = -1;
float x2 = e.getX(1);
float y2 = e.getY(1);
float dx = (x1 - x2);
float dy = (y1 - y2);
double rotateBy = 0;
float scaleBy = 1;
float tiltBy = 0;
mx = ((x1 + x2) - (mPrevX1 + mPrevX2)) / 2;
my = ((y1 + y2) - (mPrevY1 + mPrevY2)) / 2;
if (mCanTilt) {
float slope = (dx == 0) ? 0 : dy / dx;
if (Math.abs(slope) < PINCH_TILT_SLOPE) {
if (mDoTilt) {
tiltBy = my / 5;
} else if (Math.abs(my) > (dpi / PINCH_TILT_THRESHOLD)) {
/* enter exclusive tilt mode */
mCanScale = false;
mCanRotate = false;
mDoTilt = true;
}
}
}
double pinchWidth = Math.sqrt(dx * dx + dy * dy);
double deltaPinch = pinchWidth - mPrevPinchWidth;
if (mCanRotate) {
double rad = Math.atan2(dy, dx);
double r = rad - mAngle;
if (mDoRotate) {
double da = rad - mAngle;
if (Math.abs(da) > 0.0001) {
rotateBy = da;
mAngle = rad;
deltaPinch = 0;
}
} else {
r = Math.abs(r);
if (r > PINCH_ROTATE_THRESHOLD) {
/* start rotate, disable tilt */
mDoRotate = true;
mCanTilt = false;
mAngle = rad;
} else if (!mDoScale) {
/* reduce pinch trigger by the amount of rotation */
deltaPinch *= 1 - (r / PINCH_ROTATE_THRESHOLD);
} else {
mPrevPinchWidth = pinchWidth;
}
}
} else if (mDoScale && mEnableRotate) {
/* re-enable rotation when higher threshold is reached */
double rad = Math.atan2(dy, dx);
double r = rad - mAngle;
if (r > PINCH_ROTATE_THRESHOLD2) {
/* start rotate again */
mDoRotate = true;
mCanRotate = true;
mAngle = rad;
}
}
if (mCanScale || mDoRotate) {
if (!(mDoScale || mDoRotate)) {
/* enter exclusive scale mode */
if (Math.abs(deltaPinch) > (dpi / PINCH_ZOOM_THRESHOLD)) {
if (!mDoRotate) {
mPrevPinchWidth = pinchWidth;
mCanRotate = false;
}
mCanTilt = false;
mDoScale = true;
}
}
if (mDoScale || mDoRotate) {
scaleBy = (float) (pinchWidth / mPrevPinchWidth);
mPrevPinchWidth = pinchWidth;
}
}
if (!(mDoRotate || mDoScale || mDoTilt))
return;
float pivotX = 0, pivotY = 0;
if (!mFixOnCenter) {
pivotX = (x2 + x1) / 2 - width / 2;
pivotY = (y2 + y1) / 2 - height / 2;
}
synchronized (mViewport) {
if (!mDoTilt) {
if (rotateBy != 0)
mViewport.rotateMap(rotateBy, pivotX, pivotY);
if (scaleBy != 1)
mViewport.scaleMap(scaleBy, pivotX, pivotY);
if (!mFixOnCenter)
mViewport.moveMap(mx, my);
} else {
if (tiltBy != 0 && mViewport.tiltMap(-tiltBy))
mViewport.moveMap(0, my / 2);
}
}
mPrevX1 = x1;
mPrevY1 = y1;
mPrevX2 = x2;
mPrevY2 = y2;
mMap.updateMap(true);
}
private void updateMulti(MotionEvent e) {
int cnt = e.getPointerCount();
mPrevX1 = e.getX(0);
mPrevY1 = e.getY(0);
if (cnt == 2) {
mDoScale = false;
mDoRotate = false;
mDoTilt = false;
mCanScale = mEnableScale;
mCanRotate = mEnableRotate;
mCanTilt = mEnableTilt;
mPrevX2 = e.getX(1);
mPrevY2 = e.getY(1);
double dx = mPrevX1 - mPrevX2;
double dy = mPrevY1 - mPrevY2;
mAngle = Math.atan2(dy, dx);
mPrevPinchWidth = Math.sqrt(dx * dx + dy * dy);
}
}
private boolean isMinimalMove(float mx, float my) {
float minSlop = (dpi / MIN_SLOP);
return !withinSquaredDist(mx, my, minSlop * minSlop);
}
private boolean doFling(float velocityX, float velocityY) {
int w = Tile.SIZE * 5;
int h = Tile.SIZE * 5;
mMap.animator().animateFling(velocityX * 2, velocityY * 2,
-w, w, -h, h);
return true;
}
@Override
public boolean onGesture(Gesture g, MotionEvent e) {
if (g == Gesture.DOUBLE_TAP) {
mDoubleTap = true;
return true;
}
return false;
}
static class VelocityTracker {
/* sample window, 200ms */
private static final int MAX_MS = 200;
private static final int SAMPLES = 32;
private float mLastX, mLastY;
private long mLastTime;
private int mNumSamples;
private int mIndex;
private float[] mMeanX = new float[SAMPLES];
private float[] mMeanY = new float[SAMPLES];
private int[] mMeanTime = new int[SAMPLES];
public void start(float x, float y, long time) {
mLastX = x;
mLastY = y;
mNumSamples = 0;
mIndex = SAMPLES;
mLastTime = time;
}
public void update(float x, float y, long time) {
if (time == mLastTime)
return;
if (--mIndex < 0)
mIndex = SAMPLES - 1;
mMeanX[mIndex] = x - mLastX;
mMeanY[mIndex] = y - mLastY;
mMeanTime[mIndex] = (int) (time - mLastTime);
mLastTime = time;
mLastX = x;
mLastY = y;
mNumSamples++;
}
private float getVelocity(float[] move) {
mNumSamples = Math.min(SAMPLES, mNumSamples);
double duration = 0;
double amount = 0;
for (int c = 0; c < mNumSamples; c++) {
int index = (mIndex + c) % SAMPLES;
float d = mMeanTime[index];
if (c > 0 && duration + d > MAX_MS)
break;
duration += d;
amount += move[index] * (d / duration);
}
if (duration == 0)
return 0;
return (float) ((amount * 1000) / duration);
}
public float getVelocityY() {
return getVelocity(mMeanY);
}
public float getVelocityX() {
return getVelocity(mMeanX);
}
}
}
```
|
```package com.cloudera.broker;
/**
* package: com.cloudera
* describe: TODO
* creat_user: Fayson
* email: htechinfo@163.com
* creat_date: 2017/12/12
* creat_time: ไธๅ3:35
* ๅ
ฌไผๅท๏ผHadoopๅฎๆ
*/
public class ConsumerTest {
}
```
|
Please help me generate a test for this class.
|
```package com.cloudera.broker;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import java.util.Arrays;
import java.util.Properties;
/**
* package: com.cloudera
* describe: Kerberos็ฏๅขไธ้่ฟKafka็Bootstrap.Serverๆถ่ดนๆฐๆฎ
* creat_user: Fayson
* email: htechinfo@163.com
* creat_date: 2017/12/12
* creat_time: ไธๅ3:35
* ๅ
ฌไผๅท๏ผHadoopๅฎๆ
*/
public class MyConsumer {
private static String TOPIC_NAME = "test3";
public static void main(String[] args) {
System.setProperty("java.security.krb5.conf", "/Volumes/Transcend/keytab/krb5.conf");
System.setProperty("java.security.auth.login.config", "/Volumes/Transcend/keytab/jaas-cache.conf");
System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
// System.setProperty("sun.security.krb5.debug", "true");
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "ip-172-31-21-45.ap-southeast-1.compute.internal:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "DemoConsumer");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
props.put("security.protocol", "SASL_PLAINTEXT");
props.put("sasl.kerberos.service.name", "kafka");
KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
TopicPartition partition0 = new TopicPartition(TOPIC_NAME, 0);
TopicPartition partition1 = new TopicPartition(TOPIC_NAME, 1);
TopicPartition partition2 = new TopicPartition(TOPIC_NAME, 2);
consumer.assign(Arrays.asList(partition0, partition1, partition2));
ConsumerRecords<String, String> records = null;
while (true) {
try {
Thread.sleep(10000l);
System.out.println();
records = consumer.poll(Long.MAX_VALUE);
for (ConsumerRecord<String, String> record : records) {
System.out.println("Received message: (" + record.key() + ", " + record.value() + ") at offset " + record.offset());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
|
```package net.synedra.validatorfx;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.testfx.framework.junit5.ApplicationExtension;
import javafx.scene.shape.Rectangle;
@ExtendWith(ApplicationExtension.class)
class StyleClassDecorationTest {
@Test
void testDecoration() {
Rectangle targetNode = new Rectangle(1, 2, 3, 4);
StyleClassDecoration decoration = new StyleClassDecoration("a", "b", "c");
decoration.add(targetNode);
assertTrue(targetNode.getStyleClass().contains("a"));
assertTrue(targetNode.getStyleClass().contains("b"));
assertTrue(targetNode.getStyleClass().contains("c"));
targetNode.getStyleClass().add("otherStyle");
decoration.remove(targetNode);
assertFalse(targetNode.getStyleClass().contains("a"));
assertFalse(targetNode.getStyleClass().contains("b"));
assertFalse(targetNode.getStyleClass().contains("c"));
assertTrue(targetNode.getStyleClass().contains("otherStyle"));
}
@Test
void testInvalidConstructorCall() {
assertThrows(IllegalArgumentException.class, () -> new StyleClassDecoration((String []) null));
assertThrows(IllegalArgumentException.class, () -> new StyleClassDecoration());
}
}
```
|
Please help me generate a test for this class.
|
```package net.synedra.validatorfx;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javafx.scene.Node;
/** StyleClassDecoration provides decoration of nodes by setting / removing style classes.
* @author r.lichtenberger@synedra.com
*/
public class StyleClassDecoration implements Decoration {
private final Set<String> styleClasses;
/** Create new StyleClassDecoration
* @param styleClasses The style classes to apply to the target node, if check fails
* @throws IllegalArgumentException if styleClasses is null or empty.
*/
public StyleClassDecoration(String... styleClasses) {
if (styleClasses == null || styleClasses.length == 0) {
throw new IllegalArgumentException("At least one style class is required");
}
this.styleClasses = new HashSet<>(Arrays.asList(styleClasses));
}
@Override
public void add(Node targetNode) {
List<String> styleClassList = targetNode.getStyleClass();
Set<String> toAdd = new HashSet<>(styleClasses);
toAdd.removeAll(styleClassList); // don't add a style class that is already added.
styleClassList.addAll(toAdd);
}
@Override
public void remove(Node targetNode) {
targetNode.getStyleClass().removeAll(styleClasses);
}
}
```
|
```package net.synedra.validatorfx;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.Test;
class ValidationMessageTest {
@Test
void testMessage() {
ValidationMessage msg = new ValidationMessage(Severity.WARNING, "Test1");
assertEquals(Severity.WARNING, msg.getSeverity());
assertEquals("Test1", msg.getText());
msg = new ValidationMessage(Severity.ERROR, "Test2");
assertEquals(Severity.ERROR, msg.getSeverity());
assertEquals("Test2", msg.getText());
}
@Test
void testHashAndEquals() {
ValidationMessage msg1 = new ValidationMessage(Severity.WARNING, "Test1");
ValidationMessage msg2 = new ValidationMessage(Severity.WARNING, "Test1");
ValidationMessage msg3 = new ValidationMessage(Severity.ERROR, "Test1");
ValidationMessage msg4 = new ValidationMessage(Severity.WARNING, "Test2");
ValidationMessage msg5 = new ValidationMessage(Severity.ERROR, "Test3");
assertEquals(msg1, msg2);
assertNotEquals(msg1, msg3);
assertNotEquals(msg1, msg4);
assertNotEquals(msg1, msg5);
assertEquals(msg1.hashCode(), msg2.hashCode());
assertNotEquals(msg1.hashCode(), msg3.hashCode());
assertNotEquals(msg1.hashCode(), msg4.hashCode());
assertNotEquals(msg1.hashCode(), msg5.hashCode());
}
}
```
|
Please help me generate a test for this class.
|
```package net.synedra.validatorfx;
/** A validation message represents the description of a single problem.
* @author r.lichtenberger@synedra.com
*/
public class ValidationMessage {
private String text;
private Severity severity;
public ValidationMessage(Severity severity, String text) {
super();
this.severity = severity;
this.text = text;
}
public Severity getSeverity() {
return severity;
}
public String getText() {
return text;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((severity == null) ? 0 : severity.hashCode());
result = prime * result + ((text == null) ? 0 : text.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ValidationMessage other = (ValidationMessage) obj;
if (severity != other.severity)
return false;
if (text == null) {
if (other.text != null)
return false;
} else if (!text.equals(other.text))
return false;
return true;
}
}
```
|
```package net.synedra.validatorfx;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.testfx.framework.junit5.ApplicationExtension;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.control.Button;
@ExtendWith(ApplicationExtension.class)
/** TooltipWrapperTest tests TooltipWrapper.
* @author r.lichtenberger@synedra.com
*/
class TooltipWrapperTest {
@Test
void testWrappedNode() {
Button button = new Button("test");
TooltipWrapper<Button> wrapper = new TooltipWrapper<>(button, new SimpleBooleanProperty(false), new SimpleStringProperty("foobar"));
assertEquals(button, wrapper.getWrappedNode());
}
@Test
void testDisabling() {
SimpleBooleanProperty disable = new SimpleBooleanProperty(false);
Button button = new Button("test");
TooltipWrapper<Button> wrapper = new TooltipWrapper<>(button, disable, new SimpleStringProperty("foobar"));
assertEquals(false, button.isDisabled());
assertEquals(false, wrapper.isDisabled());
disable.set(true);
assertEquals(true, button.isDisabled());
assertEquals(false, wrapper.isDisabled()); // wrapper always stays enabled to allow the tooltip to be shown
}
// this test uses implementation details of JavaFX and may fail if javafx.scene.control.Tooltip is changed
@Test
void testTooltip() {
SimpleBooleanProperty disable = new SimpleBooleanProperty(false);
Button button = new Button("test");
TooltipWrapper<Button> wrapper = new TooltipWrapper<>(button, disable, new SimpleStringProperty("foobar"));
assertEquals(false, wrapper.getProperties().containsKey("javafx.scene.control.Tooltip"));
disable.set(true);
assertEquals(true, wrapper.getProperties().containsKey("javafx.scene.control.Tooltip"));
disable.set(false);
assertEquals(false, wrapper.getProperties().containsKey("javafx.scene.control.Tooltip"));
}
}
```
|
Please help me generate a test for this class.
|
```package net.synedra.validatorfx;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
/** TooltipWrapper will disable a node in case validation fails. It will also display a tooltip for the user to explain why the button is not enabled.
* It works around JDK-8090379 (tooltips don't show on disabled controls)
* @author r.lichtenberger@synedra.com
*/
public class TooltipWrapper<T extends Node> extends HBox {
private T node;
private Tooltip disabledTooltip;
private ObservableValue<Boolean> disabledProperty;
private BooleanProperty visibleProperty = new SimpleBooleanProperty(true);
public TooltipWrapper(T node, ObservableValue<Boolean> disabledProperty, ObservableValue<String> tooltipText) {
this.node = node;
this.disabledProperty = disabledProperty;
node.disableProperty().bind(disabledProperty);
disabledProperty.addListener((observable, oldValue, newValue) -> updateTooltip());
setId(node.getId() + "-wrapper");
setAlignment(Pos.CENTER);
HBox.setHgrow(node, Priority.ALWAYS);
visibleProperty().bind(visibleProperty);
getChildren().add(node);
disabledTooltip = new Tooltip();
disabledTooltip.setId(node.getId() + "-tooltip");
disabledTooltip.getStyleClass().add("TooltipWrapper");
disabledTooltip.textProperty().bind(tooltipText);
}
public T getWrappedNode() {
return node;
}
public Tooltip getDisabledTooltip() { return disabledTooltip; }
private void updateTooltip() {
if (Boolean.TRUE.equals(disabledProperty.getValue())) {
Tooltip.install(this, disabledTooltip);
} else {
Tooltip.uninstall(this, disabledTooltip);
}
}
}
```
|
```package net.synedra.validatorfx;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class ValdationResultTest {
@Test
void testSetup() {
ValidationResult result = new ValidationResult();
assertTrue(result.getMessages().isEmpty());
result.addWarning("warn");
assertFalse(result.getMessages().isEmpty());
result.addError("err");
assertEquals(Severity.WARNING, result.getMessages().get(0).getSeverity());
assertEquals("warn", result.getMessages().get(0).getText());
assertEquals(Severity.ERROR, result.getMessages().get(1).getSeverity());
assertEquals("err", result.getMessages().get(1).getText());
}
@Test
void testAddAll() {
ValidationResult result1 = new ValidationResult();
ValidationResult result2 = new ValidationResult();
result1.addWarning("warn");
result2.addError("err");
ValidationResult result = new ValidationResult();
result.addAll(result1.getMessages());
result.addAll(result2.getMessages());
assertEquals(Severity.WARNING, result.getMessages().get(0).getSeverity());
assertEquals("warn", result.getMessages().get(0).getText());
assertEquals(Severity.ERROR, result.getMessages().get(1).getSeverity());
assertEquals("err", result.getMessages().get(1).getText());
}
}
```
|
Please help me generate a test for this class.
|
```package net.synedra.validatorfx;
import java.util.ArrayList;
import java.util.List;
/** A validation result consists of 0 ... n validation messages.
* @author r.lichtenberger@synedra.com
*/
public class ValidationResult {
private List<ValidationMessage> messages = new ArrayList<>();
public List<ValidationMessage> getMessages() {
return messages;
}
public void addWarning(String text) {
messages.add(new ValidationMessage(Severity.WARNING, text));
}
public void addError(String text) {
messages.add(new ValidationMessage(Severity.ERROR, text));
}
public void addAll(List<ValidationMessage> messages) {
this.messages.addAll(messages);
}
}
```
|
```package org.apache.rocketmq.broker;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;
public class BrokerStartupTest {
private String storePathRootDir = ".";
@Test
public void testProperties2SystemEnv() throws NoSuchMethodException, InvocationTargetException,
IllegalAccessException {
Properties properties = new Properties();
Class<BrokerStartup> clazz = BrokerStartup.class;
Method method = clazz.getDeclaredMethod("properties2SystemEnv", Properties.class);
method.setAccessible(true);
System.setProperty("rocketmq.namesrv.domain", "value");
method.invoke(null, properties);
Assert.assertEquals("value", System.getProperty("rocketmq.namesrv.domain"));
}
}```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.broker;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.common.BrokerConfig;
import org.apache.rocketmq.common.MQVersion;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.remoting.common.RemotingUtil;
import org.apache.rocketmq.remoting.common.TlsMode;
import org.apache.rocketmq.remoting.netty.NettyClientConfig;
import org.apache.rocketmq.remoting.netty.NettyServerConfig;
import org.apache.rocketmq.remoting.netty.NettySystemConfig;
import org.apache.rocketmq.remoting.netty.TlsSystemConfig;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.store.config.BrokerRole;
import org.apache.rocketmq.store.config.MessageStoreConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.rocketmq.remoting.netty.TlsSystemConfig.TLS_ENABLE;
public class BrokerStartup {
public static Properties properties = null;
public static CommandLine commandLine = null;
public static String configFile = null;
public static Logger log;
public static void main(String[] args) {
start(createBrokerController(args));
}
public static BrokerController start(BrokerController controller) {
try {
controller.start();
String tip = "The broker[" + controller.getBrokerConfig().getBrokerName() + ", "
+ controller.getBrokerAddr() + "] boot success. serializeType=" + RemotingCommand.getSerializeTypeConfigInThisServer();
if (null != controller.getBrokerConfig().getNamesrvAddr()) {
tip += " and name server is " + controller.getBrokerConfig().getNamesrvAddr();
}
log.info(tip);
return controller;
} catch (Throwable e) {
e.printStackTrace();
System.exit(-1);
}
return null;
}
public static BrokerController createBrokerController(String[] args) {
System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, Integer.toString(MQVersion.CURRENT_VERSION));
if (null == System.getProperty(NettySystemConfig.COM_ROCKETMQ_REMOTING_SOCKET_SNDBUF_SIZE)) {
NettySystemConfig.socketSndbufSize = 131072;
}
if (null == System.getProperty(NettySystemConfig.COM_ROCKETMQ_REMOTING_SOCKET_RCVBUF_SIZE)) {
NettySystemConfig.socketRcvbufSize = 131072;
}
try {
//PackageConflictDetect.detectFastjson();
Options options = ServerUtil.buildCommandlineOptions(new Options());
commandLine = ServerUtil.parseCmdLine("mqbroker", args, buildCommandlineOptions(options),
new PosixParser());
if (null == commandLine) {
System.exit(-1);
}
final BrokerConfig brokerConfig = new BrokerConfig();
final NettyServerConfig nettyServerConfig = new NettyServerConfig();
final NettyClientConfig nettyClientConfig = new NettyClientConfig();
nettyClientConfig.setUseTLS(Boolean.parseBoolean(System.getProperty(TLS_ENABLE,
String.valueOf(TlsSystemConfig.tlsMode == TlsMode.ENFORCING))));
nettyServerConfig.setListenPort(10911);
final MessageStoreConfig messageStoreConfig = new MessageStoreConfig();
if (BrokerRole.SLAVE == messageStoreConfig.getBrokerRole()) {
int ratio = messageStoreConfig.getAccessMessageInMemoryMaxRatio() - 10;
messageStoreConfig.setAccessMessageInMemoryMaxRatio(ratio);
}
if (commandLine.hasOption('c')) {
String file = commandLine.getOptionValue('c');
if (file != null) {
configFile = file;
InputStream in = new BufferedInputStream(new FileInputStream(file));
properties = new Properties();
properties.load(in);
properties2SystemEnv(properties);
MixAll.properties2Object(properties, brokerConfig);
MixAll.properties2Object(properties, nettyServerConfig);
MixAll.properties2Object(properties, nettyClientConfig);
MixAll.properties2Object(properties, messageStoreConfig);
BrokerPathConfigHelper.setBrokerConfigPath(file);
in.close();
}
}
MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), brokerConfig);
if (null == brokerConfig.getRocketmqHome()) {
System.out.printf("Please set the " + MixAll.ROCKETMQ_HOME_ENV
+ " variable in your environment to match the location of the RocketMQ installation");
System.exit(-2);
}
String namesrvAddr = brokerConfig.getNamesrvAddr();
if (null != namesrvAddr) {
try {
String[] addrArray = namesrvAddr.split(";");
for (String addr : addrArray) {
RemotingUtil.string2SocketAddress(addr);
}
} catch (Exception e) {
System.out.printf(
"The Name Server Address[%s] illegal, please set it as follows, \"127.0.0.1:9876;192.168.0.1:9876\"%n",
namesrvAddr);
System.exit(-3);
}
}
switch (messageStoreConfig.getBrokerRole()) {
case ASYNC_MASTER:
case SYNC_MASTER:
brokerConfig.setBrokerId(MixAll.MASTER_ID);
break;
case SLAVE:
if (brokerConfig.getBrokerId() <= 0) {
System.out.printf("Slave's brokerId must be > 0");
System.exit(-3);
}
break;
default:
break;
}
messageStoreConfig.setHaListenPort(nettyServerConfig.getListenPort() + 1);
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(brokerConfig.getRocketmqHome() + "/conf/logback_broker.xml");
if (commandLine.hasOption('p')) {
Logger console = LoggerFactory.getLogger(LoggerName.BROKER_CONSOLE_NAME);
MixAll.printObjectProperties(console, brokerConfig);
MixAll.printObjectProperties(console, nettyServerConfig);
MixAll.printObjectProperties(console, nettyClientConfig);
MixAll.printObjectProperties(console, messageStoreConfig);
System.exit(0);
} else if (commandLine.hasOption('m')) {
Logger console = LoggerFactory.getLogger(LoggerName.BROKER_CONSOLE_NAME);
MixAll.printObjectProperties(console, brokerConfig, true);
MixAll.printObjectProperties(console, nettyServerConfig, true);
MixAll.printObjectProperties(console, nettyClientConfig, true);
MixAll.printObjectProperties(console, messageStoreConfig, true);
System.exit(0);
}
log = LoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME);
MixAll.printObjectProperties(log, brokerConfig);
MixAll.printObjectProperties(log, nettyServerConfig);
MixAll.printObjectProperties(log, nettyClientConfig);
MixAll.printObjectProperties(log, messageStoreConfig);
final BrokerController controller = new BrokerController(
brokerConfig,
nettyServerConfig,
nettyClientConfig,
messageStoreConfig);
// remember all configs to prevent discard
controller.getConfiguration().registerConfig(properties);
boolean initResult = controller.initialize();
if (!initResult) {
controller.shutdown();
System.exit(-3);
}
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
private volatile boolean hasShutdown = false;
private AtomicInteger shutdownTimes = new AtomicInteger(0);
@Override
public void run() {
synchronized (this) {
log.info("Shutdown hook was invoked, {}", this.shutdownTimes.incrementAndGet());
if (!this.hasShutdown) {
this.hasShutdown = true;
long beginTime = System.currentTimeMillis();
controller.shutdown();
long consumingTimeTotal = System.currentTimeMillis() - beginTime;
log.info("Shutdown hook over, consuming total time(ms): {}", consumingTimeTotal);
}
}
}
}, "ShutdownHook"));
return controller;
} catch (Throwable e) {
e.printStackTrace();
System.exit(-1);
}
return null;
}
private static void properties2SystemEnv(Properties properties) {
if (properties == null) {
return;
}
String rmqAddressServerDomain = properties.getProperty("rmqAddressServerDomain", MixAll.WS_DOMAIN_NAME);
String rmqAddressServerSubGroup = properties.getProperty("rmqAddressServerSubGroup", MixAll.WS_DOMAIN_SUBGROUP);
System.setProperty("rocketmq.namesrv.domain", rmqAddressServerDomain);
System.setProperty("rocketmq.namesrv.domain.subgroup", rmqAddressServerSubGroup);
}
private static Options buildCommandlineOptions(final Options options) {
Option opt = new Option("c", "configFile", true, "Broker config properties file");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("p", "printConfigItem", false, "Print all config item");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("m", "printImportantConfig", false, "Print important config item");
opt.setRequired(false);
options.addOption(opt);
return options;
}
}
```
|
```package org.apache.rocketmq.common;
import java.util.Properties;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within;
public class UtilAllTest {
@Test
public void testCurrentStackTrace() {
String currentStackTrace = UtilAll.currentStackTrace();
assertThat(currentStackTrace).contains("UtilAll.currentStackTrace");
assertThat(currentStackTrace).contains("UtilAllTest.testCurrentStackTrace(");
}
@Test
public void testProperties2Object() {
DemoConfig demoConfig = new DemoConfig();
Properties properties = new Properties();
properties.setProperty("demoWidth", "123");
properties.setProperty("demoLength", "456");
properties.setProperty("demoOK", "true");
properties.setProperty("demoName", "TestDemo");
MixAll.properties2Object(properties, demoConfig);
assertThat(demoConfig.getDemoLength()).isEqualTo(456);
assertThat(demoConfig.getDemoWidth()).isEqualTo(123);
assertThat(demoConfig.isDemoOK()).isTrue();
assertThat(demoConfig.getDemoName()).isEqualTo("TestDemo");
}
@Test
public void testProperties2String() {
DemoConfig demoConfig = new DemoConfig();
demoConfig.setDemoLength(123);
demoConfig.setDemoWidth(456);
demoConfig.setDemoName("TestDemo");
demoConfig.setDemoOK(true);
Properties properties = MixAll.object2Properties(demoConfig);
assertThat(properties.getProperty("demoLength")).isEqualTo("123");
assertThat(properties.getProperty("demoWidth")).isEqualTo("456");
assertThat(properties.getProperty("demoOK")).isEqualTo("true");
assertThat(properties.getProperty("demoName")).isEqualTo("TestDemo");
}
@Test
public void testIsPropertiesEqual() {
final Properties p1 = new Properties();
final Properties p2 = new Properties();
p1.setProperty("a", "1");
p1.setProperty("b", "2");
p2.setProperty("a", "1");
p2.setProperty("b", "2");
assertThat(MixAll.isPropertiesEqual(p1, p2)).isTrue();
}
@Test
public void testGetPid() {
assertThat(UtilAll.getPid()).isGreaterThan(0);
}
@Test
public void testGetDiskPartitionSpaceUsedPercent() {
String tmpDir = System.getProperty("java.io.tmpdir");
assertThat(UtilAll.getDiskPartitionSpaceUsedPercent(null)).isCloseTo(-1, within(0.000001));
assertThat(UtilAll.getDiskPartitionSpaceUsedPercent("")).isCloseTo(-1, within(0.000001));
assertThat(UtilAll.getDiskPartitionSpaceUsedPercent("nonExistingPath")).isCloseTo(-1, within(0.000001));
assertThat(UtilAll.getDiskPartitionSpaceUsedPercent(tmpDir)).isNotCloseTo(-1, within(0.000001));
}
@Test
public void testIsBlank() {
assertThat(UtilAll.isBlank("Hello ")).isFalse();
assertThat(UtilAll.isBlank(" Hello")).isFalse();
assertThat(UtilAll.isBlank("He llo")).isFalse();
assertThat(UtilAll.isBlank(" ")).isTrue();
assertThat(UtilAll.isBlank("Hello")).isFalse();
}
static class DemoConfig {
private int demoWidth = 0;
private int demoLength = 0;
private boolean demoOK = false;
private String demoName = "haha";
int getDemoWidth() {
return demoWidth;
}
public void setDemoWidth(int demoWidth) {
this.demoWidth = demoWidth;
}
public int getDemoLength() {
return demoLength;
}
public void setDemoLength(int demoLength) {
this.demoLength = demoLength;
}
public boolean isDemoOK() {
return demoOK;
}
public void setDemoOK(boolean demoOK) {
this.demoOK = demoOK;
}
public String getDemoName() {
return demoName;
}
public void setDemoName(String demoName) {
this.demoName = demoName;
}
@Override
public String toString() {
return "DemoConfig{" +
"demoWidth=" + demoWidth +
", demoLength=" + demoLength +
", demoOK=" + demoOK +
", demoName='" + demoName + '\'' +
'}';
}
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.common;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.zip.CRC32;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UtilAll {
private static final Logger log = LoggerFactory.getLogger(LoggerName.COMMON_LOGGER_NAME);
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String YYYY_MM_DD_HH_MM_SS_SSS = "yyyy-MM-dd#HH:mm:ss:SSS";
public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
final static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static int getPid() {
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
String name = runtime.getName(); // format: "pid@hostname"
try {
return Integer.parseInt(name.substring(0, name.indexOf('@')));
} catch (Exception e) {
return -1;
}
}
public static String currentStackTrace() {
StringBuilder sb = new StringBuilder();
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (StackTraceElement ste : stackTrace) {
sb.append("\n\t");
sb.append(ste.toString());
}
return sb.toString();
}
public static String offset2FileName(final long offset) {
final NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumIntegerDigits(20);
nf.setMaximumFractionDigits(0);
nf.setGroupingUsed(false);
return nf.format(offset);
}
public static long computeEclipseTimeMilliseconds(final long beginTime) {
return System.currentTimeMillis() - beginTime;
}
public static boolean isItTimeToDo(final String when) {
String[] whiles = when.split(";");
if (whiles.length > 0) {
Calendar now = Calendar.getInstance();
for (String w : whiles) {
int nowHour = Integer.parseInt(w);
if (nowHour == now.get(Calendar.HOUR_OF_DAY)) {
return true;
}
}
}
return false;
}
public static String timeMillisToHumanString() {
return timeMillisToHumanString(System.currentTimeMillis());
}
public static String timeMillisToHumanString(final long t) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(t);
return String.format("%04d%02d%02d%02d%02d%02d%03d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1,
cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),
cal.get(Calendar.MILLISECOND));
}
public static long computNextMorningTimeMillis() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.add(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
public static long computNextMinutesTimeMillis() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.add(Calendar.DAY_OF_MONTH, 0);
cal.add(Calendar.HOUR_OF_DAY, 0);
cal.add(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
public static long computNextHourTimeMillis() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.add(Calendar.DAY_OF_MONTH, 0);
cal.add(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
public static long computNextHalfHourTimeMillis() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.add(Calendar.DAY_OF_MONTH, 0);
cal.add(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 30);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
public static String timeMillisToHumanString2(final long t) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(t);
return String.format("%04d-%02d-%02d %02d:%02d:%02d,%03d",
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH) + 1,
cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE),
cal.get(Calendar.SECOND),
cal.get(Calendar.MILLISECOND));
}
public static String timeMillisToHumanString3(final long t) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(t);
return String.format("%04d%02d%02d%02d%02d%02d",
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH) + 1,
cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE),
cal.get(Calendar.SECOND));
}
public static double getDiskPartitionSpaceUsedPercent(final String path) {
if (null == path || path.isEmpty())
return -1;
try {
File file = new File(path);
if (!file.exists())
return -1;
long totalSpace = file.getTotalSpace();
if (totalSpace > 0) {
long freeSpace = file.getFreeSpace();
long usedSpace = totalSpace - freeSpace;
return usedSpace / (double) totalSpace;
}
} catch (Exception e) {
return -1;
}
return -1;
}
public static int crc32(byte[] array) {
if (array != null) {
return crc32(array, 0, array.length);
}
return 0;
}
public static int crc32(byte[] array, int offset, int length) {
CRC32 crc32 = new CRC32();
crc32.update(array, offset, length);
return (int) (crc32.getValue() & 0x7FFFFFFF);
}
public static String bytes2string(byte[] src) {
char[] hexChars = new char[src.length * 2];
for (int j = 0; j < src.length; j++) {
int v = src[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
public static byte[] string2bytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
public static byte[] uncompress(final byte[] src) throws IOException {
byte[] result = src;
byte[] uncompressData = new byte[src.length];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(src);
InflaterInputStream inflaterInputStream = new InflaterInputStream(byteArrayInputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(src.length);
try {
while (true) {
int len = inflaterInputStream.read(uncompressData, 0, uncompressData.length);
if (len <= 0) {
break;
}
byteArrayOutputStream.write(uncompressData, 0, len);
}
byteArrayOutputStream.flush();
result = byteArrayOutputStream.toByteArray();
} catch (IOException e) {
throw e;
} finally {
try {
byteArrayInputStream.close();
} catch (IOException e) {
log.error("Failed to close the stream", e);
}
try {
inflaterInputStream.close();
} catch (IOException e) {
log.error("Failed to close the stream", e);
}
try {
byteArrayOutputStream.close();
} catch (IOException e) {
log.error("Failed to close the stream", e);
}
}
return result;
}
public static byte[] compress(final byte[] src, final int level) throws IOException {
byte[] result = src;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(src.length);
java.util.zip.Deflater defeater = new java.util.zip.Deflater(level);
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, defeater);
try {
deflaterOutputStream.write(src);
deflaterOutputStream.finish();
deflaterOutputStream.close();
result = byteArrayOutputStream.toByteArray();
} catch (IOException e) {
defeater.end();
throw e;
} finally {
try {
byteArrayOutputStream.close();
} catch (IOException ignored) {
}
defeater.end();
}
return result;
}
public static int asInt(String str, int defaultValue) {
try {
return Integer.parseInt(str);
} catch (Exception e) {
return defaultValue;
}
}
public static long asLong(String str, long defaultValue) {
try {
return Long.parseLong(str);
} catch (Exception e) {
return defaultValue;
}
}
public static String formatDate(Date date, String pattern) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
return df.format(date);
}
public static Date parseDate(String date, String pattern) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
try {
return df.parse(date);
} catch (ParseException e) {
return null;
}
}
public static String responseCode2String(final int code) {
return Integer.toString(code);
}
public static String frontStringAtLeast(final String str, final int size) {
if (str != null) {
if (str.length() > size) {
return str.substring(0, size);
}
}
return str;
}
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}
return true;
}
public static String jstack() {
return jstack(Thread.getAllStackTraces());
}
public static String jstack(Map<Thread, StackTraceElement[]> map) {
StringBuilder result = new StringBuilder();
try {
Iterator<Map.Entry<Thread, StackTraceElement[]>> ite = map.entrySet().iterator();
while (ite.hasNext()) {
Map.Entry<Thread, StackTraceElement[]> entry = ite.next();
StackTraceElement[] elements = entry.getValue();
Thread thread = entry.getKey();
if (elements != null && elements.length > 0) {
String threadName = entry.getKey().getName();
result.append(String.format("%-40sTID: %d STATE: %s%n", threadName, thread.getId(), thread.getState()));
for (StackTraceElement el : elements) {
result.append(String.format("%-40s%s%n", threadName, el.toString()));
}
result.append("\n");
}
}
} catch (Throwable e) {
result.append(RemotingHelper.exceptionSimpleDesc(e));
}
return result.toString();
}
public static boolean isInternalIP(byte[] ip) {
if (ip.length != 4) {
throw new RuntimeException("illegal ipv4 bytes");
}
//10.0.0.0~10.255.255.255
//172.16.0.0~172.31.255.255
//192.168.0.0~192.168.255.255
if (ip[0] == (byte) 10) {
return true;
} else if (ip[0] == (byte) 172) {
if (ip[1] >= (byte) 16 && ip[1] <= (byte) 31) {
return true;
}
} else if (ip[0] == (byte) 192) {
if (ip[1] == (byte) 168) {
return true;
}
}
return false;
}
private static boolean ipCheck(byte[] ip) {
if (ip.length != 4) {
throw new RuntimeException("illegal ipv4 bytes");
}
// if (ip[0] == (byte)30 && ip[1] == (byte)10 && ip[2] == (byte)163 && ip[3] == (byte)120) {
// }
if (ip[0] >= (byte) 1 && ip[0] <= (byte) 126) {
if (ip[1] == (byte) 1 && ip[2] == (byte) 1 && ip[3] == (byte) 1) {
return false;
}
if (ip[1] == (byte) 0 && ip[2] == (byte) 0 && ip[3] == (byte) 0) {
return false;
}
return true;
} else if (ip[0] >= (byte) 128 && ip[0] <= (byte) 191) {
if (ip[2] == (byte) 1 && ip[3] == (byte) 1) {
return false;
}
if (ip[2] == (byte) 0 && ip[3] == (byte) 0) {
return false;
}
return true;
} else if (ip[0] >= (byte) 192 && ip[0] <= (byte) 223) {
if (ip[3] == (byte) 1) {
return false;
}
if (ip[3] == (byte) 0) {
return false;
}
return true;
}
return false;
}
public static String ipToIPv4Str(byte[] ip) {
if (ip.length != 4) {
return null;
}
return new StringBuilder().append(ip[0] & 0xFF).append(".").append(
ip[1] & 0xFF).append(".").append(ip[2] & 0xFF)
.append(".").append(ip[3] & 0xFF).toString();
}
public static byte[] getIP() {
try {
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
byte[] internalIP = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
byte[] ipByte = ip.getAddress();
if (ipByte.length == 4) {
if (ipCheck(ipByte)) {
if (!isInternalIP(ipByte)) {
return ipByte;
} else if (internalIP == null) {
internalIP = ipByte;
}
}
}
}
}
}
if (internalIP != null) {
return internalIP;
} else {
throw new RuntimeException("Can not get local ip");
}
} catch (Exception e) {
throw new RuntimeException("Can not get local ip", e);
}
}
public static void deleteFile(File file) {
if (!file.exists()) {
return;
}
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File[] files = file.listFiles();
for (File file1 : files) {
deleteFile(file1);
}
file.delete();
}
}
}
```
|
```package io.openmessaging.rocketmq.consumer;
import io.openmessaging.BytesMessage;
import io.openmessaging.Message;
import io.openmessaging.MessageHeader;
import io.openmessaging.MessagingAccessPoint;
import io.openmessaging.MessagingAccessPointFactory;
import io.openmessaging.OMS;
import io.openmessaging.PropertyKeys;
import io.openmessaging.PullConsumer;
import io.openmessaging.rocketmq.config.ClientConfig;
import io.openmessaging.rocketmq.domain.NonStandardKeys;
import java.lang.reflect.Field;
import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer;
import org.apache.rocketmq.common.message.MessageExt;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class PullConsumerImplTest {
private PullConsumer consumer;
private String queueName = "HELLO_QUEUE";
@Mock
private DefaultMQPullConsumer rocketmqPullConsumer;
private LocalMessageCache localMessageCache = null;
@Before
public void init() throws NoSuchFieldException, IllegalAccessException {
final MessagingAccessPoint messagingAccessPoint = MessagingAccessPointFactory
.getMessagingAccessPoint("openmessaging:rocketmq://IP1:9876,IP2:9876/namespace");
consumer = messagingAccessPoint.createPullConsumer(queueName,
OMS.newKeyValue().put(NonStandardKeys.CONSUMER_GROUP, "TestGroup"));
Field field = PullConsumerImpl.class.getDeclaredField("rocketmqPullConsumer");
field.setAccessible(true);
field.set(consumer, rocketmqPullConsumer); //Replace
ClientConfig clientConfig = new ClientConfig();
clientConfig.setOmsOperationTimeout(200);
localMessageCache = spy(new LocalMessageCache(rocketmqPullConsumer, clientConfig));
field = PullConsumerImpl.class.getDeclaredField("localMessageCache");
field.setAccessible(true);
field.set(consumer, localMessageCache);
messagingAccessPoint.startup();
consumer.startup();
}
@Test
public void testPoll() {
final byte[] testBody = new byte[] {'a', 'b'};
MessageExt consumedMsg = new MessageExt();
consumedMsg.setMsgId("NewMsgId");
consumedMsg.setBody(testBody);
consumedMsg.putUserProperty(NonStandardKeys.MESSAGE_DESTINATION, "TOPIC");
consumedMsg.setTopic(queueName);
when(localMessageCache.poll()).thenReturn(consumedMsg);
Message message = consumer.poll();
assertThat(message.headers().getString(MessageHeader.MESSAGE_ID)).isEqualTo("NewMsgId");
assertThat(((BytesMessage) message).getBody()).isEqualTo(testBody);
}
@Test
public void testPoll_WithTimeout() {
//There is a default timeout value, @see ClientConfig#omsOperationTimeout.
Message message = consumer.poll();
assertThat(message).isNull();
message = consumer.poll(OMS.newKeyValue().put(PropertyKeys.OPERATION_TIMEOUT, 100));
assertThat(message).isNull();
}
}```
|
Please help me generate a test for this class.
|
```package io.openmessaging.rocketmq.consumer;
import io.openmessaging.KeyValue;
import io.openmessaging.Message;
import io.openmessaging.PropertyKeys;
import io.openmessaging.PullConsumer;
import io.openmessaging.exception.OMSRuntimeException;
import io.openmessaging.rocketmq.config.ClientConfig;
import io.openmessaging.rocketmq.domain.ConsumeRequest;
import io.openmessaging.rocketmq.utils.BeanUtils;
import io.openmessaging.rocketmq.utils.OMSUtil;
import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer;
import org.apache.rocketmq.client.consumer.MQPullConsumer;
import org.apache.rocketmq.client.consumer.MQPullConsumerScheduleService;
import org.apache.rocketmq.client.consumer.PullResult;
import org.apache.rocketmq.client.consumer.PullTaskCallback;
import org.apache.rocketmq.client.consumer.PullTaskContext;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.impl.consumer.ProcessQueue;
import org.apache.rocketmq.client.log.ClientLogger;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;
import org.slf4j.Logger;
public class PullConsumerImpl implements PullConsumer {
private final DefaultMQPullConsumer rocketmqPullConsumer;
private final KeyValue properties;
private boolean started = false;
private String targetQueueName;
private final MQPullConsumerScheduleService pullConsumerScheduleService;
private final LocalMessageCache localMessageCache;
private final ClientConfig clientConfig;
final static Logger log = ClientLogger.getLog();
public PullConsumerImpl(final String queueName, final KeyValue properties) {
this.properties = properties;
this.targetQueueName = queueName;
this.clientConfig = BeanUtils.populate(properties, ClientConfig.class);
String consumerGroup = clientConfig.getRmqConsumerGroup();
if (null == consumerGroup || consumerGroup.isEmpty()) {
throw new OMSRuntimeException("-1", "Consumer Group is necessary for RocketMQ, please set it.");
}
pullConsumerScheduleService = new MQPullConsumerScheduleService(consumerGroup);
this.rocketmqPullConsumer = pullConsumerScheduleService.getDefaultMQPullConsumer();
String accessPoints = clientConfig.getOmsAccessPoints();
if (accessPoints == null || accessPoints.isEmpty()) {
throw new OMSRuntimeException("-1", "OMS AccessPoints is null or empty.");
}
this.rocketmqPullConsumer.setNamesrvAddr(accessPoints.replace(',', ';'));
this.rocketmqPullConsumer.setConsumerGroup(consumerGroup);
int maxReDeliveryTimes = clientConfig.getRmqMaxRedeliveryTimes();
this.rocketmqPullConsumer.setMaxReconsumeTimes(maxReDeliveryTimes);
String consumerId = OMSUtil.buildInstanceName();
this.rocketmqPullConsumer.setInstanceName(consumerId);
properties.put(PropertyKeys.CONSUMER_ID, consumerId);
this.localMessageCache = new LocalMessageCache(this.rocketmqPullConsumer, clientConfig);
}
@Override
public KeyValue properties() {
return properties;
}
@Override
public Message poll() {
MessageExt rmqMsg = localMessageCache.poll();
return rmqMsg == null ? null : OMSUtil.msgConvert(rmqMsg);
}
@Override
public Message poll(final KeyValue properties) {
MessageExt rmqMsg = localMessageCache.poll(properties);
return rmqMsg == null ? null : OMSUtil.msgConvert(rmqMsg);
}
@Override
public void ack(final String messageId) {
localMessageCache.ack(messageId);
}
@Override
public void ack(final String messageId, final KeyValue properties) {
localMessageCache.ack(messageId);
}
@Override
public synchronized void startup() {
if (!started) {
try {
registerPullTaskCallback();
this.pullConsumerScheduleService.start();
this.localMessageCache.startup();
} catch (MQClientException e) {
throw new OMSRuntimeException("-1", e);
}
}
this.started = true;
}
private void registerPullTaskCallback() {
this.pullConsumerScheduleService.registerPullTaskCallback(targetQueueName, new PullTaskCallback() {
@Override
public void doPullTask(final MessageQueue mq, final PullTaskContext context) {
MQPullConsumer consumer = context.getPullConsumer();
try {
long offset = localMessageCache.nextPullOffset(mq);
PullResult pullResult = consumer.pull(mq, "*",
offset, localMessageCache.nextPullBatchNums());
ProcessQueue pq = rocketmqPullConsumer.getDefaultMQPullConsumerImpl().getRebalanceImpl()
.getProcessQueueTable().get(mq);
switch (pullResult.getPullStatus()) {
case FOUND:
if (pq != null) {
pq.putMessage(pullResult.getMsgFoundList());
for (final MessageExt messageExt : pullResult.getMsgFoundList()) {
localMessageCache.submitConsumeRequest(new ConsumeRequest(messageExt, mq, pq));
}
}
break;
default:
break;
}
localMessageCache.updatePullOffset(mq, pullResult.getNextBeginOffset());
} catch (Exception e) {
log.error("A error occurred in pull message process.", e);
}
}
});
}
@Override
public synchronized void shutdown() {
if (this.started) {
this.localMessageCache.shutdown();
this.pullConsumerScheduleService.shutdown();
this.rocketmqPullConsumer.shutdown();
}
this.started = false;
}
}
```
|
```package org.apache.rocketmq.common.message;
import org.junit.Assert;
import org.junit.Test;
import static org.apache.rocketmq.common.message.MessageConst.PROPERTY_TRACE_SWITCH;
import static org.junit.Assert.*;
public class MessageTest {
@Test(expected = RuntimeException.class)
public void putUserPropertyWithRuntimeException() throws Exception {
Message m = new Message();
m.putUserProperty(PROPERTY_TRACE_SWITCH, "");
}
@Test(expected = IllegalArgumentException.class)
public void putUserNullValuePropertyWithException() throws Exception {
Message m = new Message();
m.putUserProperty("prop1", null);
}
@Test(expected = IllegalArgumentException.class)
public void putUserEmptyValuePropertyWithException() throws Exception {
Message m = new Message();
m.putUserProperty("prop1", " ");
}
@Test(expected = IllegalArgumentException.class)
public void putUserNullNamePropertyWithException() throws Exception {
Message m = new Message();
m.putUserProperty(null, "val1");
}
@Test(expected = IllegalArgumentException.class)
public void putUserEmptyNamePropertyWithException() throws Exception {
Message m = new Message();
m.putUserProperty(" ", "val1");
}
@Test
public void putUserProperty() throws Exception {
Message m = new Message();
m.putUserProperty("prop1", "val1");
Assert.assertEquals("val1", m.getUserProperty("prop1"));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.common.message;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class Message implements Serializable {
private static final long serialVersionUID = 8445773977080406428L;
private String topic;
private int flag;
private Map<String, String> properties;
private byte[] body;
public Message() {
}
public Message(String topic, byte[] body) {
this(topic, "", "", 0, body, true);
}
public Message(String topic, String tags, String keys, int flag, byte[] body, boolean waitStoreMsgOK) {
this.topic = topic;
this.flag = flag;
this.body = body;
if (tags != null && tags.length() > 0)
this.setTags(tags);
if (keys != null && keys.length() > 0)
this.setKeys(keys);
this.setWaitStoreMsgOK(waitStoreMsgOK);
}
public Message(String topic, String tags, byte[] body) {
this(topic, tags, "", 0, body, true);
}
public Message(String topic, String tags, String keys, byte[] body) {
this(topic, tags, keys, 0, body, true);
}
public void setKeys(String keys) {
this.putProperty(MessageConst.PROPERTY_KEYS, keys);
}
void putProperty(final String name, final String value) {
if (null == this.properties) {
this.properties = new HashMap<String, String>();
}
this.properties.put(name, value);
}
void clearProperty(final String name) {
if (null != this.properties) {
this.properties.remove(name);
}
}
public void putUserProperty(final String name, final String value) {
if (MessageConst.STRING_HASH_SET.contains(name)) {
throw new RuntimeException(String.format(
"The Property<%s> is used by system, input another please", name));
}
if (value == null || value.trim().isEmpty()
|| name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException(
"The name or value of property can not be null or blank string!"
);
}
this.putProperty(name, value);
}
public String getUserProperty(final String name) {
return this.getProperty(name);
}
public String getProperty(final String name) {
if (null == this.properties) {
this.properties = new HashMap<String, String>();
}
return this.properties.get(name);
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getTags() {
return this.getProperty(MessageConst.PROPERTY_TAGS);
}
public void setTags(String tags) {
this.putProperty(MessageConst.PROPERTY_TAGS, tags);
}
public String getKeys() {
return this.getProperty(MessageConst.PROPERTY_KEYS);
}
public void setKeys(Collection<String> keys) {
StringBuffer sb = new StringBuffer();
for (String k : keys) {
sb.append(k);
sb.append(MessageConst.KEY_SEPARATOR);
}
this.setKeys(sb.toString().trim());
}
public int getDelayTimeLevel() {
String t = this.getProperty(MessageConst.PROPERTY_DELAY_TIME_LEVEL);
if (t != null) {
return Integer.parseInt(t);
}
return 0;
}
public void setDelayTimeLevel(int level) {
this.putProperty(MessageConst.PROPERTY_DELAY_TIME_LEVEL, String.valueOf(level));
}
public boolean isWaitStoreMsgOK() {
String result = this.getProperty(MessageConst.PROPERTY_WAIT_STORE_MSG_OK);
if (null == result)
return true;
return Boolean.parseBoolean(result);
}
public void setWaitStoreMsgOK(boolean waitStoreMsgOK) {
this.putProperty(MessageConst.PROPERTY_WAIT_STORE_MSG_OK, Boolean.toString(waitStoreMsgOK));
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public byte[] getBody() {
return body;
}
public void setBody(byte[] body) {
this.body = body;
}
public Map<String, String> getProperties() {
return properties;
}
void setProperties(Map<String, String> properties) {
this.properties = properties;
}
public String getBuyerId() {
return getProperty(MessageConst.PROPERTY_BUYER_ID);
}
public void setBuyerId(String buyerId) {
putProperty(MessageConst.PROPERTY_BUYER_ID, buyerId);
}
@Override
public String toString() {
return "Message [topic=" + topic + ", flag=" + flag + ", properties=" + properties + ", body="
+ (body != null ? body.length : 0) + "]";
}
}
```
|
```package org.apache.rocketmq.tools.command.topic;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class TopicRouteSubCommandTest {
@Test
public void testExecute() {
TopicRouteSubCommand cmd = new TopicRouteSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-t unit-test"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test");
}
}```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.tools.command.topic;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.rocketmq.common.protocol.route.TopicRouteData;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.command.SubCommand;
import org.apache.rocketmq.tools.command.SubCommandException;
public class TopicRouteSubCommand implements SubCommand {
@Override
public String commandName() {
return "topicRoute";
}
@Override
public String commandDesc() {
return "Examine topic route info";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("t", "topic", true, "topic name");
opt.setRequired(true);
options.addOption(opt);
return options;
}
@Override
public void execute(final CommandLine commandLine, final Options options,
RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
defaultMQAdminExt.start();
String topic = commandLine.getOptionValue('t').trim();
TopicRouteData topicRouteData = defaultMQAdminExt.examineTopicRouteInfo(topic);
String json = topicRouteData.toJson(true);
System.out.printf("%s%n", json);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
}
```
|
```package org.apache.rocketmq.broker;
import org.apache.rocketmq.common.BrokerConfig;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.remoting.netty.NettyClientConfig;
import org.apache.rocketmq.remoting.netty.NettyServerConfig;
import org.apache.rocketmq.store.config.MessageStoreConfig;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import static org.assertj.core.api.Assertions.assertThat;
public class BrokerControllerTest {
/**
* Tests if the controller can be properly stopped and started.
*
* @throws Exception If fails.
*/
@Test
public void testBrokerRestart() throws Exception {
BrokerController brokerController = new BrokerController(
new BrokerConfig(),
new NettyServerConfig(),
new NettyClientConfig(),
new MessageStoreConfig());
assertThat(brokerController.initialize());
brokerController.start();
brokerController.shutdown();
}
@After
public void destory() {
UtilAll.deleteFile(new File(new MessageStoreConfig().getStorePathRootDir()));
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.broker;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.broker.client.ClientHousekeepingService;
import org.apache.rocketmq.broker.client.ConsumerIdsChangeListener;
import org.apache.rocketmq.broker.client.ConsumerManager;
import org.apache.rocketmq.broker.client.DefaultConsumerIdsChangeListener;
import org.apache.rocketmq.broker.client.ProducerManager;
import org.apache.rocketmq.broker.client.net.Broker2Client;
import org.apache.rocketmq.broker.client.rebalance.RebalanceLockManager;
import org.apache.rocketmq.broker.config.ConfigUpdate;
import org.apache.rocketmq.broker.filter.CommitLogDispatcherCalcBitMap;
import org.apache.rocketmq.broker.filter.ConsumerFilterManager;
import org.apache.rocketmq.broker.filtersrv.FilterServerManager;
import org.apache.rocketmq.broker.latency.BrokerFastFailure;
import org.apache.rocketmq.broker.latency.BrokerFixedThreadPoolExecutor;
import org.apache.rocketmq.broker.longpolling.NotifyMessageArrivingListener;
import org.apache.rocketmq.broker.longpolling.PullRequestHoldService;
import org.apache.rocketmq.broker.mqtrace.ConsumeMessageHook;
import org.apache.rocketmq.broker.mqtrace.SendMessageHook;
import org.apache.rocketmq.broker.offset.ConsumerOffsetManager;
import org.apache.rocketmq.broker.out.BrokerOuterAPI;
import org.apache.rocketmq.broker.plugin.MessageStoreFactory;
import org.apache.rocketmq.broker.plugin.MessageStorePluginContext;
import org.apache.rocketmq.broker.processor.AdminBrokerProcessor;
import org.apache.rocketmq.broker.processor.ClientManageProcessor;
import org.apache.rocketmq.broker.processor.ConsumerManageProcessor;
import org.apache.rocketmq.broker.processor.EndTransactionProcessor;
import org.apache.rocketmq.broker.processor.PullMessageProcessor;
import org.apache.rocketmq.broker.processor.QueryMessageProcessor;
import org.apache.rocketmq.broker.processor.SendMessageProcessor;
import org.apache.rocketmq.broker.role.RoleChangeState;
import org.apache.rocketmq.broker.slave.SlaveSynchronize;
import org.apache.rocketmq.broker.subscription.SubscriptionGroupManager;
import org.apache.rocketmq.broker.topic.TopicConfigManager;
import org.apache.rocketmq.common.BrokerConfig;
import org.apache.rocketmq.common.Configuration;
import org.apache.rocketmq.common.ThreadFactoryImpl;
import org.apache.rocketmq.common.TopicConfig;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.constant.ConfigName;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.common.constant.PermName;
import org.apache.rocketmq.common.namesrv.RegisterBrokerResult;
import org.apache.rocketmq.common.protocol.RequestCode;
import org.apache.rocketmq.common.protocol.body.ClusterInfo;
import org.apache.rocketmq.common.protocol.body.TopicConfigSerializeWrapper;
import org.apache.rocketmq.common.protocol.route.BrokerData;
import org.apache.rocketmq.common.stats.MomentStatsItem;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.RemotingServer;
import org.apache.rocketmq.remoting.netty.NettyClientConfig;
import org.apache.rocketmq.remoting.netty.NettyRemotingServer;
import org.apache.rocketmq.remoting.netty.NettyRequestProcessor;
import org.apache.rocketmq.remoting.netty.NettyServerConfig;
import org.apache.rocketmq.remoting.netty.RequestTask;
import org.apache.rocketmq.store.DefaultMessageStore;
import org.apache.rocketmq.store.MessageArrivingListener;
import org.apache.rocketmq.store.MessageStore;
import org.apache.rocketmq.store.config.BrokerRole;
import org.apache.rocketmq.store.config.MessageStoreConfig;
import org.apache.rocketmq.store.stats.BrokerStats;
import org.apache.rocketmq.store.stats.BrokerStatsManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BrokerController {
private static final Logger log = LoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME);
private static final Logger LOG_PROTECTION = LoggerFactory.getLogger(LoggerName.PROTECTION_LOGGER_NAME);
private static final Logger LOG_WATER_MARK = LoggerFactory.getLogger(LoggerName.WATER_MARK_LOGGER_NAME);
private final BrokerConfig brokerConfig;
private final NettyServerConfig nettyServerConfig;
private final NettyClientConfig nettyClientConfig;
private final MessageStoreConfig messageStoreConfig;
private final ConsumerOffsetManager consumerOffsetManager;
private final ConsumerManager consumerManager;
private final ConsumerFilterManager consumerFilterManager;
private final ProducerManager producerManager;
private final ClientHousekeepingService clientHousekeepingService;
private final PullMessageProcessor pullMessageProcessor;
private final PullRequestHoldService pullRequestHoldService;
private final MessageArrivingListener messageArrivingListener;
private final Broker2Client broker2Client;
private final SubscriptionGroupManager subscriptionGroupManager;
private final ConsumerIdsChangeListener consumerIdsChangeListener;
private final RebalanceLockManager rebalanceLockManager = new RebalanceLockManager();
private final BrokerOuterAPI brokerOuterAPI;
private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryImpl(
"BrokerControllerScheduledThread"));
private final SlaveSynchronize slaveSynchronize;
private final BlockingQueue<Runnable> sendThreadPoolQueue;
private final BlockingQueue<Runnable> pullThreadPoolQueue;
private final BlockingQueue<Runnable> queryThreadPoolQueue;
private final BlockingQueue<Runnable> clientManagerThreadPoolQueue;
private final BlockingQueue<Runnable> consumerManagerThreadPoolQueue;
private final FilterServerManager filterServerManager;
private final BrokerStatsManager brokerStatsManager;
private final List<SendMessageHook> sendMessageHookList = new ArrayList<SendMessageHook>();
private final List<ConsumeMessageHook> consumeMessageHookList = new ArrayList<ConsumeMessageHook>();
private MessageStore messageStore;
private RemotingServer remotingServer;
private RemotingServer fastRemotingServer;
private TopicConfigManager topicConfigManager;
private ExecutorService sendMessageExecutor;
private ExecutorService pullMessageExecutor;
private ExecutorService queryMessageExecutor;
private ExecutorService adminBrokerExecutor;
private ExecutorService clientManageExecutor;
private ExecutorService consumerManageExecutor;
private volatile boolean updateMasterHAServerAddrPeriodically = false;
private BrokerStats brokerStats;
private InetSocketAddress storeHost;
private BrokerFastFailure brokerFastFailure;
private Configuration configuration;
private ScheduledFuture slaveSyncFuture;
private ScheduledFuture masterAndSlaveDiffPrintFuture;
private volatile RoleChangeState roleChangeState = RoleChangeState.SUCCESS;
private volatile long term = Long.MIN_VALUE;
private ConfigUpdate configUpdateDynamic;
public BrokerController(
final BrokerConfig brokerConfig,
final NettyServerConfig nettyServerConfig,
final NettyClientConfig nettyClientConfig,
final MessageStoreConfig messageStoreConfig
) {
this.brokerConfig = brokerConfig;
this.nettyServerConfig = nettyServerConfig;
this.nettyClientConfig = nettyClientConfig;
this.messageStoreConfig = messageStoreConfig;
this.consumerOffsetManager = new ConsumerOffsetManager(this);
this.topicConfigManager = new TopicConfigManager(this);
this.pullMessageProcessor = new PullMessageProcessor(this);
this.pullRequestHoldService = new PullRequestHoldService(this);
this.messageArrivingListener = new NotifyMessageArrivingListener(this.pullRequestHoldService);
this.consumerIdsChangeListener = new DefaultConsumerIdsChangeListener(this);
this.consumerManager = new ConsumerManager(this.consumerIdsChangeListener);
this.consumerFilterManager = new ConsumerFilterManager(this);
this.producerManager = new ProducerManager();
this.clientHousekeepingService = new ClientHousekeepingService(this);
this.broker2Client = new Broker2Client(this);
this.subscriptionGroupManager = new SubscriptionGroupManager(this);
this.brokerOuterAPI = new BrokerOuterAPI(nettyClientConfig);
this.filterServerManager = new FilterServerManager(this);
this.slaveSynchronize = new SlaveSynchronize(this);
this.sendThreadPoolQueue = new LinkedBlockingQueue<Runnable>(this.brokerConfig.getSendThreadPoolQueueCapacity());
this.pullThreadPoolQueue = new LinkedBlockingQueue<Runnable>(this.brokerConfig.getPullThreadPoolQueueCapacity());
this.queryThreadPoolQueue = new LinkedBlockingQueue<Runnable>(this.brokerConfig.getQueryThreadPoolQueueCapacity());
this.clientManagerThreadPoolQueue = new LinkedBlockingQueue<Runnable>(this.brokerConfig.getClientManagerThreadPoolQueueCapacity());
this.consumerManagerThreadPoolQueue = new LinkedBlockingQueue<Runnable>(this.brokerConfig.getConsumerManagerThreadPoolQueueCapacity());
this.brokerStatsManager = new BrokerStatsManager(this.brokerConfig.getBrokerClusterName(), brokerConfig);
this.setStoreHost(new InetSocketAddress(this.getBrokerConfig().getBrokerIP1(), this.getNettyServerConfig().getListenPort()));
this.brokerFastFailure = new BrokerFastFailure(this);
this.configuration = new Configuration(
log,
BrokerPathConfigHelper.getBrokerConfigPath(),
this.brokerConfig, this.nettyServerConfig, this.nettyClientConfig, this.messageStoreConfig
);
}
public BrokerConfig getBrokerConfig() {
return brokerConfig;
}
public NettyServerConfig getNettyServerConfig() {
return nettyServerConfig;
}
public BlockingQueue<Runnable> getPullThreadPoolQueue() {
return pullThreadPoolQueue;
}
public BlockingQueue<Runnable> getQueryThreadPoolQueue() {
return queryThreadPoolQueue;
}
public boolean initialize() throws CloneNotSupportedException {
if (StringUtils.isNotEmpty(brokerConfig.getZkPath())) {
configUpdateDynamic = new ConfigUpdate(this);
if (!configUpdateDynamic.init()) {
log.error("config update failed");
return false;
}
}
boolean result = this.topicConfigManager.load();
result = result && this.consumerOffsetManager.load();
result = result && this.subscriptionGroupManager.load();
result = result && this.consumerFilterManager.load();
if (result) {
try {
this.messageStore =
new DefaultMessageStore(this.messageStoreConfig, this.brokerStatsManager, this.messageArrivingListener,
this.brokerConfig);
this.brokerStats = new BrokerStats((DefaultMessageStore) this.messageStore);
//load plugin
MessageStorePluginContext context = new MessageStorePluginContext(messageStoreConfig, brokerStatsManager, messageArrivingListener, brokerConfig);
this.messageStore = MessageStoreFactory.build(context, this.messageStore);
this.messageStore.getDispatcherList().addFirst(new CommitLogDispatcherCalcBitMap(this.brokerConfig, this.consumerFilterManager));
} catch (IOException e) {
result = false;
log.error("Failed to initialize", e);
}
}
result = result && this.messageStore.load();
if (result) {
this.remotingServer = new NettyRemotingServer(this.nettyServerConfig, this.clientHousekeepingService);
NettyServerConfig fastConfig = (NettyServerConfig) this.nettyServerConfig.clone();
fastConfig.setListenPort(nettyServerConfig.getListenPort() - 2);
this.fastRemotingServer = new NettyRemotingServer(fastConfig, this.clientHousekeepingService);
this.sendMessageExecutor = new BrokerFixedThreadPoolExecutor(
this.brokerConfig.getSendMessageThreadPoolNums(),
this.brokerConfig.getSendMessageThreadPoolNums(),
1000 * 60,
TimeUnit.MILLISECONDS,
this.sendThreadPoolQueue,
new ThreadFactoryImpl("SendMessageThread_"));
this.pullMessageExecutor = new BrokerFixedThreadPoolExecutor(
this.brokerConfig.getPullMessageThreadPoolNums(),
this.brokerConfig.getPullMessageThreadPoolNums(),
1000 * 60,
TimeUnit.MILLISECONDS,
this.pullThreadPoolQueue,
new ThreadFactoryImpl("PullMessageThread_"));
this.queryMessageExecutor = new BrokerFixedThreadPoolExecutor(
this.brokerConfig.getQueryMessageThreadPoolNums(),
this.brokerConfig.getQueryMessageThreadPoolNums(),
1000 * 60,
TimeUnit.MILLISECONDS,
this.queryThreadPoolQueue,
new ThreadFactoryImpl("QueryMessageThread_"));
this.adminBrokerExecutor =
Executors.newFixedThreadPool(this.brokerConfig.getAdminBrokerThreadPoolNums(), new ThreadFactoryImpl(
"AdminBrokerThread_"));
this.clientManageExecutor = new ThreadPoolExecutor(
this.brokerConfig.getClientManageThreadPoolNums(),
this.brokerConfig.getClientManageThreadPoolNums(),
1000 * 60,
TimeUnit.MILLISECONDS,
this.clientManagerThreadPoolQueue,
new ThreadFactoryImpl("ClientManageThread_"));
this.consumerManageExecutor =
Executors.newFixedThreadPool(this.brokerConfig.getConsumerManageThreadPoolNums(), new ThreadFactoryImpl(
"ConsumerManageThread_"));
this.registerProcessor();
final long initialDelay = UtilAll.computNextMorningTimeMillis() - System.currentTimeMillis();
final long period = 1000 * 60 * 60 * 24;
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
BrokerController.this.getBrokerStats().record();
} catch (Throwable e) {
log.error("schedule record error.", e);
}
}
}, initialDelay, period, TimeUnit.MILLISECONDS);
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
BrokerController.this.consumerOffsetManager.persist();
} catch (Throwable e) {
log.error("schedule persist consumerOffset error.", e);
}
}
}, 1000 * 10, this.brokerConfig.getFlushConsumerOffsetInterval(), TimeUnit.MILLISECONDS);
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
BrokerController.this.consumerFilterManager.persist();
} catch (Throwable e) {
log.error("schedule persist consumer filter error.", e);
}
}
}, 1000 * 10, 1000 * 10, TimeUnit.MILLISECONDS);
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
BrokerController.this.protectBroker();
} catch (Throwable e) {
log.error("protectBroker error.", e);
}
}
}, 3, 3, TimeUnit.MINUTES);
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
BrokerController.this.printWaterMark();
} catch (Throwable e) {
log.error("printWaterMark error.", e);
}
}
}, 10, 1, TimeUnit.SECONDS);
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
log.info("dispatch behind commit log {} bytes", BrokerController.this.getMessageStore().dispatchBehindBytes());
} catch (Throwable e) {
log.error("schedule dispatchBehindBytes error.", e);
}
}
}, 1000 * 10, 1000 * 60, TimeUnit.MILLISECONDS);
if (this.brokerConfig.getNamesrvAddr() != null) {
this.brokerOuterAPI.updateNameServerAddressList(this.brokerConfig.getNamesrvAddr());
log.info("Set user specified name server address: {}", this.brokerConfig.getNamesrvAddr());
} else if (this.brokerConfig.isFetchNamesrvAddrByAddressServer()) {
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
BrokerController.this.brokerOuterAPI.fetchNameServerAddr();
} catch (Throwable e) {
log.error("ScheduledTask fetchNameServerAddr exception", e);
}
}
}, 1000 * 10, 1000 * 60 * 2, TimeUnit.MILLISECONDS);
}
if (BrokerRole.SLAVE == this.messageStoreConfig.getBrokerRole()) {
initAsSlave();
} else {
initAsMaster();
}
}
return result;
}
private void initAsSlave() {
if (this.messageStoreConfig.getHaMasterAddress() != null && this.messageStoreConfig.getHaMasterAddress().length() >= 6) {
this.messageStore.updateHaMasterAddress(this.messageStoreConfig.getHaMasterAddress());
this.updateMasterHAServerAddrPeriodically = false;
} else {
this.updateMasterHAServerAddrPeriodically = true;
}
if (slaveSyncFuture != null) {
log.warn("slaveSyncFuture not null");
return;
}
slaveSyncFuture = this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
BrokerController.this.slaveSynchronize.syncAll();
} catch (Throwable e) {
log.error("ScheduledTask syncAll slave exception", e);
}
}
}, 1000 * 10, 1000 * 60, TimeUnit.MILLISECONDS);
log.info("init as a slave");
}
private void initAsMaster() {
if (masterAndSlaveDiffPrintFuture != null) {
log.warn("masterAndSlaveDiffPrintFuture not null");
return;
}
masterAndSlaveDiffPrintFuture = this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
BrokerController.this.printMasterAndSlaveDiff();
} catch (Throwable e) {
log.error("schedule printMasterAndSlaveDiff error.", e);
}
}
}, 1000 * 10, 1000 * 60, TimeUnit.MILLISECONDS);
log.info("init as a master");
}
public void registerProcessor() {
/**
* SendMessageProcessor
*/
SendMessageProcessor sendProcessor = new SendMessageProcessor(this);
sendProcessor.registerSendMessageHook(sendMessageHookList);
sendProcessor.registerConsumeMessageHook(consumeMessageHookList);
this.remotingServer.registerProcessor(RequestCode.SEND_MESSAGE, sendProcessor, this.sendMessageExecutor);
this.remotingServer.registerProcessor(RequestCode.SEND_MESSAGE_V2, sendProcessor, this.sendMessageExecutor);
this.remotingServer.registerProcessor(RequestCode.SEND_BATCH_MESSAGE, sendProcessor, this.sendMessageExecutor);
this.remotingServer.registerProcessor(RequestCode.CONSUMER_SEND_MSG_BACK, sendProcessor, this.sendMessageExecutor);
this.fastRemotingServer.registerProcessor(RequestCode.SEND_MESSAGE, sendProcessor, this.sendMessageExecutor);
this.fastRemotingServer.registerProcessor(RequestCode.SEND_MESSAGE_V2, sendProcessor, this.sendMessageExecutor);
this.fastRemotingServer.registerProcessor(RequestCode.SEND_BATCH_MESSAGE, sendProcessor, this.sendMessageExecutor);
this.fastRemotingServer.registerProcessor(RequestCode.CONSUMER_SEND_MSG_BACK, sendProcessor, this.sendMessageExecutor);
/**
* PullMessageProcessor
*/
this.remotingServer.registerProcessor(RequestCode.PULL_MESSAGE, this.pullMessageProcessor, this.pullMessageExecutor);
this.pullMessageProcessor.registerConsumeMessageHook(consumeMessageHookList);
/**
* QueryMessageProcessor
*/
NettyRequestProcessor queryProcessor = new QueryMessageProcessor(this);
this.remotingServer.registerProcessor(RequestCode.QUERY_MESSAGE, queryProcessor, this.queryMessageExecutor);
this.remotingServer.registerProcessor(RequestCode.VIEW_MESSAGE_BY_ID, queryProcessor, this.queryMessageExecutor);
this.fastRemotingServer.registerProcessor(RequestCode.QUERY_MESSAGE, queryProcessor, this.queryMessageExecutor);
this.fastRemotingServer.registerProcessor(RequestCode.VIEW_MESSAGE_BY_ID, queryProcessor, this.queryMessageExecutor);
/**
* ClientManageProcessor
*/
ClientManageProcessor clientProcessor = new ClientManageProcessor(this);
this.remotingServer.registerProcessor(RequestCode.HEART_BEAT, clientProcessor, this.clientManageExecutor);
this.remotingServer.registerProcessor(RequestCode.UNREGISTER_CLIENT, clientProcessor, this.clientManageExecutor);
this.remotingServer.registerProcessor(RequestCode.CHECK_CLIENT_CONFIG, clientProcessor, this.clientManageExecutor);
this.fastRemotingServer.registerProcessor(RequestCode.HEART_BEAT, clientProcessor, this.clientManageExecutor);
this.fastRemotingServer.registerProcessor(RequestCode.UNREGISTER_CLIENT, clientProcessor, this.clientManageExecutor);
this.fastRemotingServer.registerProcessor(RequestCode.CHECK_CLIENT_CONFIG, clientProcessor, this.clientManageExecutor);
/**
* ConsumerManageProcessor
*/
ConsumerManageProcessor consumerManageProcessor = new ConsumerManageProcessor(this);
this.remotingServer.registerProcessor(RequestCode.GET_CONSUMER_LIST_BY_GROUP, consumerManageProcessor, this.consumerManageExecutor);
this.remotingServer.registerProcessor(RequestCode.UPDATE_CONSUMER_OFFSET, consumerManageProcessor, this.consumerManageExecutor);
this.remotingServer.registerProcessor(RequestCode.QUERY_CONSUMER_OFFSET, consumerManageProcessor, this.consumerManageExecutor);
this.fastRemotingServer.registerProcessor(RequestCode.GET_CONSUMER_LIST_BY_GROUP, consumerManageProcessor, this.consumerManageExecutor);
this.fastRemotingServer.registerProcessor(RequestCode.UPDATE_CONSUMER_OFFSET, consumerManageProcessor, this.consumerManageExecutor);
this.fastRemotingServer.registerProcessor(RequestCode.QUERY_CONSUMER_OFFSET, consumerManageProcessor, this.consumerManageExecutor);
/**
* EndTransactionProcessor
*/
this.remotingServer.registerProcessor(RequestCode.END_TRANSACTION, new EndTransactionProcessor(this), this.sendMessageExecutor);
this.fastRemotingServer.registerProcessor(RequestCode.END_TRANSACTION, new EndTransactionProcessor(this), this.sendMessageExecutor);
/**
* Default
*/
AdminBrokerProcessor adminProcessor = new AdminBrokerProcessor(this);
this.remotingServer.registerDefaultProcessor(adminProcessor, this.adminBrokerExecutor);
this.fastRemotingServer.registerDefaultProcessor(adminProcessor, this.adminBrokerExecutor);
}
public BrokerStats getBrokerStats() {
return brokerStats;
}
public void setBrokerStats(BrokerStats brokerStats) {
this.brokerStats = brokerStats;
}
public void protectBroker() {
if (this.brokerConfig.isDisableConsumeIfConsumerReadSlowly()) {
final Iterator<Map.Entry<String, MomentStatsItem>> it = this.brokerStatsManager.getMomentStatsItemSetFallSize().getStatsItemTable().entrySet().iterator();
while (it.hasNext()) {
final Map.Entry<String, MomentStatsItem> next = it.next();
final long fallBehindBytes = next.getValue().getValue().get();
if (fallBehindBytes > this.brokerConfig.getConsumerFallbehindThreshold()) {
final String[] split = next.getValue().getStatsKey().split("@");
final String group = split[2];
LOG_PROTECTION.info("[PROTECT_BROKER] the consumer[{}] consume slowly, {} bytes, disable it", group, fallBehindBytes);
this.subscriptionGroupManager.disableConsume(group);
}
}
}
}
public long headSlowTimeMills(BlockingQueue<Runnable> q) {
long slowTimeMills = 0;
final Runnable peek = q.peek();
if (peek != null) {
RequestTask rt = BrokerFastFailure.castRunnable(peek);
slowTimeMills = rt == null ? 0 : this.messageStore.now() - rt.getCreateTimestamp();
}
if (slowTimeMills < 0)
slowTimeMills = 0;
return slowTimeMills;
}
public long headSlowTimeMills4SendThreadPoolQueue() {
return this.headSlowTimeMills(this.sendThreadPoolQueue);
}
public long headSlowTimeMills4PullThreadPoolQueue() {
return this.headSlowTimeMills(this.pullThreadPoolQueue);
}
public long headSlowTimeMills4QueryThreadPoolQueue() {
return this.headSlowTimeMills(this.queryThreadPoolQueue);
}
public void printWaterMark() {
LOG_WATER_MARK.info("[WATERMARK] Send Queue Size: {} SlowTimeMills: {}", this.sendThreadPoolQueue.size(), headSlowTimeMills4SendThreadPoolQueue());
LOG_WATER_MARK.info("[WATERMARK] Pull Queue Size: {} SlowTimeMills: {}", this.pullThreadPoolQueue.size(), headSlowTimeMills4PullThreadPoolQueue());
LOG_WATER_MARK.info("[WATERMARK] Query Queue Size: {} SlowTimeMills: {}", this.queryThreadPoolQueue.size(), headSlowTimeMills4QueryThreadPoolQueue());
}
public MessageStore getMessageStore() {
return messageStore;
}
public void setMessageStore(MessageStore messageStore) {
this.messageStore = messageStore;
}
private void printMasterAndSlaveDiff() {
long diff = this.messageStore.slaveFallBehindMuch();
// XXX: warn and notify me
log.info("Slave fall behind master: {} bytes", diff);
}
public Broker2Client getBroker2Client() {
return broker2Client;
}
public ConsumerManager getConsumerManager() {
return consumerManager;
}
public ConsumerFilterManager getConsumerFilterManager() {
return consumerFilterManager;
}
public ConsumerOffsetManager getConsumerOffsetManager() {
return consumerOffsetManager;
}
public MessageStoreConfig getMessageStoreConfig() {
return messageStoreConfig;
}
public ProducerManager getProducerManager() {
return producerManager;
}
public void setFastRemotingServer(RemotingServer fastRemotingServer) {
this.fastRemotingServer = fastRemotingServer;
}
public PullMessageProcessor getPullMessageProcessor() {
return pullMessageProcessor;
}
public PullRequestHoldService getPullRequestHoldService() {
return pullRequestHoldService;
}
public SubscriptionGroupManager getSubscriptionGroupManager() {
return subscriptionGroupManager;
}
public void shutdown() {
if (this.brokerStatsManager != null) {
this.brokerStatsManager.shutdown();
}
if (this.clientHousekeepingService != null) {
this.clientHousekeepingService.shutdown();
}
if (this.pullRequestHoldService != null) {
this.pullRequestHoldService.shutdown();
}
if (this.remotingServer != null) {
this.remotingServer.shutdown();
}
if (this.fastRemotingServer != null) {
this.fastRemotingServer.shutdown();
}
if (this.messageStore != null) {
this.messageStore.shutdown();
}
this.scheduledExecutorService.shutdown();
try {
this.scheduledExecutorService.awaitTermination(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
}
this.unregisterBrokerAll();
if (this.sendMessageExecutor != null) {
this.sendMessageExecutor.shutdown();
}
if (this.pullMessageExecutor != null) {
this.pullMessageExecutor.shutdown();
}
if (this.adminBrokerExecutor != null) {
this.adminBrokerExecutor.shutdown();
}
if (this.brokerOuterAPI != null) {
this.brokerOuterAPI.shutdown();
}
this.consumerOffsetManager.persist();
if (this.filterServerManager != null) {
this.filterServerManager.shutdown();
}
if (this.brokerFastFailure != null) {
this.brokerFastFailure.shutdown();
}
if (this.consumerFilterManager != null) {
this.consumerFilterManager.persist();
}
if (configUpdateDynamic != null) {
configUpdateDynamic.shutdown();
}
}
private void unregisterBrokerAll() {
unregisterBrokerAll(this.brokerConfig.getBrokerId());
}
private void unregisterBrokerAll(long brokerId) {
this.brokerOuterAPI.unregisterBrokerAll(
this.brokerConfig.getBrokerClusterName(),
this.getBrokerAddr(),
this.brokerConfig.getBrokerName(),
brokerId);
}
public String getBrokerAddr() {
return this.brokerConfig.getBrokerIP1() + ":" + this.nettyServerConfig.getListenPort();
}
public void start() throws Exception {
if (this.messageStore != null) {
this.messageStore.start();
}
if (this.remotingServer != null) {
this.remotingServer.start();
}
if (this.fastRemotingServer != null) {
this.fastRemotingServer.start();
}
if (this.brokerOuterAPI != null) {
this.brokerOuterAPI.start();
}
if (this.pullRequestHoldService != null) {
this.pullRequestHoldService.start();
}
if (this.clientHousekeepingService != null) {
this.clientHousekeepingService.start();
}
if (this.filterServerManager != null) {
this.filterServerManager.start();
}
this.registerBrokerAll(true, false);
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
log.info("registerBrokerAll start");
long start = System.currentTimeMillis();
BrokerController.this.registerBrokerAll(true, false);
long elapse = System.currentTimeMillis() - start;
log.info("registerBrokerAll cost:{}ms", elapse);
} catch (Throwable e) {
log.error("registerBrokerAll Exception", e);
}
}
}, 1000 * 10, 1000 * 30, TimeUnit.MILLISECONDS);
if (this.brokerStatsManager != null) {
this.brokerStatsManager.start();
}
if (this.brokerFastFailure != null) {
this.brokerFastFailure.start();
}
}
public synchronized void registerBrokerAll(final boolean checkOrderConfig, boolean oneway) {
if (!roleChangeState.equals(RoleChangeState.SUCCESS)) {
log.warn("role change state:{}, not register broker to name server", roleChangeState);
return;
}
TopicConfigSerializeWrapper topicConfigWrapper = this.getTopicConfigManager().buildTopicConfigSerializeWrapper();
if (!PermName.isWriteable(this.getBrokerConfig().getBrokerPermission())
|| !PermName.isReadable(this.getBrokerConfig().getBrokerPermission())) {
ConcurrentHashMap<String, TopicConfig> topicConfigTable = new ConcurrentHashMap<String, TopicConfig>();
for (TopicConfig topicConfig : topicConfigWrapper.getTopicConfigTable().values()) {
TopicConfig tmp =
new TopicConfig(topicConfig.getTopicName(), topicConfig.getReadQueueNums(), topicConfig.getWriteQueueNums(),
this.brokerConfig.getBrokerPermission());
topicConfigTable.put(topicConfig.getTopicName(), tmp);
}
topicConfigWrapper.setTopicConfigTable(topicConfigTable);
}
RegisterBrokerResult registerBrokerResult = null;
for (int i = 0; i < 3; i++) {
registerBrokerResult = this.brokerOuterAPI.registerBrokerAll(
this.brokerConfig.getBrokerClusterName(),
this.getBrokerAddr(),
this.brokerConfig.getBrokerName(),
this.brokerConfig.getBrokerId(),
this.getHAServerAddr(),
this.messageStore.getMaxPhyOffset(),
this.term,
topicConfigWrapper,
this.filterServerManager.buildNewFilterServerList(),
oneway,
this.brokerConfig.getRegisterBrokerTimeoutMills());
if (registerBrokerResult != null && registerBrokerResult.getKvTable() != null
&& registerBrokerResult.getKvTable().getTable().containsKey(ConfigName.REGISTER_RESPONSE_KV_KEY_TERM)) {
long termResponse = Long.valueOf(registerBrokerResult.getKvTable().getTable().get(ConfigName.REGISTER_RESPONSE_KV_KEY_TERM));
if (termResponse > this.term) {
log.info("term update, new term:{}, old Term:{}, register again", termResponse, this.term);
this.term = termResponse;
} else {
break;
}
} else {
break;
}
}
if (registerBrokerResult != null) {
if (this.updateMasterHAServerAddrPeriodically && registerBrokerResult.getHaServerAddr() != null) {
this.messageStore.updateHaMasterAddress(registerBrokerResult.getHaServerAddr());
}
this.slaveSynchronize.setMasterAddr(registerBrokerResult.getMasterAddr());
if (checkOrderConfig) {
this.getTopicConfigManager().updateOrderTopicConfig(registerBrokerResult.getKvTable());
}
}
}
private void shutdownOldMaster() {
if (masterAndSlaveDiffPrintFuture != null) {
masterAndSlaveDiffPrintFuture.cancel(false);
masterAndSlaveDiffPrintFuture = null;
}
if (messageStore instanceof DefaultMessageStore) {
((DefaultMessageStore) messageStore).getHaService().destroyConnections();
}
log.info("shutdown the master role");
}
private void shutdownOldSlave() {
if (slaveSyncFuture != null) {
slaveSyncFuture.cancel(false);
slaveSyncFuture = null;
}
updateMasterHAServerAddrPeriodically = false;
this.messageStore.updateHaMasterAddress(null);
log.info("shutdown the slave role");
}
public boolean onRoleChangePre(Properties properties) {
BrokerRole newRole = BrokerRole.valueOf(properties.get(ConfigName.BROKER_ROLE).toString());
if (messageStoreConfig.getBrokerRole().equals(newRole) && BrokerRole.SLAVE != newRole) {
log.warn("new role is equal to current, role:{}", messageStoreConfig.getBrokerRole());
return false;
}
if (messageStoreConfig.getBrokerRole().equals(newRole) && BrokerRole.SLAVE == newRole) {
long brokerId = Long.valueOf(properties.get(ConfigName.BROKER_ID).toString());
if (brokerId == brokerConfig.getBrokerId()) {
log.warn("broker id is equal, no need to change");
return false;
}
}
if (newRole.equals(BrokerRole.ASYNC_MASTER) || newRole.equals(BrokerRole.SYNC_MASTER)) {
if (!checkNoMaster()) {
log.error("still another master, do not init as a master");
return false;
}
}
roleChangeState = RoleChangeState.CHANGING;//will not register new role before changing completely
log.info("role status checking pass");
return true;
}
public boolean onRoleChange(BrokerRole oldBrokerRole, long oldBrokerId) {
log.info("broker role change, current role:{}, current id:{}, old role:{}, old id:{}",
this.messageStoreConfig.getBrokerRole(), this.brokerConfig.getBrokerId(), oldBrokerRole, oldBrokerId);
if (BrokerRole.SLAVE == this.messageStoreConfig.getBrokerRole() && oldBrokerRole.equals(this.messageStoreConfig.getBrokerRole())) {
unregisterBrokerAll(oldBrokerId);
roleChangeState = RoleChangeState.SUCCESS;
registerBrokerAll(true, false);
log.info("change broker id {}", this.brokerConfig.getBrokerId());
return true;
}
//1.commit log sync
if (BrokerRole.SLAVE == this.messageStoreConfig.getBrokerRole()) {
checkSyncStat();
}
//2.unregister old role
unregisterBrokerAll(oldBrokerId);
//3.reload config
if (!reloadManagerInfo()) {
roleChangeState = RoleChangeState.FAILURE;
log.error("reload manager info failed");
return false;
}
if (!getMessageStore().onRoleChange()) {
roleChangeState = RoleChangeState.FAILURE;
log.error("message store role change failed");
return false;
}
//4.clear old role and init new
if (BrokerRole.SLAVE == this.messageStoreConfig.getBrokerRole()) {
shutdownOldMaster();
initAsSlave();
} else {
shutdownOldSlave();
initAsMaster();
}
log.info("change as a {}", this.messageStoreConfig.getBrokerRole());
roleChangeState = RoleChangeState.SUCCESS;
//5.online again
registerBrokerAll(true, false);
return true;
}
private boolean checkNoMaster() {
int i = 0;
boolean isNoMaster = true;
for (; i < this.messageStoreConfig.getWaitCountInRoleChange(); i++) {
Map<String, ClusterInfo> clusterInfos = this.brokerOuterAPI.getBrokerClusterInfoOfAllNS();
isNoMaster = true;
for (ClusterInfo clusterInfo : clusterInfos.values()) {
if (clusterInfo == null) {
log.warn("get cluster info failed, wait and retry");
isNoMaster = false;
break;
}
BrokerData brokerData = clusterInfo.getBrokerAddrTable().get(this.brokerConfig.getBrokerName());
if (brokerData != null && brokerData.getBrokerAddrs() != null) {
if (brokerData.getBrokerAddrs().containsKey(MixAll.MASTER_ID)) {
isNoMaster = false;
break;
}
}
}
if (!isNoMaster) {
try {
log.info("still another master, wait a while, try the {} times", i + 1);
Thread.sleep(this.messageStoreConfig.getWaitIntervalInRoleChange());
} catch (Exception ex) {
log.error("sleep failed");
}
} else {
break;
}
}
if (i > this.messageStoreConfig.getWaitCountInRoleChange() || !isNoMaster) {
log.error("there is still a master in at least one name server");
return false;
}
return true;
}
private boolean reloadManagerInfo() {
boolean result = this.topicConfigManager.load();
result = result && this.consumerOffsetManager.load();
result = result && this.subscriptionGroupManager.load();
result = result && this.consumerFilterManager.load();
return result;
}
private void checkSyncStat() {
int i = 0;
for (; i < this.messageStoreConfig.getWaitCountInRoleChange(); i++) {
if (this.messageStore.slaveFallBehindMuch() > 0) {
try {
Thread.sleep(this.messageStoreConfig.getWaitIntervalInRoleChange());
} catch (Exception ex) {
log.error("sleep failed");
}
} else {
break;
}
}
if (i > this.messageStoreConfig.getWaitCountInRoleChange()) {
log.error("wait {} times, but still no sync", i);
} else {
log.info("wait {} times, slave sync", i);
}
}
public TopicConfigManager getTopicConfigManager() {
return topicConfigManager;
}
public void setTopicConfigManager(TopicConfigManager topicConfigManager) {
this.topicConfigManager = topicConfigManager;
}
public String getHAServerAddr() {
return this.brokerConfig.getBrokerIP2() + ":" + this.messageStoreConfig.getHaListenPort();
}
public RebalanceLockManager getRebalanceLockManager() {
return rebalanceLockManager;
}
public SlaveSynchronize getSlaveSynchronize() {
return slaveSynchronize;
}
public ExecutorService getPullMessageExecutor() {
return pullMessageExecutor;
}
public void setPullMessageExecutor(ExecutorService pullMessageExecutor) {
this.pullMessageExecutor = pullMessageExecutor;
}
public BlockingQueue<Runnable> getSendThreadPoolQueue() {
return sendThreadPoolQueue;
}
public FilterServerManager getFilterServerManager() {
return filterServerManager;
}
public BrokerStatsManager getBrokerStatsManager() {
return brokerStatsManager;
}
public List<SendMessageHook> getSendMessageHookList() {
return sendMessageHookList;
}
public void registerSendMessageHook(final SendMessageHook hook) {
this.sendMessageHookList.add(hook);
log.info("register SendMessageHook Hook, {}", hook.hookName());
}
public List<ConsumeMessageHook> getConsumeMessageHookList() {
return consumeMessageHookList;
}
public void registerConsumeMessageHook(final ConsumeMessageHook hook) {
this.consumeMessageHookList.add(hook);
log.info("register ConsumeMessageHook Hook, {}", hook.hookName());
}
public void registerServerRPCHook(RPCHook rpcHook) {
getRemotingServer().registerRPCHook(rpcHook);
}
public RemotingServer getRemotingServer() {
return remotingServer;
}
public void setRemotingServer(RemotingServer remotingServer) {
this.remotingServer = remotingServer;
}
public void registerClientRPCHook(RPCHook rpcHook) {
this.getBrokerOuterAPI().registerRPCHook(rpcHook);
}
public BrokerOuterAPI getBrokerOuterAPI() {
return brokerOuterAPI;
}
public InetSocketAddress getStoreHost() {
return storeHost;
}
public void setStoreHost(InetSocketAddress storeHost) {
this.storeHost = storeHost;
}
public Configuration getConfiguration() {
return this.configuration;
}
}
```
|
```package org.apache.rocketmq.store;
import java.io.File;
import java.io.IOException;
import org.apache.rocketmq.common.UtilAll;
import org.junit.After;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class MappedFileTest {
private final String storeMessage = "Once, there was a chance for me!";
@Test
public void testSelectMappedBuffer() throws IOException {
MappedFile mappedFile = new MappedFile("target/unit_test_store/MappedFileTest/000", 1024 * 64);
boolean result = mappedFile.appendMessage(storeMessage.getBytes());
assertThat(result).isTrue();
SelectMappedBufferResult selectMappedBufferResult = mappedFile.selectMappedBuffer(0);
byte[] data = new byte[storeMessage.length()];
selectMappedBufferResult.getByteBuffer().get(data);
String readString = new String(data);
assertThat(readString).isEqualTo(storeMessage);
mappedFile.shutdown(1000);
assertThat(mappedFile.isAvailable()).isFalse();
selectMappedBufferResult.release();
assertThat(mappedFile.isCleanupOver()).isTrue();
assertThat(mappedFile.destroy(1000)).isTrue();
}
@After
public void destory() {
File file = new File("target/unit_test_store");
UtilAll.deleteFile(file);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.store;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageExtBatch;
import org.apache.rocketmq.store.config.FlushDiskType;
import org.apache.rocketmq.store.util.LibC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.nio.ch.DirectBuffer;
public class MappedFile extends ReferenceResource {
public static final int OS_PAGE_SIZE = 1024 * 4;
protected static final Logger log = LoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME);
private static final AtomicLong TOTAL_MAPPED_VIRTUAL_MEMORY = new AtomicLong(0);
private static final AtomicInteger TOTAL_MAPPED_FILES = new AtomicInteger(0);
protected final AtomicInteger wrotePosition = new AtomicInteger(0);
//ADD BY ChenYang
protected final AtomicInteger committedPosition = new AtomicInteger(0);
private final AtomicInteger flushedPosition = new AtomicInteger(0);
protected int fileSize;
protected FileChannel fileChannel;
/**
* Message will put to here first, and then reput to FileChannel if writeBuffer is not null.
*/
protected ByteBuffer writeBuffer = null;
protected TransientStorePool transientStorePool = null;
private String fileName;
private long fileFromOffset;
private File file;
private MappedByteBuffer mappedByteBuffer;
private volatile long storeTimestamp = 0;
private boolean firstCreateInQueue = false;
public MappedFile() {
}
public MappedFile(final String fileName, final int fileSize) throws IOException {
init(fileName, fileSize);
}
public MappedFile(final String fileName, final int fileSize,
final TransientStorePool transientStorePool) throws IOException {
init(fileName, fileSize, transientStorePool);
}
public static void ensureDirOK(final String dirName) {
if (dirName != null) {
File f = new File(dirName);
if (!f.exists()) {
boolean result = f.mkdirs();
log.info(dirName + " mkdir " + (result ? "OK" : "Failed"));
}
}
}
public static void clean(final ByteBuffer buffer) {
if (buffer == null || !buffer.isDirect() || buffer.capacity() == 0)
return;
invoke(invoke(viewed(buffer), "cleaner"), "clean");
}
private static Object invoke(final Object target, final String methodName, final Class<?>... args) {
return AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
try {
Method method = method(target, methodName, args);
method.setAccessible(true);
return method.invoke(target);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
});
}
private static Method method(Object target, String methodName, Class<?>[] args)
throws NoSuchMethodException {
try {
return target.getClass().getMethod(methodName, args);
} catch (NoSuchMethodException e) {
return target.getClass().getDeclaredMethod(methodName, args);
}
}
private static ByteBuffer viewed(ByteBuffer buffer) {
String methodName = "viewedBuffer";
Method[] methods = buffer.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("attachment")) {
methodName = "attachment";
break;
}
}
ByteBuffer viewedBuffer = (ByteBuffer) invoke(buffer, methodName);
if (viewedBuffer == null)
return buffer;
else
return viewed(viewedBuffer);
}
public static int getTotalMappedFiles() {
return TOTAL_MAPPED_FILES.get();
}
public static long getTotalMappedVirtualMemory() {
return TOTAL_MAPPED_VIRTUAL_MEMORY.get();
}
public void init(final String fileName, final int fileSize,
final TransientStorePool transientStorePool) throws IOException {
init(fileName, fileSize);
this.writeBuffer = transientStorePool.borrowBuffer();
this.transientStorePool = transientStorePool;
}
private void init(final String fileName, final int fileSize) throws IOException {
this.fileName = fileName;
this.fileSize = fileSize;
this.file = new File(fileName);
this.fileFromOffset = Long.parseLong(this.file.getName());
boolean ok = false;
ensureDirOK(this.file.getParent());
try {
this.fileChannel = new RandomAccessFile(this.file, "rw").getChannel();
this.mappedByteBuffer = this.fileChannel.map(MapMode.READ_WRITE, 0, fileSize);
TOTAL_MAPPED_VIRTUAL_MEMORY.addAndGet(fileSize);
TOTAL_MAPPED_FILES.incrementAndGet();
ok = true;
} catch (FileNotFoundException e) {
log.error("create file channel " + this.fileName + " Failed. ", e);
throw e;
} catch (IOException e) {
log.error("map file " + this.fileName + " Failed. ", e);
throw e;
} finally {
if (!ok && this.fileChannel != null) {
this.fileChannel.close();
}
}
}
public long getLastModifiedTimestamp() {
return this.file.lastModified();
}
public int getFileSize() {
return fileSize;
}
public FileChannel getFileChannel() {
return fileChannel;
}
public AppendMessageResult appendMessage(final MessageExtBrokerInner msg, final AppendMessageCallback cb) {
return appendMessagesInner(msg, cb);
}
public AppendMessageResult appendMessages(final MessageExtBatch messageExtBatch, final AppendMessageCallback cb) {
return appendMessagesInner(messageExtBatch, cb);
}
public AppendMessageResult appendMessagesInner(final MessageExt messageExt, final AppendMessageCallback cb) {
assert messageExt != null;
assert cb != null;
int currentPos = this.wrotePosition.get();
if (currentPos < this.fileSize) {
ByteBuffer byteBuffer = writeBuffer != null ? writeBuffer.slice() : this.mappedByteBuffer.slice();
byteBuffer.position(currentPos);
AppendMessageResult result = null;
if (messageExt instanceof MessageExtBrokerInner) {
result = cb.doAppend(this.getFileFromOffset(), byteBuffer, this.fileSize - currentPos, (MessageExtBrokerInner) messageExt);
} else if (messageExt instanceof MessageExtBatch) {
result = cb.doAppend(this.getFileFromOffset(), byteBuffer, this.fileSize - currentPos, (MessageExtBatch) messageExt);
} else {
return new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR);
}
this.wrotePosition.addAndGet(result.getWroteBytes());
this.storeTimestamp = result.getStoreTimestamp();
return result;
}
log.error("MappedFile.appendMessage return null, wrotePosition: {} fileSize: {}", currentPos, this.fileSize);
return new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR);
}
public long getFileFromOffset() {
return this.fileFromOffset;
}
public boolean appendMessage(final byte[] data) {
int currentPos = this.wrotePosition.get();
if ((currentPos + data.length) <= this.fileSize) {
try {
this.fileChannel.position(currentPos);
this.fileChannel.write(ByteBuffer.wrap(data));
} catch (Throwable e) {
log.error("Error occurred when append message to mappedFile.", e);
}
this.wrotePosition.addAndGet(data.length);
return true;
}
return false;
}
/**
* Content of data from offset to offset + length will be wrote to file.
*
* @param offset The offset of the subarray to be used.
* @param length The length of the subarray to be used.
*/
public boolean appendMessage(final byte[] data, final int offset, final int length) {
int currentPos = this.wrotePosition.get();
if ((currentPos + length) <= this.fileSize) {
try {
this.fileChannel.position(currentPos);
this.fileChannel.write(ByteBuffer.wrap(data, offset, length));
} catch (Throwable e) {
log.error("Error occurred when append message to mappedFile.", e);
}
this.wrotePosition.addAndGet(length);
return true;
}
return false;
}
/**
* @return The current flushed position
*/
public int flush(final int flushLeastPages) {
if (this.isAbleToFlush(flushLeastPages)) {
if (this.hold()) {
int value = getReadPosition();
try {
//We only append data to fileChannel or mappedByteBuffer, never both.
if (writeBuffer != null || this.fileChannel.position() != 0) {
this.fileChannel.force(false);
} else {
this.mappedByteBuffer.force();
}
} catch (Throwable e) {
log.error("Error occurred when force data to disk.", e);
}
this.flushedPosition.set(value);
this.release();
} else {
log.warn("in flush, hold failed, flush offset = " + this.flushedPosition.get());
this.flushedPosition.set(getReadPosition());
}
}
return this.getFlushedPosition();
}
public int commit(final int commitLeastPages) {
if (writeBuffer == null) {
//no need to commit data to file channel, so just regard wrotePosition as committedPosition.
return this.wrotePosition.get();
}
if (this.isAbleToCommit(commitLeastPages)) {
if (this.hold()) {
commit0(commitLeastPages);
this.release();
} else {
log.warn("in commit, hold failed, commit offset = " + this.committedPosition.get());
}
}
// All dirty data has been committed to FileChannel.
if (writeBuffer != null && this.transientStorePool != null && this.fileSize == this.committedPosition.get()) {
this.transientStorePool.returnBuffer(writeBuffer);
this.writeBuffer = null;
}
return this.committedPosition.get();
}
protected void commit0(final int commitLeastPages) {
int writePos = this.wrotePosition.get();
int lastCommittedPosition = this.committedPosition.get();
if (writePos - this.committedPosition.get() > 0) {
try {
ByteBuffer byteBuffer = writeBuffer.slice();
byteBuffer.position(lastCommittedPosition);
byteBuffer.limit(writePos);
this.fileChannel.position(lastCommittedPosition);
this.fileChannel.write(byteBuffer);
this.committedPosition.set(writePos);
} catch (Throwable e) {
log.error("Error occurred when commit data to FileChannel.", e);
}
}
}
private boolean isAbleToFlush(final int flushLeastPages) {
int flush = this.flushedPosition.get();
int write = getReadPosition();
if (this.isFull()) {
return true;
}
if (flushLeastPages > 0) {
return ((write / OS_PAGE_SIZE) - (flush / OS_PAGE_SIZE)) >= flushLeastPages;
}
return write > flush;
}
protected boolean isAbleToCommit(final int commitLeastPages) {
int flush = this.committedPosition.get();
int write = this.wrotePosition.get();
if (this.isFull()) {
return true;
}
if (commitLeastPages > 0) {
return ((write / OS_PAGE_SIZE) - (flush / OS_PAGE_SIZE)) >= commitLeastPages;
}
return write > flush;
}
public int getFlushedPosition() {
return flushedPosition.get();
}
public void setFlushedPosition(int pos) {
this.flushedPosition.set(pos);
}
public boolean isFull() {
return this.fileSize == this.wrotePosition.get();
}
public SelectMappedBufferResult selectMappedBuffer(int pos, int size) {
int readPosition = getReadPosition();
if ((pos + size) <= readPosition) {
if (this.hold()) {
ByteBuffer byteBuffer = this.mappedByteBuffer.slice();
byteBuffer.position(pos);
ByteBuffer byteBufferNew = byteBuffer.slice();
byteBufferNew.limit(size);
return new SelectMappedBufferResult(this.fileFromOffset + pos, byteBufferNew, size, this);
} else {
log.warn("matched, but hold failed, request pos: " + pos + ", fileFromOffset: "
+ this.fileFromOffset);
}
} else {
log.warn("selectMappedBuffer request pos invalid, request pos: " + pos + ", size: " + size
+ ", fileFromOffset: " + this.fileFromOffset);
}
return null;
}
public SelectMappedBufferResult selectMappedBuffer(int pos) {
int readPosition = getReadPosition();
if (pos < readPosition && pos >= 0) {
if (this.hold()) {
ByteBuffer byteBuffer = this.mappedByteBuffer.slice();
byteBuffer.position(pos);
int size = readPosition - pos;
ByteBuffer byteBufferNew = byteBuffer.slice();
byteBufferNew.limit(size);
return new SelectMappedBufferResult(this.fileFromOffset + pos, byteBufferNew, size, this);
}
}
return null;
}
@Override
public boolean cleanup(final long currentRef) {
if (this.isAvailable()) {
log.error("this file[REF:" + currentRef + "] " + this.fileName
+ " have not shutdown, stop unmapping.");
return false;
}
if (this.isCleanupOver()) {
log.error("this file[REF:" + currentRef + "] " + this.fileName
+ " have cleanup, do not do it again.");
return true;
}
clean(this.mappedByteBuffer);
TOTAL_MAPPED_VIRTUAL_MEMORY.addAndGet(this.fileSize * (-1));
TOTAL_MAPPED_FILES.decrementAndGet();
log.info("unmap file[REF:" + currentRef + "] " + this.fileName + " OK");
return true;
}
public boolean destroy(final long intervalForcibly) {
this.shutdown(intervalForcibly);
if (this.isCleanupOver()) {
try {
this.fileChannel.close();
log.info("close file channel " + this.fileName + " OK");
long beginTime = System.currentTimeMillis();
boolean result = this.file.delete();
log.info("delete file[REF:" + this.getRefCount() + "] " + this.fileName
+ (result ? " OK, " : " Failed, ") + "W:" + this.getWrotePosition() + " M:"
+ this.getFlushedPosition() + ", "
+ UtilAll.computeEclipseTimeMilliseconds(beginTime));
} catch (Exception e) {
log.warn("close file channel " + this.fileName + " Failed. ", e);
}
return true;
} else {
log.warn("destroy mapped file[REF:" + this.getRefCount() + "] " + this.fileName
+ " Failed. cleanupOver: " + this.cleanupOver);
}
return false;
}
public int getWrotePosition() {
return wrotePosition.get();
}
public void setWrotePosition(int pos) {
this.wrotePosition.set(pos);
}
/**
* @return The max position which have valid data
*/
public int getReadPosition() {
return this.writeBuffer == null ? this.wrotePosition.get() : this.committedPosition.get();
}
public void setCommittedPosition(int pos) {
this.committedPosition.set(pos);
}
public void warmMappedFile(FlushDiskType type, int pages) {
long beginTime = System.currentTimeMillis();
ByteBuffer byteBuffer = this.mappedByteBuffer.slice();
int flush = 0;
long time = System.currentTimeMillis();
for (int i = 0, j = 0; i < this.fileSize; i += MappedFile.OS_PAGE_SIZE, j++) {
byteBuffer.put(i, (byte) 0);
// force flush when flush disk type is sync
if (type == FlushDiskType.SYNC_FLUSH) {
if ((i / OS_PAGE_SIZE) - (flush / OS_PAGE_SIZE) >= pages) {
flush = i;
mappedByteBuffer.force();
}
}
// prevent gc
if (j % 1000 == 0) {
log.info("j={}, costTime={}", j, System.currentTimeMillis() - time);
time = System.currentTimeMillis();
try {
Thread.sleep(0);
} catch (InterruptedException e) {
log.error("Interrupted", e);
}
}
}
// force flush when prepare load finished
if (type == FlushDiskType.SYNC_FLUSH) {
log.info("mapped file warm-up done, force to disk, mappedFile={}, costTime={}",
this.getFileName(), System.currentTimeMillis() - beginTime);
mappedByteBuffer.force();
}
log.info("mapped file warm-up done. mappedFile={}, costTime={}", this.getFileName(),
System.currentTimeMillis() - beginTime);
this.mlock();
}
public void truncateDirty(int pos) {
for (int i = pos; i < fileSize; i++) {
mappedByteBuffer.put(i, (byte) 0);
}
mappedByteBuffer.force();
log.info("file:{}, truncate to {}", fileName, pos);
}
public String getFileName() {
return fileName;
}
public MappedByteBuffer getMappedByteBuffer() {
return mappedByteBuffer;
}
public ByteBuffer sliceByteBuffer() {
return this.mappedByteBuffer.slice();
}
public long getStoreTimestamp() {
return storeTimestamp;
}
public boolean isFirstCreateInQueue() {
return firstCreateInQueue;
}
public void setFirstCreateInQueue(boolean firstCreateInQueue) {
this.firstCreateInQueue = firstCreateInQueue;
}
public void mlock() {
final long beginTime = System.currentTimeMillis();
final long address = ((DirectBuffer) (this.mappedByteBuffer)).address();
Pointer pointer = new Pointer(address);
{
int ret = LibC.INSTANCE.mlock(pointer, new NativeLong(this.fileSize));
log.info("mlock {} {} {} ret = {} time consuming = {}", address, this.fileName, this.fileSize, ret, System.currentTimeMillis() - beginTime);
}
{
int ret = LibC.INSTANCE.madvise(pointer, new NativeLong(this.fileSize), LibC.MADV_WILLNEED);
log.info("madvise {} {} {} ret = {} time consuming = {}", address, this.fileName, this.fileSize, ret, System.currentTimeMillis() - beginTime);
}
}
public void munlock() {
final long beginTime = System.currentTimeMillis();
final long address = ((DirectBuffer) (this.mappedByteBuffer)).address();
Pointer pointer = new Pointer(address);
int ret = LibC.INSTANCE.munlock(pointer, new NativeLong(this.fileSize));
log.info("munlock {} {} {} ret = {} time consuming = {}", address, this.fileName, this.fileSize, ret, System.currentTimeMillis() - beginTime);
}
//testable
File getFile() {
return this.file;
}
@Override
public String toString() {
return this.fileName;
}
}
```
|
```package org.apache.rocketmq.test.clientinterface;
import org.apache.rocketmq.test.sendresult.SendResult;
public interface MQProducer {
SendResult send(Object msg, Object arg);
void setDebug();
void setRun();
void shutdown();
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.client.impl.producer;
import org.apache.rocketmq.client.QueryResult;
import org.apache.rocketmq.client.Validators;
import org.apache.rocketmq.client.common.ClientErrorCode;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.hook.CheckForbiddenContext;
import org.apache.rocketmq.client.hook.CheckForbiddenHook;
import org.apache.rocketmq.client.hook.SendMessageContext;
import org.apache.rocketmq.client.hook.SendMessageHook;
import org.apache.rocketmq.client.impl.CommunicationMode;
import org.apache.rocketmq.client.impl.MQClientManager;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.client.latency.MQFaultStrategy;
import org.apache.rocketmq.client.log.ClientLogger;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.LocalTransactionExecuter;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionCheckListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.ServiceState;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.help.FAQUrl;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageAccessor;
import org.apache.rocketmq.common.message.MessageBatch;
import org.apache.rocketmq.common.message.MessageClientIDSetter;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.common.message.MessageDecoder;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageId;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.common.message.MessageType;
import org.apache.rocketmq.common.protocol.ResponseCode;
import org.apache.rocketmq.common.protocol.header.CheckTransactionStateRequestHeader;
import org.apache.rocketmq.common.protocol.header.EndTransactionRequestHeader;
import org.apache.rocketmq.common.protocol.header.SendMessageRequestHeader;
import org.apache.rocketmq.common.sysflag.MessageSysFlag;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingConnectException;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.slf4j.Logger;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class DefaultMQProducerImpl implements MQProducerInner {
private final Logger log = ClientLogger.getLog();
private final Random random = new Random();
private final DefaultMQProducer defaultMQProducer;
private final ConcurrentMap<String/* topic */, TopicPublishInfo> topicPublishInfoTable =
new ConcurrentHashMap<String, TopicPublishInfo>();
private final ArrayList<SendMessageHook> sendMessageHookList = new ArrayList<SendMessageHook>();
private final RPCHook rpcHook;
protected BlockingQueue<Runnable> checkRequestQueue;
protected ExecutorService checkExecutor;
private ServiceState serviceState = ServiceState.CREATE_JUST;
private MQClientInstance mQClientFactory;
private ArrayList<CheckForbiddenHook> checkForbiddenHookList = new ArrayList<CheckForbiddenHook>();
private int zipCompressLevel = Integer.parseInt(System.getProperty(MixAll.MESSAGE_COMPRESS_LEVEL, "5"));
private MQFaultStrategy mqFaultStrategy = new MQFaultStrategy();
public DefaultMQProducerImpl(final DefaultMQProducer defaultMQProducer) {
this(defaultMQProducer, null);
}
public DefaultMQProducerImpl(final DefaultMQProducer defaultMQProducer, RPCHook rpcHook) {
this.defaultMQProducer = defaultMQProducer;
this.rpcHook = rpcHook;
}
public void registerCheckForbiddenHook(CheckForbiddenHook checkForbiddenHook) {
this.checkForbiddenHookList.add(checkForbiddenHook);
log.info("register a new checkForbiddenHook. hookName={}, allHookSize={}", checkForbiddenHook.hookName(),
checkForbiddenHookList.size());
}
public void initTransactionEnv() {
TransactionMQProducer producer = (TransactionMQProducer) this.defaultMQProducer;
this.checkRequestQueue = new LinkedBlockingQueue<Runnable>(producer.getCheckRequestHoldMax());
this.checkExecutor = new ThreadPoolExecutor(
producer.getCheckThreadPoolMinSize(),
producer.getCheckThreadPoolMaxSize(),
1000 * 60,
TimeUnit.MILLISECONDS,
this.checkRequestQueue);
}
public void destroyTransactionEnv() {
this.checkExecutor.shutdown();
this.checkRequestQueue.clear();
}
public void registerSendMessageHook(final SendMessageHook hook) {
this.sendMessageHookList.add(hook);
log.info("register sendMessage Hook, {}", hook.hookName());
}
public void start() throws MQClientException {
this.start(true);
}
public void start(final boolean startFactory) throws MQClientException {
switch (this.serviceState) {
case CREATE_JUST:
this.serviceState = ServiceState.START_FAILED;
this.checkConfig();
if (!this.defaultMQProducer.getProducerGroup().equals(MixAll.CLIENT_INNER_PRODUCER_GROUP)) {
this.defaultMQProducer.changeInstanceNameToPID();
}
this.mQClientFactory = MQClientManager.getInstance().getAndCreateMQClientInstance(this.defaultMQProducer, rpcHook);
boolean registerOK = mQClientFactory.registerProducer(this.defaultMQProducer.getProducerGroup(), this);
if (!registerOK) {
this.serviceState = ServiceState.CREATE_JUST;
throw new MQClientException("The producer group[" + this.defaultMQProducer.getProducerGroup()
+ "] has been created before, specify another name please." + FAQUrl.suggestTodo(FAQUrl.GROUP_NAME_DUPLICATE_URL),
null);
}
this.topicPublishInfoTable.put(this.defaultMQProducer.getCreateTopicKey(), new TopicPublishInfo());
if (startFactory) {
mQClientFactory.start();
}
log.info("the producer [{}] start OK. sendMessageWithVIPChannel={}", this.defaultMQProducer.getProducerGroup(),
this.defaultMQProducer.isSendMessageWithVIPChannel());
this.serviceState = ServiceState.RUNNING;
break;
case RUNNING:
case START_FAILED:
case SHUTDOWN_ALREADY:
throw new MQClientException("The producer service state not OK, maybe started once, "
+ this.serviceState
+ FAQUrl.suggestTodo(FAQUrl.CLIENT_SERVICE_NOT_OK),
null);
default:
break;
}
this.mQClientFactory.sendHeartbeatToAllBrokerWithLock();
}
private void checkConfig() throws MQClientException {
Validators.checkGroup(this.defaultMQProducer.getProducerGroup());
if (null == this.defaultMQProducer.getProducerGroup()) {
throw new MQClientException("producerGroup is null", null);
}
if (this.defaultMQProducer.getProducerGroup().equals(MixAll.DEFAULT_PRODUCER_GROUP)) {
throw new MQClientException("producerGroup can not equal " + MixAll.DEFAULT_PRODUCER_GROUP + ", please specify another one.",
null);
}
}
public void shutdown() {
this.shutdown(true);
}
public void shutdown(final boolean shutdownFactory) {
switch (this.serviceState) {
case CREATE_JUST:
break;
case RUNNING:
this.mQClientFactory.unregisterProducer(this.defaultMQProducer.getProducerGroup());
if (shutdownFactory) {
this.mQClientFactory.shutdown();
}
log.info("the producer [{}] shutdown OK", this.defaultMQProducer.getProducerGroup());
this.serviceState = ServiceState.SHUTDOWN_ALREADY;
break;
case SHUTDOWN_ALREADY:
break;
default:
break;
}
}
@Override
public Set<String> getPublishTopicList() {
Set<String> topicList = new HashSet<String>();
for (String key : this.topicPublishInfoTable.keySet()) {
topicList.add(key);
}
return topicList;
}
@Override
public boolean isPublishTopicNeedUpdate(String topic) {
TopicPublishInfo prev = this.topicPublishInfoTable.get(topic);
return null == prev || !prev.ok();
}
@Override
public TransactionCheckListener checkListener() {
if (this.defaultMQProducer instanceof TransactionMQProducer) {
TransactionMQProducer producer = (TransactionMQProducer) defaultMQProducer;
return producer.getTransactionCheckListener();
}
return null;
}
@Override
public void checkTransactionState(final String addr, final MessageExt msg,
final CheckTransactionStateRequestHeader header) {
Runnable request = new Runnable() {
private final String brokerAddr = addr;
private final MessageExt message = msg;
private final CheckTransactionStateRequestHeader checkRequestHeader = header;
private final String group = DefaultMQProducerImpl.this.defaultMQProducer.getProducerGroup();
@Override
public void run() {
TransactionCheckListener transactionCheckListener = DefaultMQProducerImpl.this.checkListener();
if (transactionCheckListener != null) {
LocalTransactionState localTransactionState = LocalTransactionState.UNKNOW;
Throwable exception = null;
try {
localTransactionState = transactionCheckListener.checkLocalTransactionState(message);
} catch (Throwable e) {
log.error("Broker call checkTransactionState, but checkLocalTransactionState exception", e);
exception = e;
}
this.processTransactionState(
localTransactionState,
group,
exception);
} else {
log.warn("checkTransactionState, pick transactionCheckListener by group[{}] failed", group);
}
}
private void processTransactionState(
final LocalTransactionState localTransactionState,
final String producerGroup,
final Throwable exception) {
final EndTransactionRequestHeader thisHeader = new EndTransactionRequestHeader();
thisHeader.setCommitLogOffset(checkRequestHeader.getCommitLogOffset());
thisHeader.setProducerGroup(producerGroup);
thisHeader.setTranStateTableOffset(checkRequestHeader.getTranStateTableOffset());
thisHeader.setFromTransactionCheck(true);
String uniqueKey = message.getProperties().get(MessageConst.PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX);
if (uniqueKey == null) {
uniqueKey = message.getMsgId();
}
thisHeader.setMsgId(uniqueKey);
thisHeader.setTransactionId(checkRequestHeader.getTransactionId());
switch (localTransactionState) {
case COMMIT_MESSAGE:
thisHeader.setCommitOrRollback(MessageSysFlag.TRANSACTION_COMMIT_TYPE);
break;
case ROLLBACK_MESSAGE:
thisHeader.setCommitOrRollback(MessageSysFlag.TRANSACTION_ROLLBACK_TYPE);
log.warn("when broker check, client rollback this transaction, {}", thisHeader);
break;
case UNKNOW:
thisHeader.setCommitOrRollback(MessageSysFlag.TRANSACTION_NOT_TYPE);
log.warn("when broker check, client does not know this transaction state, {}", thisHeader);
break;
default:
break;
}
String remark = null;
if (exception != null) {
remark = "checkLocalTransactionState Exception: " + RemotingHelper.exceptionSimpleDesc(exception);
}
try {
DefaultMQProducerImpl.this.mQClientFactory.getMQClientAPIImpl().endTransactionOneway(brokerAddr, thisHeader, remark,
3000);
} catch (Exception e) {
log.error("endTransactionOneway exception", e);
}
}
};
this.checkExecutor.submit(request);
}
@Override
public void updateTopicPublishInfo(final String topic, final TopicPublishInfo info) {
if (info != null && topic != null) {
TopicPublishInfo prev = this.topicPublishInfoTable.put(topic, info);
if (prev != null) {
log.info("updateTopicPublishInfo prev is not null, " + prev.toString());
}
}
}
@Override
public boolean isUnitMode() {
return this.defaultMQProducer.isUnitMode();
}
public void createTopic(String key, String newTopic, int queueNum) throws MQClientException {
createTopic(key, newTopic, queueNum, 0);
}
public void createTopic(String key, String newTopic, int queueNum, int topicSysFlag) throws MQClientException {
this.makeSureStateOK();
Validators.checkTopic(newTopic);
this.mQClientFactory.getMQAdminImpl().createTopic(key, newTopic, queueNum, topicSysFlag);
}
private void makeSureStateOK() throws MQClientException {
if (this.serviceState != ServiceState.RUNNING) {
throw new MQClientException("The producer service state not OK, "
+ this.serviceState
+ FAQUrl.suggestTodo(FAQUrl.CLIENT_SERVICE_NOT_OK),
null);
}
}
public List<MessageQueue> fetchPublishMessageQueues(String topic) throws MQClientException {
this.makeSureStateOK();
return this.mQClientFactory.getMQAdminImpl().fetchPublishMessageQueues(topic);
}
public long searchOffset(MessageQueue mq, long timestamp) throws MQClientException {
this.makeSureStateOK();
return this.mQClientFactory.getMQAdminImpl().searchOffset(mq, timestamp);
}
public long maxOffset(MessageQueue mq) throws MQClientException {
this.makeSureStateOK();
return this.mQClientFactory.getMQAdminImpl().maxOffset(mq);
}
public long minOffset(MessageQueue mq) throws MQClientException {
this.makeSureStateOK();
return this.mQClientFactory.getMQAdminImpl().minOffset(mq);
}
public long earliestMsgStoreTime(MessageQueue mq) throws MQClientException {
this.makeSureStateOK();
return this.mQClientFactory.getMQAdminImpl().earliestMsgStoreTime(mq);
}
public MessageExt viewMessage(
String msgId) throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
this.makeSureStateOK();
return this.mQClientFactory.getMQAdminImpl().viewMessage(msgId);
}
public QueryResult queryMessage(String topic, String key, int maxNum, long begin, long end)
throws MQClientException, InterruptedException {
this.makeSureStateOK();
return this.mQClientFactory.getMQAdminImpl().queryMessage(topic, key, maxNum, begin, end);
}
public MessageExt queryMessageByUniqKey(String topic, String uniqKey)
throws MQClientException, InterruptedException {
this.makeSureStateOK();
return this.mQClientFactory.getMQAdminImpl().queryMessageByUniqKey(topic, uniqKey);
}
/**
* DEFAULT ASYNC -------------------------------------------------------
*/
public void send(Message msg,
SendCallback sendCallback) throws MQClientException, RemotingException, InterruptedException {
send(msg, sendCallback, this.defaultMQProducer.getSendMsgTimeout());
}
public void send(Message msg, SendCallback sendCallback, long timeout)
throws MQClientException, RemotingException, InterruptedException {
try {
this.sendDefaultImpl(msg, CommunicationMode.ASYNC, sendCallback, timeout);
} catch (MQBrokerException e) {
throw new MQClientException("unknownn exception", e);
}
}
public MessageQueue selectOneMessageQueue(final TopicPublishInfo tpInfo, final String lastBrokerName) {
return this.mqFaultStrategy.selectOneMessageQueue(tpInfo, lastBrokerName);
}
public void updateFaultItem(final String brokerName, final long currentLatency, boolean isolation) {
this.mqFaultStrategy.updateFaultItem(brokerName, currentLatency, isolation);
}
private SendResult sendDefaultImpl(
Message msg,
final CommunicationMode communicationMode,
final SendCallback sendCallback,
final long timeout
) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
this.makeSureStateOK();
Validators.checkMessage(msg, this.defaultMQProducer);
final long invokeID = random.nextLong();
long beginTimestampFirst = System.currentTimeMillis();
long beginTimestampPrev = beginTimestampFirst;
long endTimestamp = beginTimestampFirst;
TopicPublishInfo topicPublishInfo = this.tryToFindTopicPublishInfo(msg.getTopic());
if (topicPublishInfo != null && topicPublishInfo.ok()) {
MessageQueue mq = null;
Exception exception = null;
SendResult sendResult = null;
int timesTotal = communicationMode == CommunicationMode.SYNC ? 1 + this.defaultMQProducer.getRetryTimesWhenSendFailed() : 1;
int times = 0;
String[] brokersSent = new String[timesTotal];
for (; times < timesTotal; times++) {
String lastBrokerName = null == mq ? null : mq.getBrokerName();
MessageQueue mqSelected = this.selectOneMessageQueue(topicPublishInfo, lastBrokerName);
if (mqSelected != null) {
mq = mqSelected;
brokersSent[times] = mq.getBrokerName();
try {
beginTimestampPrev = System.currentTimeMillis();
sendResult = this.sendKernelImpl(msg, mq, communicationMode, sendCallback, topicPublishInfo, timeout);
endTimestamp = System.currentTimeMillis();
this.updateFaultItem(mq.getBrokerName(), endTimestamp - beginTimestampPrev, false);
switch (communicationMode) {
case ASYNC:
return null;
case ONEWAY:
return null;
case SYNC:
if (sendResult.getSendStatus() != SendStatus.SEND_OK) {
if (this.defaultMQProducer.isRetryAnotherBrokerWhenNotStoreOK()) {
continue;
}
}
return sendResult;
default:
break;
}
} catch (RemotingException e) {
endTimestamp = System.currentTimeMillis();
this.updateFaultItem(mq.getBrokerName(), endTimestamp - beginTimestampPrev, true);
log.warn(String.format("sendKernelImpl exception, resend at once, InvokeID: %s, RT: %sms, Broker: %s", invokeID, endTimestamp - beginTimestampPrev, mq), e);
log.warn(msg.toString());
exception = e;
continue;
} catch (MQClientException e) {
endTimestamp = System.currentTimeMillis();
this.updateFaultItem(mq.getBrokerName(), endTimestamp - beginTimestampPrev, true);
log.warn(String.format("sendKernelImpl exception, resend at once, InvokeID: %s, RT: %sms, Broker: %s", invokeID, endTimestamp - beginTimestampPrev, mq), e);
log.warn(msg.toString());
exception = e;
continue;
} catch (MQBrokerException e) {
endTimestamp = System.currentTimeMillis();
this.updateFaultItem(mq.getBrokerName(), endTimestamp - beginTimestampPrev, true);
log.warn(String.format("sendKernelImpl exception, resend at once, InvokeID: %s, RT: %sms, Broker: %s", invokeID, endTimestamp - beginTimestampPrev, mq), e);
log.warn(msg.toString());
exception = e;
switch (e.getResponseCode()) {
case ResponseCode.TOPIC_NOT_EXIST:
case ResponseCode.SERVICE_NOT_AVAILABLE:
case ResponseCode.SYSTEM_ERROR:
case ResponseCode.NO_PERMISSION:
case ResponseCode.NO_BUYER_ID:
case ResponseCode.NOT_IN_CURRENT_UNIT:
continue;
default:
if (sendResult != null) {
return sendResult;
}
throw e;
}
} catch (InterruptedException e) {
endTimestamp = System.currentTimeMillis();
this.updateFaultItem(mq.getBrokerName(), endTimestamp - beginTimestampPrev, false);
log.warn(String.format("sendKernelImpl exception, throw exception, InvokeID: %s, RT: %sms, Broker: %s", invokeID, endTimestamp - beginTimestampPrev, mq), e);
log.warn(msg.toString());
log.warn("sendKernelImpl exception", e);
log.warn(msg.toString());
throw e;
}
} else {
break;
}
}
if (sendResult != null) {
return sendResult;
}
String info = String.format("Send [%d] times, still failed, cost [%d]ms, Topic: %s, BrokersSent: %s",
times,
System.currentTimeMillis() - beginTimestampFirst,
msg.getTopic(),
Arrays.toString(brokersSent));
info += FAQUrl.suggestTodo(FAQUrl.SEND_MSG_FAILED);
MQClientException mqClientException = new MQClientException(info, exception);
if (exception instanceof MQBrokerException) {
mqClientException.setResponseCode(((MQBrokerException) exception).getResponseCode());
} else if (exception instanceof RemotingConnectException) {
mqClientException.setResponseCode(ClientErrorCode.CONNECT_BROKER_EXCEPTION);
} else if (exception instanceof RemotingTimeoutException) {
mqClientException.setResponseCode(ClientErrorCode.ACCESS_BROKER_TIMEOUT);
} else if (exception instanceof MQClientException) {
mqClientException.setResponseCode(ClientErrorCode.BROKER_NOT_EXIST_EXCEPTION);
}
throw mqClientException;
}
List<String> nsList = this.getmQClientFactory().getMQClientAPIImpl().getNameServerAddressList();
if (null == nsList || nsList.isEmpty()) {
throw new MQClientException(
"No name server address, please set it." + FAQUrl.suggestTodo(FAQUrl.NAME_SERVER_ADDR_NOT_EXIST_URL), null).setResponseCode(ClientErrorCode.NO_NAME_SERVER_EXCEPTION);
}
throw new MQClientException("No route info of this topic, " + msg.getTopic() + FAQUrl.suggestTodo(FAQUrl.NO_TOPIC_ROUTE_INFO),
null).setResponseCode(ClientErrorCode.NOT_FOUND_TOPIC_EXCEPTION);
}
private TopicPublishInfo tryToFindTopicPublishInfo(final String topic) {
TopicPublishInfo topicPublishInfo = this.topicPublishInfoTable.get(topic);
if (null == topicPublishInfo || !topicPublishInfo.ok()) {
this.topicPublishInfoTable.putIfAbsent(topic, new TopicPublishInfo());
this.mQClientFactory.updateTopicRouteInfoFromNameServer(topic);
topicPublishInfo = this.topicPublishInfoTable.get(topic);
}
if (topicPublishInfo.isHaveTopicRouterInfo() || topicPublishInfo.ok()) {
return topicPublishInfo;
} else {
this.mQClientFactory.updateTopicRouteInfoFromNameServer(topic, true, this.defaultMQProducer);
topicPublishInfo = this.topicPublishInfoTable.get(topic);
return topicPublishInfo;
}
}
public SendResult sendKernelImpl(final Message msg,
final MessageQueue mq,
final CommunicationMode communicationMode,
final SendCallback sendCallback,
final TopicPublishInfo topicPublishInfo,
final long timeout) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
String brokerAddr = this.mQClientFactory.findBrokerAddressInPublish(mq.getBrokerName());
if (null == brokerAddr) {
tryToFindTopicPublishInfo(mq.getTopic());
brokerAddr = this.mQClientFactory.findBrokerAddressInPublish(mq.getBrokerName());
}
SendMessageContext context = null;
if (brokerAddr != null) {
brokerAddr = MixAll.brokerVIPChannel(this.defaultMQProducer.isSendMessageWithVIPChannel(), brokerAddr);
byte[] prevBody = msg.getBody();
try {
//for MessageBatch,ID has been set in the generating process
if (!(msg instanceof MessageBatch)) {
MessageClientIDSetter.setUniqID(msg);
}
int sysFlag = 0;
if (this.tryToCompressMessage(msg)) {
sysFlag |= MessageSysFlag.COMPRESSED_FLAG;
}
final String tranMsg = msg.getProperty(MessageConst.PROPERTY_TRANSACTION_PREPARED);
if (tranMsg != null && Boolean.parseBoolean(tranMsg)) {
sysFlag |= MessageSysFlag.TRANSACTION_PREPARED_TYPE;
}
if (hasCheckForbiddenHook()) {
CheckForbiddenContext checkForbiddenContext = new CheckForbiddenContext();
checkForbiddenContext.setNameSrvAddr(this.defaultMQProducer.getNamesrvAddr());
checkForbiddenContext.setGroup(this.defaultMQProducer.getProducerGroup());
checkForbiddenContext.setCommunicationMode(communicationMode);
checkForbiddenContext.setBrokerAddr(brokerAddr);
checkForbiddenContext.setMessage(msg);
checkForbiddenContext.setMq(mq);
checkForbiddenContext.setUnitMode(this.isUnitMode());
this.executeCheckForbiddenHook(checkForbiddenContext);
}
if (this.hasSendMessageHook()) {
context = new SendMessageContext();
context.setProducer(this);
context.setProducerGroup(this.defaultMQProducer.getProducerGroup());
context.setCommunicationMode(communicationMode);
context.setBornHost(this.defaultMQProducer.getClientIP());
context.setBrokerAddr(brokerAddr);
context.setMessage(msg);
context.setMq(mq);
String isTrans = msg.getProperty(MessageConst.PROPERTY_TRANSACTION_PREPARED);
if (isTrans != null && isTrans.equals("true")) {
context.setMsgType(MessageType.Trans_Msg_Half);
}
if (msg.getProperty("__STARTDELIVERTIME") != null || msg.getProperty(MessageConst.PROPERTY_DELAY_TIME_LEVEL) != null) {
context.setMsgType(MessageType.Delay_Msg);
}
this.executeSendMessageHookBefore(context);
}
SendMessageRequestHeader requestHeader = new SendMessageRequestHeader();
requestHeader.setProducerGroup(this.defaultMQProducer.getProducerGroup());
requestHeader.setTopic(msg.getTopic());
requestHeader.setDefaultTopic(this.defaultMQProducer.getCreateTopicKey());
requestHeader.setDefaultTopicQueueNums(this.defaultMQProducer.getDefaultTopicQueueNums());
requestHeader.setQueueId(mq.getQueueId());
requestHeader.setSysFlag(sysFlag);
requestHeader.setBornTimestamp(System.currentTimeMillis());
requestHeader.setFlag(msg.getFlag());
requestHeader.setProperties(MessageDecoder.messageProperties2String(msg.getProperties()));
requestHeader.setReconsumeTimes(0);
requestHeader.setUnitMode(this.isUnitMode());
if (msg instanceof MessageBatch) {
requestHeader.setBatch(true);
requestHeader.setMultiTopic(((MessageBatch) msg).isMultiTopic());
} else {
requestHeader.setBatch(false);
requestHeader.setMultiTopic(false);
}
if (requestHeader.getTopic().startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
String reconsumeTimes = MessageAccessor.getReconsumeTime(msg);
if (reconsumeTimes != null) {
requestHeader.setReconsumeTimes(Integer.valueOf(reconsumeTimes));
MessageAccessor.clearProperty(msg, MessageConst.PROPERTY_RECONSUME_TIME);
}
String maxReconsumeTimes = MessageAccessor.getMaxReconsumeTimes(msg);
if (maxReconsumeTimes != null) {
requestHeader.setMaxReconsumeTimes(Integer.valueOf(maxReconsumeTimes));
MessageAccessor.clearProperty(msg, MessageConst.PROPERTY_MAX_RECONSUME_TIMES);
}
}
SendResult sendResult = null;
switch (communicationMode) {
case ASYNC:
sendResult = this.mQClientFactory.getMQClientAPIImpl().sendMessage(
brokerAddr,
mq.getBrokerName(),
msg,
requestHeader,
timeout,
communicationMode,
sendCallback,
topicPublishInfo,
this.mQClientFactory,
this.defaultMQProducer.getRetryTimesWhenSendAsyncFailed(),
context,
this);
break;
case ONEWAY:
case SYNC:
sendResult = this.mQClientFactory.getMQClientAPIImpl().sendMessage(
brokerAddr,
mq.getBrokerName(),
msg,
requestHeader,
timeout,
communicationMode,
context,
this);
break;
default:
assert false;
break;
}
if (this.hasSendMessageHook()) {
context.setSendResult(sendResult);
this.executeSendMessageHookAfter(context);
}
return sendResult;
} catch (RemotingException e) {
if (this.hasSendMessageHook()) {
context.setException(e);
this.executeSendMessageHookAfter(context);
}
throw e;
} catch (MQBrokerException e) {
if (this.hasSendMessageHook()) {
context.setException(e);
this.executeSendMessageHookAfter(context);
}
throw e;
} catch (InterruptedException e) {
if (this.hasSendMessageHook()) {
context.setException(e);
this.executeSendMessageHookAfter(context);
}
throw e;
} finally {
msg.setBody(prevBody);
}
}
throw new MQClientException("The broker[" + mq.getBrokerName() + "] not exist", null);
}
public MQClientInstance getmQClientFactory() {
return mQClientFactory;
}
private boolean tryToCompressMessage(final Message msg) {
if (msg instanceof MessageBatch) {
//batch dose not support compressing right now
return false;
}
byte[] body = msg.getBody();
if (body != null) {
if (body.length >= this.defaultMQProducer.getCompressMsgBodyOverHowmuch()) {
try {
byte[] data = UtilAll.compress(body, zipCompressLevel);
if (data != null) {
msg.setBody(data);
return true;
}
} catch (IOException e) {
log.error("tryToCompressMessage exception", e);
log.warn(msg.toString());
}
}
}
return false;
}
public boolean hasCheckForbiddenHook() {
return !checkForbiddenHookList.isEmpty();
}
public void executeCheckForbiddenHook(final CheckForbiddenContext context) throws MQClientException {
if (hasCheckForbiddenHook()) {
for (CheckForbiddenHook hook : checkForbiddenHookList) {
hook.checkForbidden(context);
}
}
}
public boolean hasSendMessageHook() {
return !this.sendMessageHookList.isEmpty();
}
public void executeSendMessageHookBefore(final SendMessageContext context) {
if (!this.sendMessageHookList.isEmpty()) {
for (SendMessageHook hook : this.sendMessageHookList) {
try {
hook.sendMessageBefore(context);
} catch (Throwable e) {
log.warn("failed to executeSendMessageHookBefore", e);
}
}
}
}
public void executeSendMessageHookAfter(final SendMessageContext context) {
if (!this.sendMessageHookList.isEmpty()) {
for (SendMessageHook hook : this.sendMessageHookList) {
try {
hook.sendMessageAfter(context);
} catch (Throwable e) {
log.warn("failed to executeSendMessageHookAfter", e);
}
}
}
}
/**
* DEFAULT ONEWAY -------------------------------------------------------
*/
public void sendOneway(Message msg) throws MQClientException, RemotingException, InterruptedException {
try {
this.sendDefaultImpl(msg, CommunicationMode.ONEWAY, null, this.defaultMQProducer.getSendMsgTimeout());
} catch (MQBrokerException e) {
throw new MQClientException("unknown exception", e);
}
}
/**
* KERNEL SYNC -------------------------------------------------------
*/
public SendResult send(Message msg, MessageQueue mq)
throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
return send(msg, mq, this.defaultMQProducer.getSendMsgTimeout());
}
public SendResult send(Message msg, MessageQueue mq, long timeout)
throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
this.makeSureStateOK();
Validators.checkMessage(msg, this.defaultMQProducer);
if (!msg.getTopic().equals(mq.getTopic())) {
throw new MQClientException("message's topic not equal mq's topic", null);
}
return this.sendKernelImpl(msg, mq, CommunicationMode.SYNC, null, null, timeout);
}
/**
* KERNEL ASYNC -------------------------------------------------------
*/
public void send(Message msg, MessageQueue mq, SendCallback sendCallback)
throws MQClientException, RemotingException, InterruptedException {
send(msg, mq, sendCallback, this.defaultMQProducer.getSendMsgTimeout());
}
public void send(Message msg, MessageQueue mq, SendCallback sendCallback, long timeout)
throws MQClientException, RemotingException, InterruptedException {
this.makeSureStateOK();
Validators.checkMessage(msg, this.defaultMQProducer);
if (!msg.getTopic().equals(mq.getTopic())) {
throw new MQClientException("message's topic not equal mq's topic", null);
}
try {
this.sendKernelImpl(msg, mq, CommunicationMode.ASYNC, sendCallback, null, timeout);
} catch (MQBrokerException e) {
throw new MQClientException("unknown exception", e);
}
}
/**
* KERNEL ONEWAY -------------------------------------------------------
*/
public void sendOneway(Message msg,
MessageQueue mq) throws MQClientException, RemotingException, InterruptedException {
this.makeSureStateOK();
Validators.checkMessage(msg, this.defaultMQProducer);
try {
this.sendKernelImpl(msg, mq, CommunicationMode.ONEWAY, null, null, this.defaultMQProducer.getSendMsgTimeout());
} catch (MQBrokerException e) {
throw new MQClientException("unknown exception", e);
}
}
/**
* SELECT SYNC -------------------------------------------------------
*/
public SendResult send(Message msg, MessageQueueSelector selector, Object arg)
throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
return send(msg, selector, arg, this.defaultMQProducer.getSendMsgTimeout());
}
public SendResult send(Message msg, MessageQueueSelector selector, Object arg, long timeout)
throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
return this.sendSelectImpl(msg, selector, arg, CommunicationMode.SYNC, null, timeout);
}
private SendResult sendSelectImpl(
Message msg,
MessageQueueSelector selector,
Object arg,
final CommunicationMode communicationMode,
final SendCallback sendCallback, final long timeout
) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
this.makeSureStateOK();
Validators.checkMessage(msg, this.defaultMQProducer);
TopicPublishInfo topicPublishInfo = this.tryToFindTopicPublishInfo(msg.getTopic());
if (topicPublishInfo != null && topicPublishInfo.ok()) {
MessageQueue mq = null;
try {
mq = selector.select(topicPublishInfo.getMessageQueueList(), msg, arg);
} catch (Throwable e) {
throw new MQClientException("select message queue throwed exception.", e);
}
if (mq != null) {
return this.sendKernelImpl(msg, mq, communicationMode, sendCallback, null, timeout);
} else {
throw new MQClientException("select message queue return null.", null);
}
}
throw new MQClientException("No route info for this topic, " + msg.getTopic(), null);
}
/**
* SELECT ASYNC -------------------------------------------------------
*/
public void send(Message msg, MessageQueueSelector selector, Object arg, SendCallback sendCallback)
throws MQClientException, RemotingException, InterruptedException {
send(msg, selector, arg, sendCallback, this.defaultMQProducer.getSendMsgTimeout());
}
public void send(Message msg, MessageQueueSelector selector, Object arg, SendCallback sendCallback, long timeout)
throws MQClientException, RemotingException, InterruptedException {
try {
this.sendSelectImpl(msg, selector, arg, CommunicationMode.ASYNC, sendCallback, timeout);
} catch (MQBrokerException e) {
throw new MQClientException("unknownn exception", e);
}
}
/**
* SELECT ONEWAY -------------------------------------------------------
*/
public void sendOneway(Message msg, MessageQueueSelector selector, Object arg)
throws MQClientException, RemotingException, InterruptedException {
try {
this.sendSelectImpl(msg, selector, arg, CommunicationMode.ONEWAY, null, this.defaultMQProducer.getSendMsgTimeout());
} catch (MQBrokerException e) {
throw new MQClientException("unknown exception", e);
}
}
public TransactionSendResult sendMessageInTransaction(final Message msg,
final LocalTransactionExecuter tranExecuter, final Object arg)
throws MQClientException {
if (null == tranExecuter) {
throw new MQClientException("tranExecutor is null", null);
}
Validators.checkMessage(msg, this.defaultMQProducer);
SendResult sendResult = null;
MessageAccessor.putProperty(msg, MessageConst.PROPERTY_TRANSACTION_PREPARED, "true");
MessageAccessor.putProperty(msg, MessageConst.PROPERTY_PRODUCER_GROUP, this.defaultMQProducer.getProducerGroup());
try {
sendResult = this.send(msg);
} catch (Exception e) {
throw new MQClientException("send message Exception", e);
}
LocalTransactionState localTransactionState = LocalTransactionState.UNKNOW;
Throwable localException = null;
switch (sendResult.getSendStatus()) {
case SEND_OK: {
try {
if (sendResult.getTransactionId() != null) {
msg.putUserProperty("__transactionId__", sendResult.getTransactionId());
}
localTransactionState = tranExecuter.executeLocalTransactionBranch(msg, arg);
if (null == localTransactionState) {
localTransactionState = LocalTransactionState.UNKNOW;
}
if (localTransactionState != LocalTransactionState.COMMIT_MESSAGE) {
log.info("executeLocalTransactionBranch return {}", localTransactionState);
log.info(msg.toString());
}
} catch (Throwable e) {
log.info("executeLocalTransactionBranch exception", e);
log.info(msg.toString());
localException = e;
}
}
break;
case FLUSH_DISK_TIMEOUT:
case FLUSH_SLAVE_TIMEOUT:
case SLAVE_NOT_AVAILABLE:
localTransactionState = LocalTransactionState.ROLLBACK_MESSAGE;
break;
default:
break;
}
try {
this.endTransaction(sendResult, localTransactionState, localException);
} catch (Exception e) {
log.warn("local transaction execute " + localTransactionState + ", but end broker transaction failed", e);
}
TransactionSendResult transactionSendResult = new TransactionSendResult();
transactionSendResult.setSendStatus(sendResult.getSendStatus());
transactionSendResult.setMessageQueue(sendResult.getMessageQueue());
transactionSendResult.setMsgId(sendResult.getMsgId());
transactionSendResult.setQueueOffset(sendResult.getQueueOffset());
transactionSendResult.setTransactionId(sendResult.getTransactionId());
transactionSendResult.setLocalTransactionState(localTransactionState);
return transactionSendResult;
}
/**
* DEFAULT SYNC -------------------------------------------------------
*/
public SendResult send(
Message msg) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
return send(msg, this.defaultMQProducer.getSendMsgTimeout());
}
public void endTransaction(
final SendResult sendResult,
final LocalTransactionState localTransactionState,
final Throwable localException) throws RemotingException, MQBrokerException, InterruptedException, UnknownHostException {
final MessageId id;
if (sendResult.getOffsetMsgId() != null) {
id = MessageDecoder.decodeMessageId(sendResult.getOffsetMsgId());
} else {
id = MessageDecoder.decodeMessageId(sendResult.getMsgId());
}
String transactionId = sendResult.getTransactionId();
final String brokerAddr = this.mQClientFactory.findBrokerAddressInPublish(sendResult.getMessageQueue().getBrokerName());
EndTransactionRequestHeader requestHeader = new EndTransactionRequestHeader();
requestHeader.setTransactionId(transactionId);
requestHeader.setCommitLogOffset(id.getOffset());
switch (localTransactionState) {
case COMMIT_MESSAGE:
requestHeader.setCommitOrRollback(MessageSysFlag.TRANSACTION_COMMIT_TYPE);
break;
case ROLLBACK_MESSAGE:
requestHeader.setCommitOrRollback(MessageSysFlag.TRANSACTION_ROLLBACK_TYPE);
break;
case UNKNOW:
requestHeader.setCommitOrRollback(MessageSysFlag.TRANSACTION_NOT_TYPE);
break;
default:
break;
}
requestHeader.setProducerGroup(this.defaultMQProducer.getProducerGroup());
requestHeader.setTranStateTableOffset(sendResult.getQueueOffset());
requestHeader.setMsgId(sendResult.getMsgId());
String remark = localException != null ? ("executeLocalTransactionBranch exception: " + localException.toString()) : null;
this.mQClientFactory.getMQClientAPIImpl().endTransactionOneway(brokerAddr, requestHeader, remark,
this.defaultMQProducer.getSendMsgTimeout());
}
public void setCallbackExecutor(final ExecutorService callbackExecutor) {
this.mQClientFactory.getMQClientAPIImpl().getRemotingClient().setCallbackExecutor(callbackExecutor);
}
public SendResult send(Message msg,
long timeout) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
return this.sendDefaultImpl(msg, CommunicationMode.SYNC, null, timeout);
}
public ConcurrentMap<String, TopicPublishInfo> getTopicPublishInfoTable() {
return topicPublishInfoTable;
}
public int getZipCompressLevel() {
return zipCompressLevel;
}
public void setZipCompressLevel(int zipCompressLevel) {
this.zipCompressLevel = zipCompressLevel;
}
public ServiceState getServiceState() {
return serviceState;
}
public void setServiceState(ServiceState serviceState) {
this.serviceState = serviceState;
}
public long[] getNotAvailableDuration() {
return this.mqFaultStrategy.getNotAvailableDuration();
}
public void setNotAvailableDuration(final long[] notAvailableDuration) {
this.mqFaultStrategy.setNotAvailableDuration(notAvailableDuration);
}
public long[] getLatencyMax() {
return this.mqFaultStrategy.getLatencyMax();
}
public void setLatencyMax(final long[] latencyMax) {
this.mqFaultStrategy.setLatencyMax(latencyMax);
}
public boolean isSendLatencyFaultEnable() {
return this.mqFaultStrategy.isSendLatencyFaultEnable();
}
public void setSendLatencyFaultEnable(final boolean sendLatencyFaultEnable) {
this.mqFaultStrategy.setSendLatencyFaultEnable(sendLatencyFaultEnable);
}
}
```
|
```package io.openmessaging.rocketmq.producer;
import io.openmessaging.BytesMessage;
import io.openmessaging.MessageHeader;
import io.openmessaging.MessagingAccessPoint;
import io.openmessaging.MessagingAccessPointFactory;
import io.openmessaging.SequenceProducer;
import java.lang.reflect.Field;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class SequenceProducerImplTest {
private SequenceProducer producer;
@Mock
private DefaultMQProducer rocketmqProducer;
@Before
public void init() throws NoSuchFieldException, IllegalAccessException {
final MessagingAccessPoint messagingAccessPoint = MessagingAccessPointFactory
.getMessagingAccessPoint("openmessaging:rocketmq://IP1:9876,IP2:9876/namespace");
producer = messagingAccessPoint.createSequenceProducer();
Field field = AbstractOMSProducer.class.getDeclaredField("rocketmqProducer");
field.setAccessible(true);
field.set(producer, rocketmqProducer);
messagingAccessPoint.startup();
producer.startup();
}
@Test
public void testSend_WithCommit() throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
SendResult sendResult = new SendResult();
sendResult.setMsgId("TestMsgID");
sendResult.setSendStatus(SendStatus.SEND_OK);
when(rocketmqProducer.send(ArgumentMatchers.<Message>anyList())).thenReturn(sendResult);
when(rocketmqProducer.getMaxMessageSize()).thenReturn(1024);
final BytesMessage message = producer.createBytesMessageToTopic("HELLO_TOPIC", new byte[] {'a'});
producer.send(message);
producer.commit();
assertThat(message.headers().getString(MessageHeader.MESSAGE_ID)).isEqualTo("TestMsgID");
}
@Test
public void testRollback() {
when(rocketmqProducer.getMaxMessageSize()).thenReturn(1024);
final BytesMessage message = producer.createBytesMessageToTopic("HELLO_TOPIC", new byte[] {'a'});
producer.send(message);
producer.rollback();
producer.commit(); //Commit nothing.
assertThat(message.headers().getString(MessageHeader.MESSAGE_ID)).isEqualTo(null);
}
}```
|
Please help me generate a test for this class.
|
```package io.openmessaging.rocketmq.producer;
import io.openmessaging.BytesMessage;
import io.openmessaging.KeyValue;
import io.openmessaging.Message;
import io.openmessaging.MessageHeader;
import io.openmessaging.SequenceProducer;
import io.openmessaging.rocketmq.utils.OMSUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.rocketmq.client.Validators;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
public class SequenceProducerImpl extends AbstractOMSProducer implements SequenceProducer {
private BlockingQueue<Message> msgCacheQueue;
public SequenceProducerImpl(final KeyValue properties) {
super(properties);
this.msgCacheQueue = new LinkedBlockingQueue<>();
}
@Override
public KeyValue properties() {
return properties;
}
@Override
public void send(final Message message) {
checkMessageType(message);
org.apache.rocketmq.common.message.Message rmqMessage = OMSUtil.msgConvert((BytesMessage) message);
try {
Validators.checkMessage(rmqMessage, this.rocketmqProducer);
} catch (MQClientException e) {
throw checkProducerException(rmqMessage.getTopic(), message.headers().getString(MessageHeader.MESSAGE_ID), e);
}
msgCacheQueue.add(message);
}
@Override
public void send(final Message message, final KeyValue properties) {
send(message);
}
@Override
public synchronized void commit() {
List<Message> messages = new ArrayList<>();
msgCacheQueue.drainTo(messages);
List<org.apache.rocketmq.common.message.Message> rmqMessages = new ArrayList<>();
for (Message message : messages) {
rmqMessages.add(OMSUtil.msgConvert((BytesMessage) message));
}
if (rmqMessages.size() == 0) {
return;
}
try {
SendResult sendResult = this.rocketmqProducer.send(rmqMessages);
String[] msgIdArray = sendResult.getMsgId().split(",");
for (int i = 0; i < messages.size(); i++) {
Message message = messages.get(i);
message.headers().put(MessageHeader.MESSAGE_ID, msgIdArray[i]);
}
} catch (Exception e) {
throw checkProducerException("", "", e);
}
}
@Override
public synchronized void rollback() {
msgCacheQueue.clear();
}
}
```
|
```package org.apache.rocketmq.client.latency;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class LatencyFaultToleranceImplTest {
private LatencyFaultTolerance<String> latencyFaultTolerance;
private String brokerName = "BrokerA";
private String anotherBrokerName = "BrokerB";
@Before
public void init() {
latencyFaultTolerance = new LatencyFaultToleranceImpl();
}
@Test
public void testUpdateFaultItem() throws Exception {
latencyFaultTolerance.updateFaultItem(brokerName, 3000, 3000);
assertThat(latencyFaultTolerance.isAvailable(brokerName)).isFalse();
assertThat(latencyFaultTolerance.isAvailable(anotherBrokerName)).isTrue();
}
@Test
public void testIsAvailable() throws Exception {
latencyFaultTolerance.updateFaultItem(brokerName, 3000, 50);
assertThat(latencyFaultTolerance.isAvailable(brokerName)).isFalse();
TimeUnit.MILLISECONDS.sleep(70);
assertThat(latencyFaultTolerance.isAvailable(brokerName)).isTrue();
}
@Test
public void testRemove() throws Exception {
latencyFaultTolerance.updateFaultItem(brokerName, 3000, 3000);
assertThat(latencyFaultTolerance.isAvailable(brokerName)).isFalse();
latencyFaultTolerance.remove(brokerName);
assertThat(latencyFaultTolerance.isAvailable(brokerName)).isTrue();
}
@Test
public void testPickOneAtLeast() throws Exception {
latencyFaultTolerance.updateFaultItem(brokerName, 1000, 3000);
assertThat(latencyFaultTolerance.pickOneAtLeast()).isEqualTo(brokerName);
latencyFaultTolerance.updateFaultItem(anotherBrokerName, 1001, 3000);
assertThat(latencyFaultTolerance.pickOneAtLeast()).isEqualTo(brokerName);
}
}```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.client.latency;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.rocketmq.client.common.ThreadLocalIndex;
public class LatencyFaultToleranceImpl implements LatencyFaultTolerance<String> {
private final ConcurrentHashMap<String, FaultItem> faultItemTable = new ConcurrentHashMap<String, FaultItem>(16);
private final ThreadLocalIndex whichItemWorst = new ThreadLocalIndex();
@Override
public void updateFaultItem(final String name, final long currentLatency, final long notAvailableDuration) {
FaultItem old = this.faultItemTable.get(name);
if (null == old) {
final FaultItem faultItem = new FaultItem(name);
faultItem.setCurrentLatency(currentLatency);
faultItem.setStartTimestamp(System.currentTimeMillis() + notAvailableDuration);
old = this.faultItemTable.putIfAbsent(name, faultItem);
if (old != null) {
old.setCurrentLatency(currentLatency);
old.setStartTimestamp(System.currentTimeMillis() + notAvailableDuration);
}
} else {
old.setCurrentLatency(currentLatency);
old.setStartTimestamp(System.currentTimeMillis() + notAvailableDuration);
}
}
@Override
public boolean isAvailable(final String name) {
final FaultItem faultItem = this.faultItemTable.get(name);
if (faultItem != null) {
return faultItem.isAvailable();
}
return true;
}
@Override
public void remove(final String name) {
this.faultItemTable.remove(name);
}
@Override
public String pickOneAtLeast() {
final Enumeration<FaultItem> elements = this.faultItemTable.elements();
List<FaultItem> tmpList = new LinkedList<FaultItem>();
while (elements.hasMoreElements()) {
final FaultItem faultItem = elements.nextElement();
tmpList.add(faultItem);
}
if (!tmpList.isEmpty()) {
Collections.shuffle(tmpList);
Collections.sort(tmpList);
final int half = tmpList.size() / 2;
if (half <= 0) {
return tmpList.get(0).getName();
} else {
final int i = this.whichItemWorst.getAndIncrement() % half;
return tmpList.get(i).getName();
}
}
return null;
}
@Override
public String toString() {
return "LatencyFaultToleranceImpl{" +
"faultItemTable=" + faultItemTable +
", whichItemWorst=" + whichItemWorst +
'}';
}
class FaultItem implements Comparable<FaultItem> {
private final String name;
private volatile long currentLatency;
private volatile long startTimestamp;
public FaultItem(final String name) {
this.name = name;
}
@Override
public int compareTo(final FaultItem other) {
if (this.isAvailable() != other.isAvailable()) {
if (this.isAvailable())
return -1;
if (other.isAvailable())
return 1;
}
if (this.currentLatency < other.currentLatency)
return -1;
else if (this.currentLatency > other.currentLatency) {
return 1;
}
if (this.startTimestamp < other.startTimestamp)
return -1;
else if (this.startTimestamp > other.startTimestamp) {
return 1;
}
return 0;
}
public boolean isAvailable() {
return (System.currentTimeMillis() - startTimestamp) >= 0;
}
@Override
public int hashCode() {
int result = getName() != null ? getName().hashCode() : 0;
result = 31 * result + (int) (getCurrentLatency() ^ (getCurrentLatency() >>> 32));
result = 31 * result + (int) (getStartTimestamp() ^ (getStartTimestamp() >>> 32));
return result;
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (!(o instanceof FaultItem))
return false;
final FaultItem faultItem = (FaultItem) o;
if (getCurrentLatency() != faultItem.getCurrentLatency())
return false;
if (getStartTimestamp() != faultItem.getStartTimestamp())
return false;
return getName() != null ? getName().equals(faultItem.getName()) : faultItem.getName() == null;
}
@Override
public String toString() {
return "FaultItem{" +
"name='" + name + '\'' +
", currentLatency=" + currentLatency +
", startTimestamp=" + startTimestamp +
'}';
}
public String getName() {
return name;
}
public long getCurrentLatency() {
return currentLatency;
}
public void setCurrentLatency(final long currentLatency) {
this.currentLatency = currentLatency;
}
public long getStartTimestamp() {
return startTimestamp;
}
public void setStartTimestamp(final long startTimestamp) {
this.startTimestamp = startTimestamp;
}
}
}
```
|
```package org.apache.rocketmq.broker.client;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import java.lang.reflect.Field;
import java.util.HashMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ProducerManagerTest {
private ProducerManager producerManager;
private String group = "FooBar";
private ClientChannelInfo clientInfo;
@Mock
private Channel channel;
@Before
public void init() {
producerManager = new ProducerManager();
clientInfo = new ClientChannelInfo(channel);
}
@Test
public void scanNotActiveChannel() throws Exception {
producerManager.registerProducer(group, clientInfo);
assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNotNull();
Field field = ProducerManager.class.getDeclaredField("CHANNEL_EXPIRED_TIMEOUT");
field.setAccessible(true);
long CHANNEL_EXPIRED_TIMEOUT = field.getLong(producerManager);
clientInfo.setLastUpdateTimestamp(System.currentTimeMillis() - CHANNEL_EXPIRED_TIMEOUT - 10);
when(channel.close()).thenReturn(mock(ChannelFuture.class));
producerManager.scanNotActiveChannel();
assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNull();
}
@Test
public void doChannelCloseEvent() throws Exception {
producerManager.registerProducer(group, clientInfo);
assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNotNull();
producerManager.doChannelCloseEvent("127.0.0.1", channel);
assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNull();
}
@Test
public void testRegisterProducer() throws Exception {
producerManager.registerProducer(group, clientInfo);
HashMap<Channel, ClientChannelInfo> channelMap = producerManager.getGroupChannelTable().get(group);
assertThat(channelMap).isNotNull();
assertThat(channelMap.get(channel)).isEqualTo(clientInfo);
}
@Test
public void unregisterProducer() throws Exception {
producerManager.registerProducer(group, clientInfo);
HashMap<Channel, ClientChannelInfo> channelMap = producerManager.getGroupChannelTable().get(group);
assertThat(channelMap).isNotNull();
assertThat(channelMap.get(channel)).isEqualTo(clientInfo);
producerManager.unregisterProducer(group, clientInfo);
channelMap = producerManager.getGroupChannelTable().get(group);
assertThat(channelMap).isNull();
}
}```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.broker.client;
import io.netty.channel.Channel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.common.RemotingUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProducerManager {
private static final Logger log = LoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME);
private static final long LOCK_TIMEOUT_MILLIS = 3000;
private static final long CHANNEL_EXPIRED_TIMEOUT = 1000 * 120;
private final Lock groupChannelLock = new ReentrantLock();
private final HashMap<String /* group name */, HashMap<Channel, ClientChannelInfo>> groupChannelTable =
new HashMap<String, HashMap<Channel, ClientChannelInfo>>();
public ProducerManager() {
}
public HashMap<String, HashMap<Channel, ClientChannelInfo>> getGroupChannelTable() {
HashMap<String /* group name */, HashMap<Channel, ClientChannelInfo>> newGroupChannelTable =
new HashMap<String, HashMap<Channel, ClientChannelInfo>>();
try {
if (this.groupChannelLock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
try {
newGroupChannelTable.putAll(groupChannelTable);
} finally {
groupChannelLock.unlock();
}
}
} catch (InterruptedException e) {
log.error("", e);
}
return newGroupChannelTable;
}
public void scanNotActiveChannel() {
try {
if (this.groupChannelLock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
try {
for (final Map.Entry<String, HashMap<Channel, ClientChannelInfo>> entry : this.groupChannelTable
.entrySet()) {
final String group = entry.getKey();
final HashMap<Channel, ClientChannelInfo> chlMap = entry.getValue();
Iterator<Entry<Channel, ClientChannelInfo>> it = chlMap.entrySet().iterator();
while (it.hasNext()) {
Entry<Channel, ClientChannelInfo> item = it.next();
// final Integer id = item.getKey();
final ClientChannelInfo info = item.getValue();
long diff = System.currentTimeMillis() - info.getLastUpdateTimestamp();
if (diff > CHANNEL_EXPIRED_TIMEOUT) {
it.remove();
log.warn(
"SCAN: remove expired channel[{}] from ProducerManager groupChannelTable, producer group name: {}",
RemotingHelper.parseChannelRemoteAddr(info.getChannel()), group);
RemotingUtil.closeChannel(info.getChannel());
}
}
}
} finally {
this.groupChannelLock.unlock();
}
} else {
log.warn("ProducerManager scanNotActiveChannel lock timeout");
}
} catch (InterruptedException e) {
log.error("", e);
}
}
public void doChannelCloseEvent(final String remoteAddr, final Channel channel) {
if (channel != null) {
try {
if (this.groupChannelLock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
try {
for (final Map.Entry<String, HashMap<Channel, ClientChannelInfo>> entry : this.groupChannelTable
.entrySet()) {
final String group = entry.getKey();
final HashMap<Channel, ClientChannelInfo> clientChannelInfoTable =
entry.getValue();
final ClientChannelInfo clientChannelInfo =
clientChannelInfoTable.remove(channel);
if (clientChannelInfo != null) {
log.info(
"NETTY EVENT: remove channel[{}][{}] from ProducerManager groupChannelTable, producer group: {}",
clientChannelInfo.toString(), remoteAddr, group);
}
}
} finally {
this.groupChannelLock.unlock();
}
} else {
log.warn("ProducerManager doChannelCloseEvent lock timeout");
}
} catch (InterruptedException e) {
log.error("", e);
}
}
}
public void registerProducer(final String group, final ClientChannelInfo clientChannelInfo) {
try {
ClientChannelInfo clientChannelInfoFound = null;
if (this.groupChannelLock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
try {
HashMap<Channel, ClientChannelInfo> channelTable = this.groupChannelTable.get(group);
if (null == channelTable) {
channelTable = new HashMap<>();
this.groupChannelTable.put(group, channelTable);
}
clientChannelInfoFound = channelTable.get(clientChannelInfo.getChannel());
if (null == clientChannelInfoFound) {
channelTable.put(clientChannelInfo.getChannel(), clientChannelInfo);
log.info("new producer connected, group: {} channel: {}", group,
clientChannelInfo.toString());
}
} finally {
this.groupChannelLock.unlock();
}
if (clientChannelInfoFound != null) {
clientChannelInfoFound.setLastUpdateTimestamp(System.currentTimeMillis());
}
} else {
log.warn("ProducerManager registerProducer lock timeout");
}
} catch (InterruptedException e) {
log.error("", e);
}
}
public void unregisterProducer(final String group, final ClientChannelInfo clientChannelInfo) {
try {
if (this.groupChannelLock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
try {
HashMap<Channel, ClientChannelInfo> channelTable = this.groupChannelTable.get(group);
if (null != channelTable && !channelTable.isEmpty()) {
ClientChannelInfo old = channelTable.remove(clientChannelInfo.getChannel());
if (old != null) {
log.info("unregister a producer[{}] from groupChannelTable {}", group,
clientChannelInfo.toString());
}
if (channelTable.isEmpty()) {
this.groupChannelTable.remove(group);
log.info("unregister a producer group[{}] from groupChannelTable", group);
}
}
} finally {
this.groupChannelLock.unlock();
}
} else {
log.warn("ProducerManager unregisterProducer lock timeout");
}
} catch (InterruptedException e) {
log.error("", e);
}
}
}
```
|
```package io.openmessaging.rocketmq.utils;
import io.openmessaging.KeyValue;
import io.openmessaging.OMS;
import io.openmessaging.rocketmq.config.ClientConfig;
import io.openmessaging.rocketmq.domain.NonStandardKeys;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class BeanUtilsTest {
private KeyValue properties = OMS.newKeyValue();
public static class CustomizedConfig extends ClientConfig {
final static String STRING_TEST = "string.test";
String stringTest = "foobar";
final static String DOUBLE_TEST = "double.test";
double doubleTest = 123.0;
final static String LONG_TEST = "long.test";
long longTest = 123L;
String getStringTest() {
return stringTest;
}
public void setStringTest(String stringTest) {
this.stringTest = stringTest;
}
double getDoubleTest() {
return doubleTest;
}
public void setDoubleTest(final double doubleTest) {
this.doubleTest = doubleTest;
}
long getLongTest() {
return longTest;
}
public void setLongTest(final long longTest) {
this.longTest = longTest;
}
CustomizedConfig() {
}
}
@Before
public void init() {
properties.put(NonStandardKeys.MAX_REDELIVERY_TIMES, 120);
properties.put(CustomizedConfig.STRING_TEST, "kaka");
properties.put(NonStandardKeys.CONSUMER_GROUP, "Default_Consumer_Group");
properties.put(NonStandardKeys.MESSAGE_CONSUME_TIMEOUT, 101);
properties.put(CustomizedConfig.LONG_TEST, 1234567890L);
properties.put(CustomizedConfig.DOUBLE_TEST, 10.234);
}
@Test
public void testPopulate() {
CustomizedConfig config = BeanUtils.populate(properties, CustomizedConfig.class);
//RemotingConfig config = BeanUtils.populate(properties, RemotingConfig.class);
Assert.assertEquals(config.getRmqMaxRedeliveryTimes(), 120);
Assert.assertEquals(config.getStringTest(), "kaka");
Assert.assertEquals(config.getRmqConsumerGroup(), "Default_Consumer_Group");
Assert.assertEquals(config.getRmqMessageConsumeTimeout(), 101);
Assert.assertEquals(config.getLongTest(), 1234567890L);
Assert.assertEquals(config.getDoubleTest(), 10.234, 0.000001);
}
@Test
public void testPopulate_ExistObj() {
CustomizedConfig config = new CustomizedConfig();
config.setOmsConsumerId("NewConsumerId");
Assert.assertEquals(config.getOmsConsumerId(), "NewConsumerId");
config = BeanUtils.populate(properties, config);
//RemotingConfig config = BeanUtils.populate(properties, RemotingConfig.class);
Assert.assertEquals(config.getRmqMaxRedeliveryTimes(), 120);
Assert.assertEquals(config.getStringTest(), "kaka");
Assert.assertEquals(config.getRmqConsumerGroup(), "Default_Consumer_Group");
Assert.assertEquals(config.getRmqMessageConsumeTimeout(), 101);
Assert.assertEquals(config.getLongTest(), 1234567890L);
Assert.assertEquals(config.getDoubleTest(), 10.234, 0.000001);
}
}```
|
Please help me generate a test for this class.
|
```package io.openmessaging.rocketmq.utils;
import io.openmessaging.KeyValue;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.log.ClientLogger;
import org.slf4j.Logger;
public final class BeanUtils {
final static Logger log = ClientLogger.getLog();
/**
* Maps primitive {@code Class}es to their corresponding wrapper {@code Class}.
*/
private static Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap<Class<?>, Class<?>>();
static {
primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
primitiveWrapperMap.put(Byte.TYPE, Byte.class);
primitiveWrapperMap.put(Character.TYPE, Character.class);
primitiveWrapperMap.put(Short.TYPE, Short.class);
primitiveWrapperMap.put(Integer.TYPE, Integer.class);
primitiveWrapperMap.put(Long.TYPE, Long.class);
primitiveWrapperMap.put(Double.TYPE, Double.class);
primitiveWrapperMap.put(Float.TYPE, Float.class);
primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
}
private static Map<Class<?>, Class<?>> wrapperMap = new HashMap<Class<?>, Class<?>>();
static {
for (final Class<?> primitiveClass : primitiveWrapperMap.keySet()) {
final Class<?> wrapperClass = primitiveWrapperMap.get(primitiveClass);
if (!primitiveClass.equals(wrapperClass)) {
wrapperMap.put(wrapperClass, primitiveClass);
}
}
wrapperMap.put(String.class, String.class);
}
/**
* <p>Populate the JavaBeans properties of the specified bean, based on
* the specified name/value pairs. This method uses Java reflection APIs
* to identify corresponding "property setter" method names, and deals
* with setter arguments of type <Code>String</Code>, <Code>boolean</Code>,
* <Code>int</Code>, <Code>long</Code>, <Code>float</Code>, and
* <Code>double</Code>.</p>
*
* <p>The particular setter method to be called for each property is
* determined using the usual JavaBeans introspection mechanisms. Thus,
* you may identify custom setter methods using a BeanInfo class that is
* associated with the class of the bean itself. If no such BeanInfo
* class is available, the standard method name conversion ("set" plus
* the capitalized name of the property in question) is used.</p>
*
* <p><strong>NOTE</strong>: It is contrary to the JavaBeans Specification
* to have more than one setter method (with different argument
* signatures) for the same property.</p>
*
* @param clazz JavaBean class whose properties are being populated
* @param properties Map keyed by property name, with the corresponding (String or String[]) value(s) to be set
* @param <T> Class type
* @return Class instance
*/
public static <T> T populate(final Properties properties, final Class<T> clazz) {
T obj = null;
try {
obj = clazz.newInstance();
return populate(properties, obj);
} catch (Throwable e) {
log.warn("Error occurs !", e);
}
return obj;
}
public static <T> T populate(final KeyValue properties, final Class<T> clazz) {
T obj = null;
try {
obj = clazz.newInstance();
return populate(properties, obj);
} catch (Throwable e) {
log.warn("Error occurs !", e);
}
return obj;
}
public static Class<?> getMethodClass(Class<?> clazz, String methodName) {
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (method.getName().equalsIgnoreCase(methodName)) {
return method.getParameterTypes()[0];
}
}
return null;
}
public static void setProperties(Class<?> clazz, Object obj, String methodName,
Object value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<?> parameterClass = getMethodClass(clazz, methodName);
Method setterMethod = clazz.getMethod(methodName, parameterClass);
if (parameterClass == Boolean.TYPE) {
setterMethod.invoke(obj, Boolean.valueOf(value.toString()));
} else if (parameterClass == Integer.TYPE) {
setterMethod.invoke(obj, Integer.valueOf(value.toString()));
} else if (parameterClass == Double.TYPE) {
setterMethod.invoke(obj, Double.valueOf(value.toString()));
} else if (parameterClass == Float.TYPE) {
setterMethod.invoke(obj, Float.valueOf(value.toString()));
} else if (parameterClass == Long.TYPE) {
setterMethod.invoke(obj, Long.valueOf(value.toString()));
} else
setterMethod.invoke(obj, value);
}
public static <T> T populate(final Properties properties, final T obj) {
Class<?> clazz = obj.getClass();
try {
Set<Map.Entry<Object, Object>> entries = properties.entrySet();
for (Map.Entry<Object, Object> entry : entries) {
String entryKey = entry.getKey().toString();
String[] keyGroup = entryKey.split("\\.");
for (int i = 0; i < keyGroup.length; i++) {
keyGroup[i] = keyGroup[i].toLowerCase();
keyGroup[i] = StringUtils.capitalize(keyGroup[i]);
}
String beanFieldNameWithCapitalization = StringUtils.join(keyGroup);
try {
setProperties(clazz, obj, "set" + beanFieldNameWithCapitalization, entry.getValue());
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
//ignored...
}
}
} catch (RuntimeException e) {
log.warn("Error occurs !", e);
}
return obj;
}
public static <T> T populate(final KeyValue properties, final T obj) {
Class<?> clazz = obj.getClass();
try {
final Set<String> keySet = properties.keySet();
for (String key : keySet) {
String[] keyGroup = key.split("\\.");
for (int i = 0; i < keyGroup.length; i++) {
keyGroup[i] = keyGroup[i].toLowerCase();
keyGroup[i] = StringUtils.capitalize(keyGroup[i]);
}
String beanFieldNameWithCapitalization = StringUtils.join(keyGroup);
try {
setProperties(clazz, obj, "set" + beanFieldNameWithCapitalization, properties.getString(key));
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
//ignored...
}
}
} catch (RuntimeException e) {
log.warn("Error occurs !", e);
}
return obj;
}
}
```
|
```package org.apache.rocketmq.remoting.netty;
import java.lang.reflect.Field;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(MockitoJUnitRunner.class)
public class NettyRemotingClientTest {
private NettyRemotingClient remotingClient = new NettyRemotingClient(new NettyClientConfig());
@Test
public void testSetCallbackExecutor() throws NoSuchFieldException, IllegalAccessException {
Field field = NettyRemotingClient.class.getDeclaredField("publicExecutor");
field.setAccessible(true);
assertThat(remotingClient.getCallbackExecutor()).isEqualTo(field.get(remotingClient));
ExecutorService customized = Executors.newCachedThreadPool();
remotingClient.setCallbackExecutor(customized);
assertThat(remotingClient.getCallbackExecutor()).isEqualTo(customized);
}
}```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.remoting.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.apache.rocketmq.remoting.ChannelEventListener;
import org.apache.rocketmq.remoting.InvokeCallback;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.RemotingClient;
import org.apache.rocketmq.remoting.common.Pair;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.common.RemotingUtil;
import org.apache.rocketmq.remoting.exception.RemotingConnectException;
import org.apache.rocketmq.remoting.exception.RemotingSendRequestException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.apache.rocketmq.remoting.exception.RemotingTooMuchRequestException;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.SocketAddress;
import java.security.cert.CertificateException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class NettyRemotingClient extends NettyRemotingAbstract implements RemotingClient {
private static final Logger log = LoggerFactory.getLogger(RemotingHelper.ROCKETMQ_REMOTING);
private static final long LOCK_TIMEOUT_MILLIS = 3000;
private final NettyClientConfig nettyClientConfig;
private final Bootstrap bootstrap = new Bootstrap();
private final EventLoopGroup eventLoopGroupWorker;
private final Lock lockChannelTables = new ReentrantLock();
private final ConcurrentMap<String /* addr */, ChannelWrapper> channelTables = new ConcurrentHashMap<String, ChannelWrapper>();
private final ScheduledExecutorService timer;
private final AtomicReference<List<String>> namesrvAddrList = new AtomicReference<List<String>>();
private final AtomicReference<String> namesrvAddrChoosed = new AtomicReference<String>();
private final AtomicInteger namesrvIndex = new AtomicInteger(initValueIndex());
private final Lock lockNamesrvChannel = new ReentrantLock();
private final ExecutorService publicExecutor;
/**
* Invoke the callback methods in this executor when process response.
*/
private ExecutorService callbackExecutor;
private final ChannelEventListener channelEventListener;
private DefaultEventExecutorGroup defaultEventExecutorGroup;
private RPCHook rpcHook;
private final boolean shareThread;
private Future timerFuture;
public NettyRemotingClient(final NettyClientConfig nettyClientConfig,
final ChannelEventListener channelEventListener) {
this(nettyClientConfig, channelEventListener, false);
}
public NettyRemotingClient(final NettyClientConfig nettyClientConfig) {
this(nettyClientConfig, null);
}
public NettyRemotingClient(final NettyClientConfig nettyClientConfig,
final ChannelEventListener channelEventListener, boolean shareThread) {
super(nettyClientConfig.getClientOnewaySemaphoreValue(), nettyClientConfig.getClientAsyncSemaphoreValue());
this.shareThread = shareThread;
this.nettyClientConfig = nettyClientConfig;
this.channelEventListener = channelEventListener;
int publicThreadNums = nettyClientConfig.getClientCallbackExecutorThreads();
if (publicThreadNums <= 0) {
publicThreadNums = 4;
}
if (shareThread) {
this.publicExecutor = SharedResources.publicExecutor;
this.eventLoopGroupWorker = SharedResources.eventLoopGroup;
timer = SharedResources.timer;
} else {
this.publicExecutor = Executors.newFixedThreadPool(publicThreadNums, new ThreadFactory() {
private AtomicInteger threadIndex = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "NettyClientPublicExecutor_" + this.threadIndex.incrementAndGet());
}
});
this.eventLoopGroupWorker = new NioEventLoopGroup(1, new ThreadFactory() {
private AtomicInteger threadIndex = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, String.format("NettyClientSelector_%d", this.threadIndex.incrementAndGet()));
}
});
timer = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "ClientHouseKeepingService");
t.setDaemon(true);
return t;
}
});
}
if (nettyClientConfig.isUseTLS()) {
try {
sslContext = TlsHelper.buildSslContext(true);
log.info("SSL enabled for client");
} catch (IOException e) {
log.error("Failed to create SSLContext", e);
} catch (CertificateException e) {
log.error("Failed to create SSLContext", e);
throw new RuntimeException("Failed to create SSLContext", e);
}
}
}
private static int initValueIndex() {
Random r = new Random();
return Math.abs(r.nextInt() % 999) % 999;
}
@Override
public void start() {
if (!shareThread) {
this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(
nettyClientConfig.getClientWorkerThreads(),
new ThreadFactory() {
private AtomicInteger threadIndex = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
}
});
}
Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_KEEPALIVE, false)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyClientConfig.getConnectTimeoutMillis())
.option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize())
.option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize())
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
if (nettyClientConfig.isUseTLS()) {
if (null != sslContext) {
pipeline.addFirst(defaultEventExecutorGroup, "sslHandler", sslContext.newHandler(ch.alloc()));
log.info("Prepend SSL handler");
} else {
log.warn("Connections are insecure as SSLContext is null!");
}
}
if (shareThread) {
pipeline.addLast(
new NettyEncoder(),
new NettyDecoder(),
new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()),
new NettyConnectManageHandler(),
new NettyClientHandler());
} else {
pipeline.addLast(
defaultEventExecutorGroup,
new NettyEncoder(),
new NettyDecoder(),
new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()),
new NettyConnectManageHandler(),
new NettyClientHandler());
}
}
});
timerFuture = this.timer.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
NettyRemotingClient.this.scanResponseTable();
} catch (Throwable e) {
log.error("scanResponseTable exception", e);
}
}
}, 1000 * 3, 1000, TimeUnit.MILLISECONDS);
if (this.channelEventListener != null) {
this.nettyEventExecutor.start();
}
}
@Override
public void shutdown() {
try {
if (shareThread) {
timerFuture.cancel(true);
} else {
this.timer.shutdownNow();
this.eventLoopGroupWorker.shutdownGracefully();
if (this.defaultEventExecutorGroup != null) {
this.defaultEventExecutorGroup.shutdownGracefully();
}
if (this.publicExecutor != null) {
try {
this.publicExecutor.shutdown();
} catch (Exception e) {
log.error("NettyRemotingServer shutdown exception, ", e);
}
}
}
for (ChannelWrapper cw : this.channelTables.values()) {
this.closeChannel(null, cw.getChannel());
}
this.channelTables.clear();
if (this.nettyEventExecutor != null) {
this.nettyEventExecutor.shutdown();
}
} catch (Exception e) {
log.error("NettyRemotingClient shutdown exception, ", e);
}
}
public void closeChannel(final String addr, final Channel channel) {
if (null == channel)
return;
final String addrRemote = null == addr ? RemotingHelper.parseChannelRemoteAddr(channel) : addr;
try {
if (this.lockChannelTables.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
try {
boolean removeItemFromTable = true;
final ChannelWrapper prevCW = this.channelTables.get(addrRemote);
log.info("closeChannel: begin close the channel[{}] Found: {}", addrRemote, prevCW != null);
if (null == prevCW) {
log.info("closeChannel: the channel[{}] has been removed from the channel table before", addrRemote);
removeItemFromTable = false;
} else if (prevCW.getChannel() != channel) {
log.info("closeChannel: the channel[{}] has been closed before, and has been created again, nothing to do.",
addrRemote);
removeItemFromTable = false;
}
if (removeItemFromTable) {
this.channelTables.remove(addrRemote);
log.info("closeChannel: the channel[{}] was removed from channel table", addrRemote);
}
RemotingUtil.closeChannel(channel);
} catch (Exception e) {
log.error("closeChannel: close the channel exception", e);
} finally {
this.lockChannelTables.unlock();
}
} else {
log.warn("closeChannel: try to lock channel table, but timeout, {}ms", LOCK_TIMEOUT_MILLIS);
}
} catch (InterruptedException e) {
log.error("closeChannel exception", e);
}
}
@Override
public void registerRPCHook(RPCHook rpcHook) {
this.rpcHook = rpcHook;
}
public void closeChannel(final Channel channel) {
if (null == channel)
return;
try {
if (this.lockChannelTables.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
try {
boolean removeItemFromTable = true;
ChannelWrapper prevCW = null;
String addrRemote = null;
for (Map.Entry<String, ChannelWrapper> entry : channelTables.entrySet()) {
String key = entry.getKey();
ChannelWrapper prev = entry.getValue();
if (prev.getChannel() != null) {
if (prev.getChannel() == channel) {
prevCW = prev;
addrRemote = key;
break;
}
}
}
if (null == prevCW) {
log.info("eventCloseChannel: the channel[{}] has been removed from the channel table before", addrRemote);
removeItemFromTable = false;
}
if (removeItemFromTable) {
this.channelTables.remove(addrRemote);
log.info("closeChannel: the channel[{}] was removed from channel table", addrRemote);
RemotingUtil.closeChannel(channel);
}
} catch (Exception e) {
log.error("closeChannel: close the channel exception", e);
} finally {
this.lockChannelTables.unlock();
}
} else {
log.warn("closeChannel: try to lock channel table, but timeout, {}ms", LOCK_TIMEOUT_MILLIS);
}
} catch (InterruptedException e) {
log.error("closeChannel exception", e);
}
}
@Override
public void updateNameServerAddressList(List<String> addrs) {
List<String> old = this.namesrvAddrList.get();
boolean update = false;
if (!addrs.isEmpty()) {
if (null == old) {
update = true;
} else if (addrs.size() != old.size()) {
update = true;
} else {
for (int i = 0; i < addrs.size() && !update; i++) {
if (!old.contains(addrs.get(i))) {
update = true;
}
}
}
if (update) {
Collections.shuffle(addrs);
log.info("name server address updated. NEW : {} , OLD: {}", addrs, old);
this.namesrvAddrList.set(addrs);
}
}
}
@Override
public RemotingCommand invokeSync(String addr, final RemotingCommand request, long timeoutMillis)
throws InterruptedException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException {
final Channel channel = this.getAndCreateChannel(addr);
if (channel != null && channel.isActive()) {
try {
if (this.rpcHook != null) {
this.rpcHook.doBeforeRequest(addr, request);
}
RemotingCommand response = this.invokeSyncImpl(channel, request, timeoutMillis);
if (this.rpcHook != null) {
this.rpcHook.doAfterResponse(RemotingHelper.parseChannelRemoteAddr(channel), request, response);
}
return response;
} catch (RemotingSendRequestException e) {
log.warn("invokeSync: send request exception, so close the channel[{}]", addr);
this.closeChannel(addr, channel);
throw e;
} catch (RemotingTimeoutException e) {
if (nettyClientConfig.isClientCloseSocketIfTimeout()) {
this.closeChannel(addr, channel);
log.warn("invokeSync: close socket because of timeout, {}ms, {}", timeoutMillis, addr);
}
log.warn("invokeSync: wait response timeout exception, the channel[{}]", addr);
throw e;
}
} else {
this.closeChannel(addr, channel);
throw new RemotingConnectException(addr);
}
}
private Channel getAndCreateChannel(final String addr) throws InterruptedException {
if (null == addr)
return getAndCreateNameserverChannel();
ChannelWrapper cw = this.channelTables.get(addr);
if (cw != null && cw.isOK()) {
return cw.getChannel();
}
return this.createChannel(addr);
}
private Channel getAndCreateNameserverChannel() throws InterruptedException {
String addr = this.namesrvAddrChoosed.get();
if (addr != null) {
ChannelWrapper cw = this.channelTables.get(addr);
if (cw != null && cw.isOK()) {
return cw.getChannel();
}
}
final List<String> addrList = this.namesrvAddrList.get();
if (this.lockNamesrvChannel.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
try {
addr = this.namesrvAddrChoosed.get();
if (addr != null) {
ChannelWrapper cw = this.channelTables.get(addr);
if (cw != null && cw.isOK()) {
return cw.getChannel();
}
}
if (addrList != null && !addrList.isEmpty()) {
for (int i = 0; i < addrList.size(); i++) {
int index = this.namesrvIndex.incrementAndGet();
index = Math.abs(index);
index = index % addrList.size();
String newAddr = addrList.get(index);
this.namesrvAddrChoosed.set(newAddr);
log.info("new name server is chosen. OLD: {} , NEW: {}. namesrvIndex = {}", addr, newAddr, namesrvIndex);
Channel channelNew = this.createChannel(newAddr);
if (channelNew != null)
return channelNew;
}
}
} catch (Exception e) {
log.error("getAndCreateNameserverChannel: create name server channel exception", e);
} finally {
this.lockNamesrvChannel.unlock();
}
} else {
log.warn("getAndCreateNameserverChannel: try to lock name server, but timeout, {}ms", LOCK_TIMEOUT_MILLIS);
}
return null;
}
private Channel createChannel(final String addr) throws InterruptedException {
ChannelWrapper cw = this.channelTables.get(addr);
if (cw != null && cw.isOK()) {
cw.getChannel().close();
channelTables.remove(addr);
}
if (this.lockChannelTables.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
try {
boolean createNewConnection;
cw = this.channelTables.get(addr);
if (cw != null) {
if (cw.isOK()) {
cw.getChannel().close();
this.channelTables.remove(addr);
createNewConnection = true;
} else if (!cw.getChannelFuture().isDone()) {
createNewConnection = false;
} else {
this.channelTables.remove(addr);
createNewConnection = true;
}
} else {
createNewConnection = true;
}
if (createNewConnection) {
ChannelFuture channelFuture = this.bootstrap.connect(RemotingHelper.string2SocketAddress(addr));
log.info("createChannel: begin to connect remote host[{}] asynchronously", addr);
cw = new ChannelWrapper(channelFuture);
this.channelTables.put(addr, cw);
}
} catch (Exception e) {
log.error("createChannel: create channel exception", e);
} finally {
this.lockChannelTables.unlock();
}
} else {
log.warn("createChannel: try to lock channel table, but timeout, {}ms", LOCK_TIMEOUT_MILLIS);
}
if (cw != null) {
ChannelFuture channelFuture = cw.getChannelFuture();
if (channelFuture.awaitUninterruptibly(this.nettyClientConfig.getConnectTimeoutMillis())) {
if (cw.isOK()) {
log.info("createChannel: connect remote host[{}] success, {}", addr, channelFuture.toString());
return cw.getChannel();
} else {
log.warn("createChannel: connect remote host[" + addr + "] failed, " + channelFuture.toString(), channelFuture.cause());
}
} else {
log.warn("createChannel: connect remote host[{}] timeout {}ms, {}", addr, this.nettyClientConfig.getConnectTimeoutMillis(),
channelFuture.toString());
}
}
return null;
}
@Override
public void invokeAsync(String addr, RemotingCommand request, long timeoutMillis, InvokeCallback invokeCallback)
throws InterruptedException, RemotingConnectException, RemotingTooMuchRequestException, RemotingTimeoutException,
RemotingSendRequestException {
final Channel channel = this.getAndCreateChannel(addr);
if (channel != null && channel.isActive()) {
try {
if (this.rpcHook != null) {
this.rpcHook.doBeforeRequest(addr, request);
}
this.invokeAsyncImpl(channel, request, timeoutMillis, invokeCallback);
} catch (RemotingSendRequestException e) {
log.warn("invokeAsync: send request exception, so close the channel[{}]", addr);
this.closeChannel(addr, channel);
throw e;
}
} else {
this.closeChannel(addr, channel);
throw new RemotingConnectException(addr);
}
}
@Override
public void invokeOneway(String addr, RemotingCommand request, long timeoutMillis) throws InterruptedException,
RemotingConnectException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException {
final Channel channel = this.getAndCreateChannel(addr);
if (channel != null && channel.isActive()) {
try {
if (this.rpcHook != null) {
this.rpcHook.doBeforeRequest(addr, request);
}
this.invokeOnewayImpl(channel, request, timeoutMillis);
} catch (RemotingSendRequestException e) {
log.warn("invokeOneway: send request exception, so close the channel[{}]", addr);
this.closeChannel(addr, channel);
throw e;
}
} else {
this.closeChannel(addr, channel);
throw new RemotingConnectException(addr);
}
}
@Override
public void registerProcessor(int requestCode, NettyRequestProcessor processor, ExecutorService executor) {
ExecutorService executorThis = executor;
if (null == executor) {
executorThis = this.publicExecutor;
}
Pair<NettyRequestProcessor, ExecutorService> pair = new Pair<NettyRequestProcessor, ExecutorService>(processor, executorThis);
this.processorTable.put(requestCode, pair);
}
@Override
public boolean isChannelWritable(String addr) {
ChannelWrapper cw = this.channelTables.get(addr);
if (cw != null && cw.isOK()) {
return cw.isWritable();
}
return true;
}
@Override
public List<String> getNameServerAddressList() {
return this.namesrvAddrList.get();
}
@Override
public ChannelEventListener getChannelEventListener() {
return channelEventListener;
}
@Override
public RPCHook getRPCHook() {
return this.rpcHook;
}
@Override
public ExecutorService getCallbackExecutor() {
return callbackExecutor != null ? callbackExecutor : publicExecutor;
}
@Override
public void setCallbackExecutor(final ExecutorService callbackExecutor) {
this.callbackExecutor = callbackExecutor;
}
static class ChannelWrapper {
private final ChannelFuture channelFuture;
public ChannelWrapper(ChannelFuture channelFuture) {
this.channelFuture = channelFuture;
}
public boolean isOK() {
return this.channelFuture.channel() != null && this.channelFuture.channel().isActive();
}
public boolean isWritable() {
return this.channelFuture.channel().isWritable();
}
private Channel getChannel() {
return this.channelFuture.channel();
}
public ChannelFuture getChannelFuture() {
return channelFuture;
}
}
class NettyClientHandler extends SimpleChannelInboundHandler<RemotingCommand> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, RemotingCommand msg) throws Exception {
processMessageReceived(ctx, msg);
}
}
class NettyConnectManageHandler extends ChannelDuplexHandler {
@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
ChannelPromise promise) throws Exception {
final String local = localAddress == null ? "UNKNOWN" : RemotingHelper.parseSocketAddressAddr(localAddress);
final String remote = remoteAddress == null ? "UNKNOWN" : RemotingHelper.parseSocketAddressAddr(remoteAddress);
log.info("NETTY CLIENT PIPELINE: CONNECT {} => {}", local, remote);
super.connect(ctx, remoteAddress, localAddress, promise);
if (NettyRemotingClient.this.channelEventListener != null) {
NettyRemotingClient.this.putNettyEvent(new NettyEvent(NettyEventType.CONNECT, remote, ctx.channel()));
}
}
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
log.info("NETTY CLIENT PIPELINE: DISCONNECT {}", remoteAddress);
closeChannel(ctx.channel());
super.disconnect(ctx, promise);
if (NettyRemotingClient.this.channelEventListener != null) {
NettyRemotingClient.this.putNettyEvent(new NettyEvent(NettyEventType.CLOSE, remoteAddress, ctx.channel()));
}
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
log.info("NETTY CLIENT PIPELINE: CLOSE {}", remoteAddress);
closeChannel(ctx.channel());
super.close(ctx, promise);
if (NettyRemotingClient.this.channelEventListener != null) {
NettyRemotingClient.this.putNettyEvent(new NettyEvent(NettyEventType.CLOSE, remoteAddress, ctx.channel()));
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state().equals(IdleState.ALL_IDLE)) {
final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
log.warn("NETTY CLIENT PIPELINE: IDLE exception [{}]", remoteAddress);
closeChannel(ctx.channel());
if (NettyRemotingClient.this.channelEventListener != null) {
NettyRemotingClient.this
.putNettyEvent(new NettyEvent(NettyEventType.IDLE, remoteAddress, ctx.channel()));
}
}
}
ctx.fireUserEventTriggered(evt);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
log.warn("NETTY CLIENT PIPELINE: exceptionCaught {}", remoteAddress);
log.warn("NETTY CLIENT PIPELINE: exceptionCaught exception.", cause);
closeChannel(ctx.channel());
if (NettyRemotingClient.this.channelEventListener != null) {
NettyRemotingClient.this.putNettyEvent(new NettyEvent(NettyEventType.EXCEPTION, remoteAddress, ctx.channel()));
}
}
}
public static class SharedResources {
//select read write.
private static EventLoopGroup eventLoopGroup = new NioEventLoopGroup(Math.max(1, Math.max(1, Runtime.getRuntime().availableProcessors() / 3)), new ThreadFactory() {
private AtomicInteger threadIndex = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, String.format("Shared_NettyClientSelector_%d", this.threadIndex.incrementAndGet()));
}
});
private static ScheduledExecutorService timer = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "Shared_ClientHouseKeepingService");
t.setDaemon(true);
return t;
}
});
private static ExecutorService publicExecutor = Executors.newFixedThreadPool(Math.max(1, Runtime.getRuntime().availableProcessors() / 3), new ThreadFactory() {
private AtomicInteger threadIndex = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "Shared_NettyClientPublicExecutor_" + this.threadIndex.incrementAndGet());
}
});
public static void shutdown() {
eventLoopGroup.shutdownGracefully();
timer.shutdownNow();
publicExecutor.shutdownNow();
}
}
}
```
|
```package org.apache.rocketmq.common;
import org.apache.rocketmq.remoting.common.RemotingUtil;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class RemotingUtilTest {
@Test
public void testGetLocalAddress() throws Exception {
String localAddress = RemotingUtil.getLocalAddress();
assertThat(localAddress).isNotNull();
assertThat(localAddress.length()).isGreaterThan(0);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.remoting.common;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.ArrayList;
import java.util.Enumeration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RemotingUtil {
public static final String OS_NAME = System.getProperty("os.name");
private static final Logger log = LoggerFactory.getLogger(RemotingHelper.ROCKETMQ_REMOTING);
private static boolean isLinuxPlatform = false;
private static boolean isWindowsPlatform = false;
static {
if (OS_NAME != null && OS_NAME.toLowerCase().contains("linux")) {
isLinuxPlatform = true;
}
if (OS_NAME != null && OS_NAME.toLowerCase().contains("windows")) {
isWindowsPlatform = true;
}
}
public static boolean isWindowsPlatform() {
return isWindowsPlatform;
}
public static Selector openSelector() throws IOException {
Selector result = null;
if (isLinuxPlatform()) {
try {
final Class<?> providerClazz = Class.forName("sun.nio.ch.EPollSelectorProvider");
if (providerClazz != null) {
try {
final Method method = providerClazz.getMethod("provider");
if (method != null) {
final SelectorProvider selectorProvider = (SelectorProvider) method.invoke(null);
if (selectorProvider != null) {
result = selectorProvider.openSelector();
}
}
} catch (final Exception e) {
log.warn("Open ePoll Selector for linux platform exception", e);
}
}
} catch (final Exception e) {
// ignore
}
}
if (result == null) {
result = Selector.open();
}
return result;
}
public static boolean isLinuxPlatform() {
return isLinuxPlatform;
}
public static String getLocalAddress() {
try {
// Traversal Network interface to get the first non-loopback and non-private address
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
ArrayList<String> ipv4Result = new ArrayList<String>();
ArrayList<String> ipv6Result = new ArrayList<String>();
while (enumeration.hasMoreElements()) {
final NetworkInterface networkInterface = enumeration.nextElement();
final Enumeration<InetAddress> en = networkInterface.getInetAddresses();
while (en.hasMoreElements()) {
final InetAddress address = en.nextElement();
if (!address.isLoopbackAddress()) {
if (address instanceof Inet6Address) {
ipv6Result.add(normalizeHostAddress(address));
} else {
ipv4Result.add(normalizeHostAddress(address));
}
}
}
}
// prefer ipv4
if (!ipv4Result.isEmpty()) {
for (String ip : ipv4Result) {
if (ip.startsWith("127.0") || ip.startsWith("192.168")) {
continue;
}
return ip;
}
return ipv4Result.get(ipv4Result.size() - 1);
} else if (!ipv6Result.isEmpty()) {
return ipv6Result.get(0);
}
//If failed to find,fall back to localhost
final InetAddress localHost = InetAddress.getLocalHost();
return normalizeHostAddress(localHost);
} catch (Exception e) {
log.error("Failed to obtain local address", e);
}
return null;
}
public static String normalizeHostAddress(final InetAddress localHost) {
if (localHost instanceof Inet6Address) {
return "[" + localHost.getHostAddress() + "]";
} else {
return localHost.getHostAddress();
}
}
public static SocketAddress string2SocketAddress(final String addr) {
String[] s = addr.split(":");
InetSocketAddress isa = new InetSocketAddress(s[0], Integer.parseInt(s[1]));
return isa;
}
public static String socketAddress2String(final SocketAddress addr) {
StringBuilder sb = new StringBuilder();
InetSocketAddress inetSocketAddress = (InetSocketAddress) addr;
sb.append(inetSocketAddress.getAddress().getHostAddress());
sb.append(":");
sb.append(inetSocketAddress.getPort());
return sb.toString();
}
public static SocketChannel connect(SocketAddress remote) {
return connect(remote, 1000 * 5);
}
public static SocketChannel connect(SocketAddress remote, final int timeoutMillis) {
SocketChannel sc = null;
try {
sc = SocketChannel.open();
sc.configureBlocking(true);
sc.socket().setSoLinger(false, -1);
sc.socket().setTcpNoDelay(true);
sc.socket().setReceiveBufferSize(1024 * 64);
sc.socket().setSendBufferSize(1024 * 64);
sc.socket().connect(remote, timeoutMillis);
sc.configureBlocking(false);
return sc;
} catch (Exception e) {
if (sc != null) {
try {
sc.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return null;
}
public static void closeChannel(Channel channel) {
final String addrRemote = RemotingHelper.parseChannelRemoteAddr(channel);
channel.close().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
log.info("closeChannel: close the connection to remote address[{}] result: {}", addrRemote,
future.isSuccess());
}
});
}
}
```
|
```package org.apache.rocketmq.tools.command.offset;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.impl.MQClientAPIImpl;
import org.apache.rocketmq.client.impl.MQClientManager;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExtImpl;
import org.apache.rocketmq.tools.command.SubCommandException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class GetConsumerStatusCommandTest {
private static DefaultMQAdminExt defaultMQAdminExt;
private static DefaultMQAdminExtImpl defaultMQAdminExtImpl;
private static MQClientInstance mqClientInstance = MQClientManager.getInstance().getAndCreateMQClientInstance(new ClientConfig());
private static MQClientAPIImpl mQClientAPIImpl;
@BeforeClass
public static void init() throws NoSuchFieldException, IllegalAccessException, InterruptedException, RemotingException, MQClientException, MQBrokerException {
mQClientAPIImpl = mock(MQClientAPIImpl.class);
defaultMQAdminExt = new DefaultMQAdminExt();
defaultMQAdminExtImpl = new DefaultMQAdminExtImpl(defaultMQAdminExt, 1000);
Field field = DefaultMQAdminExtImpl.class.getDeclaredField("mqClientInstance");
field.setAccessible(true);
field.set(defaultMQAdminExtImpl, mqClientInstance);
field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
field.setAccessible(true);
field.set(mqClientInstance, mQClientAPIImpl);
field = DefaultMQAdminExt.class.getDeclaredField("defaultMQAdminExtImpl");
field.setAccessible(true);
field.set(defaultMQAdminExt, defaultMQAdminExtImpl);
Map<String, Map<MessageQueue, Long>> consumerStatus = new HashMap<>();
when(mQClientAPIImpl.invokeBrokerToGetConsumerStatus(anyString(), anyString(), anyString(), anyString(), anyLong())).thenReturn(consumerStatus);
}
@AfterClass
public static void terminate() {
defaultMQAdminExt.shutdown();
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
GetConsumerStatusCommand cmd = new GetConsumerStatusCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-g default-group", "-t unit-test", "-i clientid"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.tools.command.offset;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.command.SubCommand;
import org.apache.rocketmq.tools.command.SubCommandException;
public class GetConsumerStatusCommand implements SubCommand {
@Override
public String commandName() {
return "getConsumerStatus";
}
@Override
public String commandDesc() {
return "get consumer status from client.";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("g", "group", true, "set the consumer group");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("t", "topic", true, "set the topic");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("i", "originClientId", true, "set the consumer clientId");
opt.setRequired(false);
options.addOption(opt);
return options;
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
String group = commandLine.getOptionValue("g").trim();
String topic = commandLine.getOptionValue("t").trim();
String originClientId = "";
if (commandLine.hasOption("i")) {
originClientId = commandLine.getOptionValue("i").trim();
}
defaultMQAdminExt.start();
Map<String, Map<MessageQueue, Long>> consumerStatusTable =
defaultMQAdminExt.getConsumeStatus(topic, group, originClientId);
System.out.printf("get consumer status from client. group=%s, topic=%s, originClientId=%s%n",
group, topic, originClientId);
System.out.printf("%-50s %-15s %-15s %-20s%n",
"#clientId",
"#brokerName",
"#queueId",
"#offset");
for (Map.Entry<String, Map<MessageQueue, Long>> entry : consumerStatusTable.entrySet()) {
String clientId = entry.getKey();
Map<MessageQueue, Long> mqTable = entry.getValue();
for (Map.Entry<MessageQueue, Long> entry1 : mqTable.entrySet()) {
MessageQueue mq = entry1.getKey();
System.out.printf("%-50s %-15s %-15d %-20d%n",
UtilAll.frontStringAtLeast(clientId, 50),
mq.getBrokerName(),
mq.getQueueId(),
mqTable.get(mq));
}
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
}
```
|
```package org.apache.rocketmq.common;
import java.util.ArrayList;
import java.util.List;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageBatch;
import org.junit.Test;
public class MessageBatchTest {
public List<Message> generateMessages() {
List<Message> messages = new ArrayList<Message>();
Message message1 = new Message("topic1", "body".getBytes());
Message message2 = new Message("topic1", "body".getBytes());
messages.add(message1);
messages.add(message2);
return messages;
}
@Test
public void testGenerate_OK() throws Exception {
List<Message> messages = generateMessages();
MessageBatch.generateFromList(messages);
}
@Test(expected = UnsupportedOperationException.class)
public void testGenerate_DiffTopic() throws Exception {
List<Message> messages = generateMessages();
messages.get(1).setTopic("topic2");
MessageBatch.generateFromList(messages);
}
@Test(expected = UnsupportedOperationException.class)
public void testGenerate_DiffWaitOK() throws Exception {
List<Message> messages = generateMessages();
messages.get(1).setWaitStoreMsgOK(false);
MessageBatch.generateFromList(messages);
}
@Test(expected = UnsupportedOperationException.class)
public void testGenerate_Delay() throws Exception {
List<Message> messages = generateMessages();
messages.get(1).setDelayTimeLevel(1);
MessageBatch.generateFromList(messages);
}
@Test(expected = UnsupportedOperationException.class)
public void testGenerate_Retry() throws Exception {
List<Message> messages = generateMessages();
messages.get(1).setTopic(MixAll.RETRY_GROUP_TOPIC_PREFIX + "topic");
MessageBatch.generateFromList(messages);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.common.message;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.rocketmq.common.MixAll;
public class MessageBatch extends Message implements Iterable<Message> {
private static final long serialVersionUID = 621335151046335557L;
private final List<Message> messages;
private boolean multiTopic = false;
private List<String> topics;
public MessageBatch() {
messages = null;
}
private MessageBatch(List<Message> messages) {
this.messages = messages;
}
public byte[] encode() {
return MessageDecoder.encodeMessages(messages);
}
public Iterator<Message> iterator() {
if (messages == null) {
List<Message> msgs = Collections.emptyList();
return msgs.iterator();
}
return messages.iterator();
}
public static MessageBatch generateFromList(Collection<Message> messages) {
assert messages != null;
assert messages.size() > 0;
List<Message> messageList = new ArrayList<Message>(messages.size());
Message first = null;
for (Message message : messages) {
if (message.getDelayTimeLevel() > 0) {
throw new UnsupportedOperationException("TimeDelayLevel in not supported for batching");
}
if (message.getTopic().startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
throw new UnsupportedOperationException("Retry Group is not supported for batching");
}
if (first == null) {
first = message;
} else {
if (!first.getTopic().equals(message.getTopic())) {
throw new UnsupportedOperationException("The topic of the messages in one batch should be the same");
}
if (first.isWaitStoreMsgOK() != message.isWaitStoreMsgOK()) {
throw new UnsupportedOperationException("The waitStoreMsgOK of the messages in one batch should the same");
}
}
messageList.add(message);
}
MessageBatch messageBatch = new MessageBatch(messageList);
messageBatch.setTopic(first.getTopic());
messageBatch.setWaitStoreMsgOK(first.isWaitStoreMsgOK());
return messageBatch;
}
public boolean isMultiTopic() {
return multiTopic;
}
public void setMultiTopic(boolean multiTopic) {
this.multiTopic = multiTopic;
}
}
```
|
```package org.apache.rocketmq.test.clientinterface;
public interface MQConsumer {
void create();
void create(boolean useTLS);
void start();
void shutdown();
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.client.impl.consumer;
import java.util.Set;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.common.protocol.body.ConsumerRunningInfo;
import org.apache.rocketmq.common.protocol.heartbeat.ConsumeType;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData;
/**
* Consumer inner interface
*/
public interface MQConsumerInner {
String groupName();
MessageModel messageModel();
ConsumeType consumeType();
ConsumeFromWhere consumeFromWhere();
Set<SubscriptionData> subscriptions();
void doRebalance();
void persistConsumerOffset();
void updateTopicSubscribeInfo(final String topic, final Set<MessageQueue> info);
boolean isSubscribeTopicNeedUpdate(final String topic);
boolean isUnitMode();
ConsumerRunningInfo consumerRunningInfo();
}
```
|
```package org.apache.rocketmq.namesrv.kvconfig;
import java.util.HashMap;
import org.apache.rocketmq.common.namesrv.NamesrvUtil;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class KVConfigSerializeWrapperTest {
private KVConfigSerializeWrapper kvConfigSerializeWrapper;
@Before
public void setup() throws Exception {
kvConfigSerializeWrapper = new KVConfigSerializeWrapper();
}
@Test
public void testEncodeAndDecode() {
HashMap<String, HashMap<String, String>> result = new HashMap<>();
HashMap<String, String> kvs = new HashMap<>();
kvs.put("broker-name", "default-broker");
kvs.put("topic-name", "default-topic");
kvs.put("cid", "default-consumer-name");
result.put(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, kvs);
kvConfigSerializeWrapper.setConfigTable(result);
byte[] serializeByte = KVConfigSerializeWrapper.encode(kvConfigSerializeWrapper);
assertThat(serializeByte).isNotNull();
KVConfigSerializeWrapper deserializeObject = KVConfigSerializeWrapper.decode(serializeByte, KVConfigSerializeWrapper.class);
assertThat(deserializeObject.getConfigTable()).containsKey(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG);
assertThat(deserializeObject.getConfigTable().get(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG).get("broker-name")).isEqualTo("default-broker");
assertThat(deserializeObject.getConfigTable().get(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG).get("topic-name")).isEqualTo("default-topic");
assertThat(deserializeObject.getConfigTable().get(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG).get("cid")).isEqualTo("default-consumer-name");
}
}```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.namesrv.kvconfig;
import java.util.HashMap;
import org.apache.rocketmq.remoting.protocol.RemotingSerializable;
public class KVConfigSerializeWrapper extends RemotingSerializable {
private HashMap<String/* Namespace */, HashMap<String/* Key */, String/* Value */>> configTable;
public HashMap<String, HashMap<String, String>> getConfigTable() {
return configTable;
}
public void setConfigTable(HashMap<String, HashMap<String, String>> configTable) {
this.configTable = configTable;
}
}
```
|
```package org.apache.rocketmq.tools.command.topic;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class UpdateTopicSubCommandTest {
@Test
public void testExecute() {
UpdateTopicSubCommand cmd = new UpdateTopicSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {
"-b 127.0.0.1:10911",
"-c default-cluster",
"-t unit-test",
"-r 8",
"-w 8",
"-p 6",
"-o false",
"-u false",
"-s false"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
assertThat(commandLine.getOptionValue('b').trim()).isEqualTo("127.0.0.1:10911");
assertThat(commandLine.getOptionValue('c').trim()).isEqualTo("default-cluster");
assertThat(commandLine.getOptionValue('r').trim()).isEqualTo("8");
assertThat(commandLine.getOptionValue('w').trim()).isEqualTo("8");
assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test");
assertThat(commandLine.getOptionValue('p').trim()).isEqualTo("6");
assertThat(commandLine.getOptionValue('o').trim()).isEqualTo("false");
assertThat(commandLine.getOptionValue('u').trim()).isEqualTo("false");
assertThat(commandLine.getOptionValue('s').trim()).isEqualTo("false");
}
}```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.tools.command.topic;
import java.util.Set;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.rocketmq.common.TopicConfig;
import org.apache.rocketmq.common.sysflag.TopicSysFlag;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.command.CommandUtil;
import org.apache.rocketmq.tools.command.SubCommand;
import org.apache.rocketmq.tools.command.SubCommandException;
public class UpdateTopicSubCommand implements SubCommand {
@Override
public String commandName() {
return "updateTopic";
}
@Override
public String commandDesc() {
return "Update or create topic";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("b", "brokerAddr", true, "create topic to which broker");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("c", "clusterName", true, "create topic to which cluster");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("t", "topic", true, "topic name");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("r", "readQueueNums", true, "set read queue nums");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("w", "writeQueueNums", true, "set write queue nums");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("p", "perm", true, "set topic's permission(2|4|6), intro[2:W 4:R; 6:RW]");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("o", "order", true, "set topic's order(true|false");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("u", "unit", true, "is unit topic (true|false");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("s", "hasUnitSub", true, "has unit sub (true|false");
opt.setRequired(false);
options.addOption(opt);
return options;
}
@Override
public void execute(final CommandLine commandLine, final Options options,
RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
TopicConfig topicConfig = new TopicConfig();
topicConfig.setReadQueueNums(8);
topicConfig.setWriteQueueNums(8);
topicConfig.setTopicName(commandLine.getOptionValue('t').trim());
// readQueueNums
if (commandLine.hasOption('r')) {
topicConfig.setReadQueueNums(Integer.parseInt(commandLine.getOptionValue('r').trim()));
}
// writeQueueNums
if (commandLine.hasOption('w')) {
topicConfig.setWriteQueueNums(Integer.parseInt(commandLine.getOptionValue('w').trim()));
}
// perm
if (commandLine.hasOption('p')) {
topicConfig.setPerm(Integer.parseInt(commandLine.getOptionValue('p').trim()));
}
boolean isUnit = false;
if (commandLine.hasOption('u')) {
isUnit = Boolean.parseBoolean(commandLine.getOptionValue('u').trim());
}
boolean isCenterSync = false;
if (commandLine.hasOption('s')) {
isCenterSync = Boolean.parseBoolean(commandLine.getOptionValue('s').trim());
}
int topicCenterSync = TopicSysFlag.buildSysFlag(isUnit, isCenterSync);
topicConfig.setTopicSysFlag(topicCenterSync);
boolean isOrder = false;
if (commandLine.hasOption('o')) {
isOrder = Boolean.parseBoolean(commandLine.getOptionValue('o').trim());
}
topicConfig.setOrder(isOrder);
if (commandLine.hasOption('b')) {
String addr = commandLine.getOptionValue('b').trim();
defaultMQAdminExt.start();
defaultMQAdminExt.createAndUpdateTopicConfig(addr, topicConfig);
if (isOrder) {
String brokerName = CommandUtil.fetchBrokerNameByAddr(defaultMQAdminExt, addr);
String orderConf = brokerName + ":" + topicConfig.getWriteQueueNums();
defaultMQAdminExt.createOrUpdateOrderConf(topicConfig.getTopicName(), orderConf, false);
System.out.printf(String.format("set broker orderConf. isOrder=%s, orderConf=[%s]",
isOrder, orderConf.toString()));
}
System.out.printf("create topic to %s success.%n", addr);
System.out.printf("%s", topicConfig);
return;
} else if (commandLine.hasOption('c')) {
String clusterName = commandLine.getOptionValue('c').trim();
defaultMQAdminExt.start();
Set<String> masterSet =
CommandUtil.fetchMasterAddrByClusterName(defaultMQAdminExt, clusterName);
for (String addr : masterSet) {
defaultMQAdminExt.createAndUpdateTopicConfig(addr, topicConfig);
System.out.printf("create topic to %s success.%n", addr);
}
if (isOrder) {
Set<String> brokerNameSet =
CommandUtil.fetchBrokerNameByClusterName(defaultMQAdminExt, clusterName);
StringBuilder orderConf = new StringBuilder();
String splitor = "";
for (String s : brokerNameSet) {
orderConf.append(splitor).append(s).append(":")
.append(topicConfig.getWriteQueueNums());
splitor = ";";
}
defaultMQAdminExt.createOrUpdateOrderConf(topicConfig.getTopicName(),
orderConf.toString(), true);
System.out.printf("set cluster orderConf. isOrder=%s, orderConf=[%s]", isOrder, orderConf);
}
System.out.printf("%s", topicConfig);
return;
}
ServerUtil.printCommandLineHelp("mqadmin " + this.commandName(), options);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
}
```
|
```package org.apache.rocketmq.client.impl.consumer;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.rebalance.AllocateMessageQueueAveragely;
import org.apache.rocketmq.client.consumer.store.OffsetStore;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class RebalancePushImplTest {
@Spy
private DefaultMQPushConsumerImpl defaultMQPushConsumer = new DefaultMQPushConsumerImpl(new DefaultMQPushConsumer("RebalancePushImplTest"), null);
@Mock
private MQClientInstance mqClientInstance;
@Mock
private OffsetStore offsetStore;
private String consumerGroup = "CID_RebalancePushImplTest";
private String topic = "TopicA";
@Test
public void testMessageQueueChanged_CountThreshold() {
RebalancePushImpl rebalancePush = new RebalancePushImpl(consumerGroup, MessageModel.CLUSTERING,
new AllocateMessageQueueAveragely(), mqClientInstance, defaultMQPushConsumer);
init(rebalancePush);
// Just set pullThresholdForQueue
defaultMQPushConsumer.getDefaultMQPushConsumer().setPullThresholdForQueue(1024);
Set<MessageQueue> allocateResultSet = new HashSet<MessageQueue>();
allocateResultSet.add(new MessageQueue(topic, "BrokerA", 0));
allocateResultSet.add(new MessageQueue(topic, "BrokerA", 1));
doRebalanceForcibly(rebalancePush, allocateResultSet);
assertThat(defaultMQPushConsumer.getDefaultMQPushConsumer().getPullThresholdForQueue()).isEqualTo(1024);
// Set pullThresholdForTopic
defaultMQPushConsumer.getDefaultMQPushConsumer().setPullThresholdForTopic(1024);
doRebalanceForcibly(rebalancePush, allocateResultSet);
assertThat(defaultMQPushConsumer.getDefaultMQPushConsumer().getPullThresholdForQueue()).isEqualTo(512);
// Change message queue allocate result
allocateResultSet.add(new MessageQueue(topic, "BrokerA", 2));
doRebalanceForcibly(rebalancePush, allocateResultSet);
assertThat(defaultMQPushConsumer.getDefaultMQPushConsumer().getPullThresholdForQueue()).isEqualTo(341);
}
private void doRebalanceForcibly(RebalancePushImpl rebalancePush, Set<MessageQueue> allocateResultSet) {
rebalancePush.topicSubscribeInfoTable.put(topic, allocateResultSet);
rebalancePush.doRebalance(false);
rebalancePush.messageQueueChanged(topic, allocateResultSet, allocateResultSet);
}
private void init(final RebalancePushImpl rebalancePush) {
rebalancePush.getSubscriptionInner().putIfAbsent(topic, new SubscriptionData());
rebalancePush.subscriptionInner.putIfAbsent(topic, new SubscriptionData());
when(mqClientInstance.findConsumerIdList(anyString(), anyString())).thenReturn(Collections.singletonList(consumerGroup));
when(mqClientInstance.getClientId()).thenReturn(consumerGroup);
when(defaultMQPushConsumer.getOffsetStore()).thenReturn(offsetStore);
doAnswer(new Answer() {
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
return null;
}
}).when(defaultMQPushConsumer).executePullRequestImmediately(any(PullRequest.class));
}
@Test
public void testMessageQueueChanged_SizeThreshold() {
RebalancePushImpl rebalancePush = new RebalancePushImpl(consumerGroup, MessageModel.CLUSTERING,
new AllocateMessageQueueAveragely(), mqClientInstance, defaultMQPushConsumer);
init(rebalancePush);
// Just set pullThresholdSizeForQueue
defaultMQPushConsumer.getDefaultMQPushConsumer().setPullThresholdSizeForQueue(1024);
Set<MessageQueue> allocateResultSet = new HashSet<MessageQueue>();
allocateResultSet.add(new MessageQueue(topic, "BrokerA", 0));
allocateResultSet.add(new MessageQueue(topic, "BrokerA", 1));
doRebalanceForcibly(rebalancePush, allocateResultSet);
assertThat(defaultMQPushConsumer.getDefaultMQPushConsumer().getPullThresholdSizeForQueue()).isEqualTo(1024);
// Set pullThresholdSizeForTopic
defaultMQPushConsumer.getDefaultMQPushConsumer().setPullThresholdSizeForTopic(1024);
doRebalanceForcibly(rebalancePush, allocateResultSet);
assertThat(defaultMQPushConsumer.getDefaultMQPushConsumer().getPullThresholdSizeForQueue()).isEqualTo(512);
// Change message queue allocate result
allocateResultSet.add(new MessageQueue(topic, "BrokerA", 2));
doRebalanceForcibly(rebalancePush, allocateResultSet);
assertThat(defaultMQPushConsumer.getDefaultMQPushConsumer().getPullThresholdSizeForQueue()).isEqualTo(341);
}
@Test
public void testMessageQueueChanged_ConsumerRuntimeInfo() throws MQClientException {
RebalancePushImpl rebalancePush = new RebalancePushImpl(consumerGroup, MessageModel.CLUSTERING,
new AllocateMessageQueueAveragely(), mqClientInstance, defaultMQPushConsumer);
init(rebalancePush);
defaultMQPushConsumer.getDefaultMQPushConsumer().setPullThresholdSizeForQueue(1024);
defaultMQPushConsumer.getDefaultMQPushConsumer().setPullThresholdForQueue(1024);
Set<MessageQueue> allocateResultSet = new HashSet<MessageQueue>();
allocateResultSet.add(new MessageQueue(topic, "BrokerA", 0));
allocateResultSet.add(new MessageQueue(topic, "BrokerA", 1));
doRebalanceForcibly(rebalancePush, allocateResultSet);
defaultMQPushConsumer.setConsumeMessageService(new ConsumeMessageConcurrentlyService(defaultMQPushConsumer, null));
assertThat(defaultMQPushConsumer.consumerRunningInfo().getProperties().get("pullThresholdSizeForQueue")).isEqualTo("1024");
assertThat(defaultMQPushConsumer.consumerRunningInfo().getProperties().get("pullThresholdForQueue")).isEqualTo("1024");
assertThat(defaultMQPushConsumer.consumerRunningInfo().getProperties().get("pullThresholdSizeForTopic")).isEqualTo("-1");
assertThat(defaultMQPushConsumer.consumerRunningInfo().getProperties().get("pullThresholdForTopic")).isEqualTo("-1");
defaultMQPushConsumer.getDefaultMQPushConsumer().setPullThresholdSizeForTopic(1024);
defaultMQPushConsumer.getDefaultMQPushConsumer().setPullThresholdForTopic(1024);
doRebalanceForcibly(rebalancePush, allocateResultSet);
assertThat(defaultMQPushConsumer.consumerRunningInfo().getProperties().get("pullThresholdSizeForQueue")).isEqualTo("512");
assertThat(defaultMQPushConsumer.consumerRunningInfo().getProperties().get("pullThresholdForQueue")).isEqualTo("512");
assertThat(defaultMQPushConsumer.consumerRunningInfo().getProperties().get("pullThresholdSizeForTopic")).isEqualTo("1024");
assertThat(defaultMQPushConsumer.consumerRunningInfo().getProperties().get("pullThresholdForTopic")).isEqualTo("1024");
// Change message queue allocate result
allocateResultSet.add(new MessageQueue(topic, "BrokerA", 2));
doRebalanceForcibly(rebalancePush, allocateResultSet);
assertThat(defaultMQPushConsumer.consumerRunningInfo().getProperties().get("pullThresholdSizeForQueue")).isEqualTo("341");
assertThat(defaultMQPushConsumer.consumerRunningInfo().getProperties().get("pullThresholdForQueue")).isEqualTo("341");
assertThat(defaultMQPushConsumer.consumerRunningInfo().getProperties().get("pullThresholdSizeForTopic")).isEqualTo("1024");
assertThat(defaultMQPushConsumer.consumerRunningInfo().getProperties().get("pullThresholdForTopic")).isEqualTo("1024");
}
}```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.client.impl.consumer;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.rocketmq.client.consumer.AllocateMessageQueueStrategy;
import org.apache.rocketmq.client.consumer.MessageQueueListener;
import org.apache.rocketmq.client.consumer.store.OffsetStore;
import org.apache.rocketmq.client.consumer.store.ReadOffsetType;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.common.protocol.heartbeat.ConsumeType;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData;
public class RebalancePushImpl extends RebalanceImpl {
private final static long UNLOCK_DELAY_TIME_MILLS = Long.parseLong(System.getProperty("rocketmq.client.unlockDelayTimeMills", "20000"));
private final DefaultMQPushConsumerImpl defaultMQPushConsumerImpl;
public RebalancePushImpl(DefaultMQPushConsumerImpl defaultMQPushConsumerImpl) {
this(null, null, null, null, defaultMQPushConsumerImpl);
}
public RebalancePushImpl(String consumerGroup, MessageModel messageModel,
AllocateMessageQueueStrategy allocateMessageQueueStrategy,
MQClientInstance mQClientFactory, DefaultMQPushConsumerImpl defaultMQPushConsumerImpl) {
super(consumerGroup, messageModel, allocateMessageQueueStrategy, mQClientFactory);
this.defaultMQPushConsumerImpl = defaultMQPushConsumerImpl;
}
@Override
public void messageQueueChanged(String topic, Set<MessageQueue> mqAll, Set<MessageQueue> mqDivided) {
/**
* When rebalance result changed, should update subscription's version to notify broker.
* Fix: inconsistency subscription may lead to consumer miss messages.
*/
SubscriptionData subscriptionData = this.subscriptionInner.get(topic);
long newVersion = System.currentTimeMillis();
log.info("{} Rebalance changed, also update version: {}, {}", topic, subscriptionData.getSubVersion(), newVersion);
subscriptionData.setSubVersion(newVersion);
int currentQueueCount = this.processQueueTable.size();
if (currentQueueCount != 0) {
int pullThresholdForTopic = this.defaultMQPushConsumerImpl.getDefaultMQPushConsumer().getPullThresholdForTopic();
if (pullThresholdForTopic != -1) {
int minPullThresholdForQueue = defaultMQPushConsumerImpl.getDefaultMQPushConsumer().getMinPullThresholdForQueue();
int newVal = Math.max(minPullThresholdForQueue, pullThresholdForTopic / currentQueueCount);
log.info("The pullThresholdForQueue is changed from {} to {}, min PullThresholdForQueue is {}.",
this.defaultMQPushConsumerImpl.getDefaultMQPushConsumer().getPullThresholdForQueue(), newVal,
minPullThresholdForQueue);
this.defaultMQPushConsumerImpl.getDefaultMQPushConsumer().setPullThresholdForQueue(newVal);
}
int pullThresholdSizeForTopic = this.defaultMQPushConsumerImpl.getDefaultMQPushConsumer().getPullThresholdSizeForTopic();
if (pullThresholdSizeForTopic != -1) {
int newVal = Math.max(1, pullThresholdSizeForTopic / currentQueueCount);
log.info("The pullThresholdSizeForQueue is changed from {} to {}",
this.defaultMQPushConsumerImpl.getDefaultMQPushConsumer().getPullThresholdSizeForQueue(), newVal);
this.defaultMQPushConsumerImpl.getDefaultMQPushConsumer().setPullThresholdSizeForQueue(newVal);
}
}
// notify broker
if (!MixAll.MQTT_MODE) {
this.getmQClientFactory().sendHeartbeatToAllBrokerWithLock();
}
//exec MessageQueueListener
MessageQueueListener messageQueueListener = this.defaultMQPushConsumerImpl.getDefaultMQPushConsumer().getMessageQueueListener();
if (messageQueueListener != null) {
try {
messageQueueListener.messageQueueChanged(topic, mqAll, mqDivided);
} catch (Throwable e) {
log.error("messageQueueChanged exception", e);
}
}
}
@Override
public boolean removeUnnecessaryMessageQueue(MessageQueue mq, ProcessQueue pq) {
this.defaultMQPushConsumerImpl.getOffsetStore().persist(mq);
this.defaultMQPushConsumerImpl.getOffsetStore().removeOffset(mq);
if (this.defaultMQPushConsumerImpl.isConsumeOrderly()
&& MessageModel.CLUSTERING.equals(this.defaultMQPushConsumerImpl.messageModel())) {
try {
if (pq.getLockConsume().tryLock(1000, TimeUnit.MILLISECONDS)) {
try {
return this.unlockDelay(mq, pq);
} finally {
pq.getLockConsume().unlock();
}
} else {
log.warn("[WRONG]mq is consuming, so can not unlock it, {}. maybe hanged for a while, {}",
mq,
pq.getTryUnlockTimes());
pq.incTryUnlockTimes();
}
} catch (Exception e) {
log.error("removeUnnecessaryMessageQueue Exception", e);
}
return false;
}
return true;
}
private boolean unlockDelay(final MessageQueue mq, final ProcessQueue pq) {
if (pq.hasTempMessage()) {
log.info("[{}]unlockDelay, begin {} ", mq.hashCode(), mq);
this.defaultMQPushConsumerImpl.getmQClientFactory().getScheduledExecutorService().schedule(new Runnable() {
@Override
public void run() {
log.info("[{}]unlockDelay, execute at once {}", mq.hashCode(), mq);
RebalancePushImpl.this.unlock(mq, true);
}
}, UNLOCK_DELAY_TIME_MILLS, TimeUnit.MILLISECONDS);
} else {
this.unlock(mq, true);
}
return true;
}
@Override
public ConsumeType consumeType() {
return ConsumeType.CONSUME_PASSIVELY;
}
@Override
public void removeDirtyOffset(final MessageQueue mq) {
this.defaultMQPushConsumerImpl.getOffsetStore().removeOffset(mq);
}
@Override
public long computePullFromWhere(MessageQueue mq) {
long result = -1;
final ConsumeFromWhere consumeFromWhere = this.defaultMQPushConsumerImpl.getDefaultMQPushConsumer().getConsumeFromWhere();
final OffsetStore offsetStore = this.defaultMQPushConsumerImpl.getOffsetStore();
switch (consumeFromWhere) {
case CONSUME_FROM_LAST_OFFSET_AND_FROM_MIN_WHEN_BOOT_FIRST:
case CONSUME_FROM_MIN_OFFSET:
case CONSUME_FROM_MAX_OFFSET:
case CONSUME_FROM_LAST_OFFSET: {
long lastOffset = offsetStore.readOffset(mq, ReadOffsetType.READ_FROM_STORE);
if (lastOffset >= 0) {
result = lastOffset;
}
// First start,no offset
else if (-1 == lastOffset) {
if (mq.getTopic().startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
result = 0L;
} else {
try {
result = this.mQClientFactory.getMQAdminImpl().maxOffset(mq);
} catch (MQClientException e) {
result = -1;
}
}
} else {
result = -1;
}
break;
}
case CONSUME_FROM_FIRST_OFFSET: {
long lastOffset = offsetStore.readOffset(mq, ReadOffsetType.READ_FROM_STORE);
if (lastOffset >= 0) {
result = lastOffset;
} else if (-1 == lastOffset) {
result = 0L;
} else {
result = -1;
}
break;
}
case CONSUME_FROM_TIMESTAMP: {
long lastOffset = offsetStore.readOffset(mq, ReadOffsetType.READ_FROM_STORE);
if (lastOffset >= 0) {
result = lastOffset;
} else if (-1 == lastOffset) {
if (mq.getTopic().startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
try {
result = this.mQClientFactory.getMQAdminImpl().maxOffset(mq);
} catch (MQClientException e) {
result = -1;
}
} else {
try {
long timestamp = UtilAll.parseDate(this.defaultMQPushConsumerImpl.getDefaultMQPushConsumer().getConsumeTimestamp(),
UtilAll.YYYYMMDDHHMMSS).getTime();
result = this.mQClientFactory.getMQAdminImpl().searchOffset(mq, timestamp);
} catch (MQClientException e) {
result = -1;
}
}
} else {
result = -1;
}
break;
}
default:
break;
}
return result;
}
@Override
public void dispatchPullRequest(List<PullRequest> pullRequestList) {
for (PullRequest pullRequest : pullRequestList) {
this.defaultMQPushConsumerImpl.executePullRequestImmediately(pullRequest);
log.info("doRebalance, {}, add a new pull request {}", consumerGroup, pullRequest);
}
}
}
```
|
```package org.apache.rocketmq.tools.command.broker;
import java.lang.reflect.Field;
import java.util.HashMap;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.impl.MQClientAPIImpl;
import org.apache.rocketmq.client.impl.MQClientManager;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.common.protocol.body.KVTable;
import org.apache.rocketmq.remoting.exception.RemotingConnectException;
import org.apache.rocketmq.remoting.exception.RemotingSendRequestException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExtImpl;
import org.apache.rocketmq.tools.command.SubCommandException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BrokerStatusSubCommandTest {
private static DefaultMQAdminExt defaultMQAdminExt;
private static DefaultMQAdminExtImpl defaultMQAdminExtImpl;
private static MQClientInstance mqClientInstance = MQClientManager.getInstance().getAndCreateMQClientInstance(new ClientConfig());
private static MQClientAPIImpl mQClientAPIImpl;
@BeforeClass
public static void init() throws NoSuchFieldException, IllegalAccessException, InterruptedException, RemotingTimeoutException, MQClientException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
mQClientAPIImpl = mock(MQClientAPIImpl.class);
defaultMQAdminExt = new DefaultMQAdminExt();
defaultMQAdminExtImpl = new DefaultMQAdminExtImpl(defaultMQAdminExt, 1000);
Field field = DefaultMQAdminExtImpl.class.getDeclaredField("mqClientInstance");
field.setAccessible(true);
field.set(defaultMQAdminExtImpl, mqClientInstance);
field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
field.setAccessible(true);
field.set(mqClientInstance, mQClientAPIImpl);
field = DefaultMQAdminExt.class.getDeclaredField("defaultMQAdminExtImpl");
field.setAccessible(true);
field.set(defaultMQAdminExt, defaultMQAdminExtImpl);
KVTable kvTable = new KVTable();
kvTable.setTable(new HashMap<String, String>());
when(mQClientAPIImpl.getBrokerRuntimeInfo(anyString(), anyLong())).thenReturn(kvTable);
}
@AfterClass
public static void terminate() {
defaultMQAdminExt.shutdown();
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
BrokerStatusSubCommand cmd = new BrokerStatusSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.tools.command.broker;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.common.protocol.body.KVTable;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.exception.RemotingConnectException;
import org.apache.rocketmq.remoting.exception.RemotingSendRequestException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.command.CommandUtil;
import org.apache.rocketmq.tools.command.SubCommand;
import org.apache.rocketmq.tools.command.SubCommandException;
public class BrokerStatusSubCommand implements SubCommand {
@Override
public String commandName() {
return "brokerStatus";
}
@Override
public String commandDesc() {
return "Fetch broker runtime status data";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("b", "brokerAddr", true, "Broker address");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("c", "clusterName", true, "which cluster");
opt.setRequired(false);
options.addOption(opt);
return options;
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
defaultMQAdminExt.start();
String brokerAddr = commandLine.hasOption('b') ? commandLine.getOptionValue('b').trim() : null;
String clusterName = commandLine.hasOption('c') ? commandLine.getOptionValue('c').trim() : null;
if (brokerAddr != null) {
printBrokerRuntimeStats(defaultMQAdminExt, brokerAddr, false);
} else if (clusterName != null) {
Set<String> masterSet =
CommandUtil.fetchMasterAndSlaveAddrByClusterName(defaultMQAdminExt, clusterName);
for (String ba : masterSet) {
try {
printBrokerRuntimeStats(defaultMQAdminExt, ba, true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
public void printBrokerRuntimeStats(final DefaultMQAdminExt defaultMQAdminExt, final String brokerAddr,
final boolean printBroker) throws InterruptedException, MQBrokerException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException {
KVTable kvTable = defaultMQAdminExt.fetchBrokerRuntimeStats(brokerAddr);
TreeMap<String, String> tmp = new TreeMap<String, String>();
tmp.putAll(kvTable.getTable());
Iterator<Entry<String, String>> it = tmp.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> next = it.next();
if (printBroker) {
System.out.printf("%-24s %-32s: %s%n", brokerAddr, next.getKey(), next.getValue());
} else {
System.out.printf("%-32s: %s%n", next.getKey(), next.getValue());
}
}
}
}
```
|
```package org.apache.rocketmq.namesrv.kvconfig;
import org.apache.rocketmq.common.namesrv.NamesrvUtil;
import org.apache.rocketmq.namesrv.NameServerInstanceTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class KVConfigManagerTest extends NameServerInstanceTest {
private KVConfigManager kvConfigManager;
@Before
public void setup() throws Exception {
kvConfigManager = new KVConfigManager(nameSrvController);
}
@Test
public void testPutKVConfig() {
kvConfigManager.putKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, "UnitTest", "test");
byte[] kvConfig = kvConfigManager.getKVListByNamespace(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG);
assertThat(kvConfig).isNotNull();
String value = kvConfigManager.getKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, "UnitTest");
assertThat(value).isEqualTo("test");
}
@Test
public void testDeleteKVConfig() {
kvConfigManager.deleteKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, "UnitTest");
byte[] kvConfig = kvConfigManager.getKVListByNamespace(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG);
assertThat(kvConfig).isNull();
Assert.assertTrue(kvConfig == null);
String value = kvConfigManager.getKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, "UnitTest");
assertThat(value).isNull();
}
}```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.namesrv.kvconfig;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.common.protocol.body.KVTable;
import org.apache.rocketmq.namesrv.NamesrvController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KVConfigManager {
private static final Logger log = LoggerFactory.getLogger(LoggerName.NAMESRV_LOGGER_NAME);
private final NamesrvController namesrvController;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final HashMap<String/* Namespace */, HashMap<String/* Key */, String/* Value */>> configTable =
new HashMap<String, HashMap<String, String>>();
public KVConfigManager(NamesrvController namesrvController) {
this.namesrvController = namesrvController;
}
public void load() {
String content = null;
try {
content = MixAll.file2String(this.namesrvController.getNamesrvConfig().getKvConfigPath());
} catch (IOException e) {
log.warn("Load KV config table exception", e);
}
if (content != null) {
KVConfigSerializeWrapper kvConfigSerializeWrapper =
KVConfigSerializeWrapper.fromJson(content, KVConfigSerializeWrapper.class);
if (null != kvConfigSerializeWrapper) {
this.configTable.putAll(kvConfigSerializeWrapper.getConfigTable());
log.info("load KV config table OK");
}
}
}
public void putKVConfig(final String namespace, final String key, final String value) {
try {
this.lock.writeLock().lockInterruptibly();
try {
HashMap<String, String> kvTable = this.configTable.get(namespace);
if (null == kvTable) {
kvTable = new HashMap<String, String>();
this.configTable.put(namespace, kvTable);
log.info("putKVConfig create new Namespace {}", namespace);
}
final String prev = kvTable.put(key, value);
if (null != prev) {
log.info("putKVConfig update config item, Namespace: {} Key: {} Value: {}",
namespace, key, value);
} else {
log.info("putKVConfig create new config item, Namespace: {} Key: {} Value: {}",
namespace, key, value);
}
} finally {
this.lock.writeLock().unlock();
}
} catch (InterruptedException e) {
log.error("putKVConfig InterruptedException", e);
}
this.persist();
}
public void persist() {
try {
this.lock.readLock().lockInterruptibly();
try {
KVConfigSerializeWrapper kvConfigSerializeWrapper = new KVConfigSerializeWrapper();
kvConfigSerializeWrapper.setConfigTable(this.configTable);
String content = kvConfigSerializeWrapper.toJson();
if (null != content) {
MixAll.string2File(content, this.namesrvController.getNamesrvConfig().getKvConfigPath());
}
} catch (IOException e) {
log.error("persist kvconfig Exception, "
+ this.namesrvController.getNamesrvConfig().getKvConfigPath(), e);
} finally {
this.lock.readLock().unlock();
}
} catch (InterruptedException e) {
log.error("persist InterruptedException", e);
}
}
public void deleteKVConfig(final String namespace, final String key) {
try {
this.lock.writeLock().lockInterruptibly();
try {
HashMap<String, String> kvTable = this.configTable.get(namespace);
if (null != kvTable) {
String value = kvTable.remove(key);
log.info("deleteKVConfig delete a config item, Namespace: {} Key: {} Value: {}",
namespace, key, value);
}
} finally {
this.lock.writeLock().unlock();
}
} catch (InterruptedException e) {
log.error("deleteKVConfig InterruptedException", e);
}
this.persist();
}
public byte[] getKVListByNamespace(final String namespace) {
try {
this.lock.readLock().lockInterruptibly();
try {
HashMap<String, String> kvTable = this.configTable.get(namespace);
if (null != kvTable) {
KVTable table = new KVTable();
table.setTable(kvTable);
return table.encode();
}
} finally {
this.lock.readLock().unlock();
}
} catch (InterruptedException e) {
log.error("getKVListByNamespace InterruptedException", e);
}
return null;
}
public String getKVConfig(final String namespace, final String key) {
try {
this.lock.readLock().lockInterruptibly();
try {
HashMap<String, String> kvTable = this.configTable.get(namespace);
if (null != kvTable) {
return kvTable.get(key);
}
} finally {
this.lock.readLock().unlock();
}
} catch (InterruptedException e) {
log.error("getKVConfig InterruptedException", e);
}
return null;
}
public void printAllPeriodically() {
try {
this.lock.readLock().lockInterruptibly();
try {
log.info("--------------------------------------------------------");
{
log.info("configTable SIZE: {}", this.configTable.size());
Iterator<Entry<String, HashMap<String, String>>> it =
this.configTable.entrySet().iterator();
while (it.hasNext()) {
Entry<String, HashMap<String, String>> next = it.next();
Iterator<Entry<String, String>> itSub = next.getValue().entrySet().iterator();
while (itSub.hasNext()) {
Entry<String, String> nextSub = itSub.next();
log.info("configTable NS: {} Key: {} Value: {}", next.getKey(), nextSub.getKey(),
nextSub.getValue());
}
}
}
} finally {
this.lock.readLock().unlock();
}
} catch (InterruptedException e) {
log.error("printAllPeriodically InterruptedException", e);
}
}
}
```
|
```package org.apache.rocketmq.broker.processor;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import java.util.HashMap;
import java.util.UUID;
import org.apache.rocketmq.broker.BrokerController;
import org.apache.rocketmq.broker.client.ClientChannelInfo;
import org.apache.rocketmq.broker.client.ConsumerGroupInfo;
import org.apache.rocketmq.common.BrokerConfig;
import org.apache.rocketmq.common.protocol.RequestCode;
import org.apache.rocketmq.common.protocol.ResponseCode;
import org.apache.rocketmq.common.protocol.header.UnregisterClientRequestHeader;
import org.apache.rocketmq.common.protocol.heartbeat.ConsumerData;
import org.apache.rocketmq.remoting.exception.RemotingCommandException;
import org.apache.rocketmq.remoting.netty.NettyClientConfig;
import org.apache.rocketmq.remoting.netty.NettyServerConfig;
import org.apache.rocketmq.remoting.protocol.LanguageCode;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
import org.apache.rocketmq.store.config.MessageStoreConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import static org.apache.rocketmq.broker.processor.PullMessageProcessorTest.createConsumerData;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ClientManageProcessorTest {
private ClientManageProcessor clientManageProcessor;
@Spy
private BrokerController brokerController = new BrokerController(new BrokerConfig(), new NettyServerConfig(), new NettyClientConfig(), new MessageStoreConfig());
@Mock
private ChannelHandlerContext handlerContext;
@Mock
private Channel channel;
private ClientChannelInfo clientChannelInfo;
private String clientId = UUID.randomUUID().toString();
private String group = "FooBarGroup";
private String topic = "FooBar";
@Before
public void init() {
when(handlerContext.channel()).thenReturn(channel);
clientManageProcessor = new ClientManageProcessor(brokerController);
clientChannelInfo = new ClientChannelInfo(channel, clientId, LanguageCode.JAVA, 100);
brokerController.getProducerManager().registerProducer(group, clientChannelInfo);
ConsumerData consumerData = createConsumerData(group, topic);
brokerController.getConsumerManager().registerConsumer(
consumerData.getGroupName(),
clientChannelInfo,
consumerData.getConsumeType(),
consumerData.getMessageModel(),
consumerData.getConsumeFromWhere(),
consumerData.getSubscriptionDataSet(),
false);
}
@Test
public void processRequest_UnRegisterProducer() throws Exception {
brokerController.getProducerManager().registerProducer(group, clientChannelInfo);
HashMap<Channel, ClientChannelInfo> channelMap = brokerController.getProducerManager().getGroupChannelTable().get(group);
assertThat(channelMap).isNotNull();
assertThat(channelMap.get(channel)).isEqualTo(clientChannelInfo);
RemotingCommand request = createUnRegisterProducerCommand();
RemotingCommand response = clientManageProcessor.processRequest(handlerContext, request);
assertThat(response).isNotNull();
assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS);
channelMap = brokerController.getProducerManager().getGroupChannelTable().get(group);
assertThat(channelMap).isNull();
}
@Test
public void processRequest_UnRegisterConsumer() throws RemotingCommandException {
ConsumerGroupInfo consumerGroupInfo = brokerController.getConsumerManager().getConsumerGroupInfo(group);
assertThat(consumerGroupInfo).isNotNull();
RemotingCommand request = createUnRegisterConsumerCommand();
RemotingCommand response = clientManageProcessor.processRequest(handlerContext, request);
assertThat(response).isNotNull();
assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS);
consumerGroupInfo = brokerController.getConsumerManager().getConsumerGroupInfo(group);
assertThat(consumerGroupInfo).isNull();
}
private RemotingCommand createUnRegisterProducerCommand() {
UnregisterClientRequestHeader requestHeader = new UnregisterClientRequestHeader();
requestHeader.setClientID(clientId);
requestHeader.setProducerGroup(group);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UNREGISTER_CLIENT, requestHeader);
request.setLanguage(LanguageCode.JAVA);
request.setVersion(100);
request.makeCustomHeaderToNet();
return request;
}
private RemotingCommand createUnRegisterConsumerCommand() {
UnregisterClientRequestHeader requestHeader = new UnregisterClientRequestHeader();
requestHeader.setClientID(clientId);
requestHeader.setConsumerGroup(group);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UNREGISTER_CLIENT, requestHeader);
request.setLanguage(LanguageCode.JAVA);
request.setVersion(100);
request.makeCustomHeaderToNet();
return request;
}
}```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.broker.processor;
import io.netty.channel.ChannelHandlerContext;
import org.apache.rocketmq.broker.BrokerController;
import org.apache.rocketmq.broker.client.ClientChannelInfo;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.common.constant.PermName;
import org.apache.rocketmq.common.filter.ExpressionType;
import org.apache.rocketmq.common.protocol.RequestCode;
import org.apache.rocketmq.common.protocol.ResponseCode;
import org.apache.rocketmq.common.protocol.body.CheckClientRequestBody;
import org.apache.rocketmq.common.protocol.header.UnregisterClientRequestHeader;
import org.apache.rocketmq.common.protocol.header.UnregisterClientResponseHeader;
import org.apache.rocketmq.common.protocol.heartbeat.ConsumerData;
import org.apache.rocketmq.common.protocol.heartbeat.HeartbeatData;
import org.apache.rocketmq.common.protocol.heartbeat.ProducerData;
import org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData;
import org.apache.rocketmq.common.subscription.SubscriptionGroupConfig;
import org.apache.rocketmq.common.sysflag.TopicSysFlag;
import org.apache.rocketmq.filter.FilterFactory;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingCommandException;
import org.apache.rocketmq.remoting.netty.NettyRequestProcessor;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClientManageProcessor implements NettyRequestProcessor {
private static final Logger log = LoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME);
private final BrokerController brokerController;
public ClientManageProcessor(final BrokerController brokerController) {
this.brokerController = brokerController;
}
@Override
public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request)
throws RemotingCommandException {
switch (request.getCode()) {
case RequestCode.HEART_BEAT:
return this.heartBeat(ctx, request);
case RequestCode.UNREGISTER_CLIENT:
return this.unregisterClient(ctx, request);
case RequestCode.CHECK_CLIENT_CONFIG:
return this.checkClientConfig(ctx, request);
default:
break;
}
return null;
}
@Override
public boolean rejectRequest() {
return false;
}
public RemotingCommand heartBeat(ChannelHandlerContext ctx, RemotingCommand request) {
RemotingCommand response = RemotingCommand.createResponseCommand(null);
long start = System.currentTimeMillis();
HeartbeatData heartbeatData = HeartbeatData.decode(request.getBody(), HeartbeatData.class);
ClientChannelInfo clientChannelInfo = new ClientChannelInfo(
ctx.channel(),
heartbeatData.getClientID(),
request.getLanguage(),
request.getVersion()
);
long startProcess = System.currentTimeMillis();
for (ConsumerData data : heartbeatData.getConsumerDataSet()) {
boolean hasTopic = false;
for (SubscriptionData subscriptionData : data.getSubscriptionDataSet()) {
if (brokerController.getTopicConfigManager().getTopicConfigTable().containsKey(subscriptionData.getTopic())) {
hasTopic = true;
break;
}
}
if (!hasTopic) {
//ignore this group if there is no topic it subscribes.
continue;
}
SubscriptionGroupConfig subscriptionGroupConfig =
this.brokerController.getSubscriptionGroupManager().findSubscriptionGroupConfig(
data.getGroupName());
boolean isNotifyConsumerIdsChangedEnable = !MixAll.MQTT_MODE;
if (null != subscriptionGroupConfig) {
isNotifyConsumerIdsChangedEnable = subscriptionGroupConfig.isNotifyConsumerIdsChangedEnable();
if (!MixAll.MQTT_MODE) { //do not use RETRY Topic.
int topicSysFlag = 0;
if (data.isUnitMode()) {
topicSysFlag = TopicSysFlag.buildSysFlag(false, true);
}
String newTopic = MixAll.getRetryTopic(data.getGroupName());
this.brokerController.getTopicConfigManager().createTopicInSendMessageBackMethod(
newTopic,
subscriptionGroupConfig.getRetryQueueNums(),
PermName.PERM_WRITE | PermName.PERM_READ, topicSysFlag);
}
}
boolean changed = this.brokerController.getConsumerManager().registerConsumer(
data.getGroupName(),
clientChannelInfo,
data.getConsumeType(),
data.getMessageModel(),
data.getConsumeFromWhere(),
data.getSubscriptionDataSet(),
isNotifyConsumerIdsChangedEnable
);
if (changed) {
log.info("registerConsumer info changed {} {}",
data.toString(),
RemotingHelper.parseChannelRemoteAddr(ctx.channel())
);
}
}
long elapse = System.currentTimeMillis() - start;
if (elapse > 5000) {
log.info("long heartBeat process, CID={}, requestBody={}, decode={}ms, totalProcess={}",
heartbeatData.getClientID(), request.getBody().length, startProcess - start, elapse);
}
for (ProducerData data : heartbeatData.getProducerDataSet()) {
this.brokerController.getProducerManager().registerProducer(data.getGroupName(),
clientChannelInfo);
}
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
public RemotingCommand unregisterClient(ChannelHandlerContext ctx, RemotingCommand request)
throws RemotingCommandException {
final RemotingCommand response =
RemotingCommand.createResponseCommand(UnregisterClientResponseHeader.class);
final UnregisterClientRequestHeader requestHeader =
(UnregisterClientRequestHeader) request
.decodeCommandCustomHeader(UnregisterClientRequestHeader.class);
ClientChannelInfo clientChannelInfo = new ClientChannelInfo(
ctx.channel(),
requestHeader.getClientID(),
request.getLanguage(),
request.getVersion());
{
final String group = requestHeader.getProducerGroup();
if (group != null) {
this.brokerController.getProducerManager().unregisterProducer(group, clientChannelInfo);
}
}
{
final String group = requestHeader.getConsumerGroup();
if (group != null) {
SubscriptionGroupConfig subscriptionGroupConfig =
this.brokerController.getSubscriptionGroupManager().findSubscriptionGroupConfig(group);
boolean isNotifyConsumerIdsChangedEnable = true;
if (null != subscriptionGroupConfig) {
isNotifyConsumerIdsChangedEnable = subscriptionGroupConfig.isNotifyConsumerIdsChangedEnable();
}
this.brokerController.getConsumerManager().unregisterConsumer(group, clientChannelInfo, isNotifyConsumerIdsChangedEnable);
}
}
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
public RemotingCommand checkClientConfig(ChannelHandlerContext ctx, RemotingCommand request)
throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
CheckClientRequestBody requestBody = CheckClientRequestBody.decode(request.getBody(),
CheckClientRequestBody.class);
if (requestBody != null && requestBody.getSubscriptionData() != null) {
SubscriptionData subscriptionData = requestBody.getSubscriptionData();
if (ExpressionType.isTagType(subscriptionData.getExpressionType())) {
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
if (!this.brokerController.getBrokerConfig().isEnablePropertyFilter()) {
response.setCode(ResponseCode.SYSTEM_ERROR);
response.setRemark("The broker does not support consumer to filter message by " + subscriptionData.getExpressionType());
return response;
}
try {
FilterFactory.INSTANCE.get(subscriptionData.getExpressionType()).compile(subscriptionData.getSubString());
} catch (Exception e) {
log.warn("Client {}@{} filter message, but failed to compile expression! sub={}, error={}",
requestBody.getClientId(), requestBody.getGroup(), requestBody.getSubscriptionData(), e.getMessage());
response.setCode(ResponseCode.SUBSCRIPTION_PARSE_FAILED);
response.setRemark(e.getMessage());
return response;
}
}
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
}
```
|
```package org.apache.rocketmq.tools.command.topic;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class TopicClusterSubCommandTest {
@Test
public void testExecute() {
TopicClusterSubCommand cmd = new TopicClusterSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-t unit-test"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test");
}
}```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.tools.command.topic;
import java.util.Set;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.command.SubCommand;
import org.apache.rocketmq.tools.command.SubCommandException;
public class TopicClusterSubCommand implements SubCommand {
@Override
public String commandName() {
return "topicClusterList";
}
@Override
public String commandDesc() {
return "get cluster info for topic";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("t", "topic", true, "topic name");
opt.setRequired(true);
options.addOption(opt);
return options;
}
@Override
public void execute(final CommandLine commandLine, final Options options,
RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
String topic = commandLine.getOptionValue('t').trim();
try {
defaultMQAdminExt.start();
Set<String> clusters = defaultMQAdminExt.getTopicClusterList(topic);
for (String value : clusters) {
System.out.printf("%s%n", value);
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
}
```
|
```package org.apache.rocketmq.tools.command.topic;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class UpdateOrderConfCommandTest {
@Test
public void testExecute() {
UpdateOrderConfCommand cmd = new UpdateOrderConfCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-t unit-test", "-v default-broker:8", "-m post"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test");
assertThat(commandLine.getOptionValue('v').trim()).isEqualTo("default-broker:8");
assertThat(commandLine.getOptionValue('m').trim()).isEqualTo("post");
}
}```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.tools.command.topic;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.namesrv.NamesrvUtil;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.command.SubCommand;
import org.apache.rocketmq.tools.command.SubCommandException;
public class UpdateOrderConfCommand implements SubCommand {
@Override
public String commandName() {
return "updateOrderConf";
}
@Override
public String commandDesc() {
return "Create or update or delete order conf";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("t", "topic", true, "topic name");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("v", "orderConf", true, "set order conf [eg. brokerName1:num;brokerName2:num]");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("m", "method", true, "option type [eg. put|get|delete");
opt.setRequired(true);
options.addOption(opt);
return options;
}
@Override
public void execute(final CommandLine commandLine, final Options options,
RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
String topic = commandLine.getOptionValue('t').trim();
String type = commandLine.getOptionValue('m').trim();
if ("get".equals(type)) {
defaultMQAdminExt.start();
String orderConf =
defaultMQAdminExt.getKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, topic);
System.out.printf("get orderConf success. topic=[%s], orderConf=[%s] ", topic, orderConf);
return;
} else if ("put".equals(type)) {
defaultMQAdminExt.start();
String orderConf = "";
if (commandLine.hasOption('v')) {
orderConf = commandLine.getOptionValue('v').trim();
}
if (UtilAll.isBlank(orderConf)) {
throw new Exception("please set orderConf with option -v.");
}
defaultMQAdminExt.createOrUpdateOrderConf(topic, orderConf, true);
System.out.printf("update orderConf success. topic=[%s], orderConf=[%s]", topic,
orderConf.toString());
return;
} else if ("delete".equals(type)) {
defaultMQAdminExt.start();
defaultMQAdminExt.deleteKvConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, topic);
System.out.printf("delete orderConf success. topic=[%s]", topic);
return;
}
ServerUtil.printCommandLineHelp("mqadmin " + this.commandName(), options);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
}
```
|
```package org.apache.rocketmq.tools.command.broker;
import java.lang.reflect.Field;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.impl.MQClientAPIImpl;
import org.apache.rocketmq.client.impl.MQClientManager;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.remoting.exception.RemotingConnectException;
import org.apache.rocketmq.remoting.exception.RemotingSendRequestException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExtImpl;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.mockito.Mockito.mock;
public class SendMsgStatusCommandTest {
private static DefaultMQAdminExt defaultMQAdminExt;
private static DefaultMQAdminExtImpl defaultMQAdminExtImpl;
private static MQClientInstance mqClientInstance = MQClientManager.getInstance().getAndCreateMQClientInstance(new ClientConfig());
private static MQClientAPIImpl mQClientAPIImpl;
@BeforeClass
public static void init() throws NoSuchFieldException, IllegalAccessException, InterruptedException, RemotingTimeoutException, MQClientException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
mQClientAPIImpl = mock(MQClientAPIImpl.class);
defaultMQAdminExt = new DefaultMQAdminExt();
defaultMQAdminExtImpl = new DefaultMQAdminExtImpl(defaultMQAdminExt, 1000);
Field field = DefaultMQAdminExtImpl.class.getDeclaredField("mqClientInstance");
field.setAccessible(true);
field.set(defaultMQAdminExtImpl, mqClientInstance);
field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
field.setAccessible(true);
field.set(mqClientInstance, mQClientAPIImpl);
field = DefaultMQAdminExt.class.getDeclaredField("defaultMQAdminExtImpl");
field.setAccessible(true);
field.set(defaultMQAdminExt, defaultMQAdminExtImpl);
}
@AfterClass
public static void terminate() {
defaultMQAdminExt.shutdown();
}
@Test
public void testExecute() {
SendMsgStatusCommand cmd = new SendMsgStatusCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-b 127.0.0.1:10911", "-s 1024 -c 10"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
//cmd.execute(commandLine, options, null);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.tools.command.broker;
import java.io.UnsupportedEncodingException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.tools.command.SubCommand;
import org.apache.rocketmq.tools.command.SubCommandException;
public class SendMsgStatusCommand implements SubCommand {
private static Message buildMessage(final String topic, final int messageSize) throws UnsupportedEncodingException {
Message msg = new Message();
msg.setTopic(topic);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < messageSize; i += 11) {
sb.append("hello jodie");
}
msg.setBody(sb.toString().getBytes(MixAll.DEFAULT_CHARSET));
return msg;
}
@Override
public String commandName() {
return "sendMsgStatus";
}
@Override
public String commandDesc() {
return "send msg to broker.";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("b", "brokerName", true, "Broker Name");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("s", "messageSize", true, "Message Size, Default: 128");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("c", "count", true, "send message count, Default: 50");
opt.setRequired(false);
options.addOption(opt);
return options;
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
final DefaultMQProducer producer = new DefaultMQProducer("PID_SMSC", rpcHook);
producer.setInstanceName("PID_SMSC_" + System.currentTimeMillis());
try {
producer.start();
String brokerName = commandLine.getOptionValue('b').trim();
int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s')) : 128;
int count = commandLine.hasOption('c') ? Integer.parseInt(commandLine.getOptionValue('c')) : 50;
producer.send(buildMessage(brokerName, 16));
for (int i = 0; i < count; i++) {
long begin = System.currentTimeMillis();
SendResult result = producer.send(buildMessage(brokerName, messageSize));
System.out.printf("rt:" + (System.currentTimeMillis() - begin) + "ms, SendResult=%s", result);
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
producer.shutdown();
}
}
}
```
|
```package com.xiaoju.chronos;
import com.xiaojukeji.chronos.config.ConfigManager;
import com.xiaojukeji.chronos.db.RDB;
import org.junit.AfterClass;
import org.junit.BeforeClass;
public class TestPullService {
private static String dbPath = "/Users/didi/rocks_db";
private static String configPath = "/Users/didi/work/carrera-chronos/src/main/resources/chronos.yaml";
@BeforeClass
public static void init() {
ConfigManager.initConfig(configPath);
RDB.init(dbPath);
}
@AfterClass
public static void destructor() {
RDB.close();
}
}```
|
Please help me generate a test for this class.
|
```package com.xiaojukeji.chronos.services;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.xiaojukeji.chronos.autobatcher.Batcher;
import com.xiaojukeji.chronos.config.ConfigManager;
import com.xiaojukeji.chronos.config.PullConfig;
import com.xiaojukeji.chronos.ha.MasterElection;
import com.xiaojukeji.chronos.metrics.MetricMsgAction;
import com.xiaojukeji.chronos.metrics.MetricMsgToOrFrom;
import com.xiaojukeji.chronos.metrics.MetricMsgType;
import com.xiaojukeji.chronos.metrics.MetricPullMsgResult;
import com.xiaojukeji.chronos.metrics.MetricService;
import com.xiaojukeji.chronos.metrics.MetricWriteMsgResult;
import com.xiaojukeji.chronos.model.CancelWrap;
import com.xiaojukeji.chronos.model.InternalPair;
import com.xiaojukeji.chronos.model.InternalValue;
import com.xiaojukeji.chronos.utils.JsonUtils;
import com.xiaojukeji.chronos.utils.KeyUtils;
import com.xiaojukeji.carrera.chronos.enums.Actions;
import com.xiaojukeji.carrera.chronos.enums.MsgTypes;
import com.xiaojukeji.carrera.chronos.model.BodyExt;
import com.xiaojukeji.carrera.chronos.model.InternalKey;
import com.xiaojukeji.carrera.consumer.thrift.Message;
import com.xiaojukeji.carrera.consumer.thrift.PullResponse;
import com.xiaojukeji.carrera.consumer.thrift.client.CarreraConfig;
import com.xiaojukeji.carrera.consumer.thrift.client.SimpleCarreraConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class MqPullService implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(MqPullService.class);
private static final PullConfig PULL_CONFIG = ConfigManager.getConfig().getPullConfig();
private static final Batcher BATCHER = Batcher.getInstance();
private volatile boolean shouldStop = false;
private CountDownLatch cdl;
private final List<Long> succOffsets = new ArrayList<>();
private final List<Long> failOffsets = new ArrayList<>();
private SimpleCarreraConsumer carreraConsumer;
private String mqPullServiceName;
private final int INTERNAL_PAIR_COUNT = 5000;
private final BlockingQueue<InternalPair> blockingQueue = new ArrayBlockingQueue<>(INTERNAL_PAIR_COUNT);
public MqPullService(final String server, final int index) {
this.mqPullServiceName = Joiner.on("-").join("mqPullServiceName", index);
CarreraConfig carreraConfig = new CarreraConfig();
carreraConfig.setServers(server);
carreraConfig.setGroupId(PULL_CONFIG.getInnerGroup());
carreraConfig.setRetryInterval(PULL_CONFIG.getRetryIntervalMs());
carreraConfig.setTimeout(PULL_CONFIG.getTimeoutMs());
carreraConfig.setMaxBatchSize(PULL_CONFIG.getMaxBatchSize());
carreraConsumer = new SimpleCarreraConsumer(carreraConfig);
LOGGER.info("{} init carrera consumer, carreraConfig:{}", mqPullServiceName, carreraConfig);
}
@Override
public void run() {
long round = 0L;
while (!shouldStop) {
round++;
final PullResponse response = carreraConsumer.pullMessage();
if (response == null || response.getContext() == null || response.getMessagesSize() == 0) {
try {
TimeUnit.MILLISECONDS.sleep(PULL_CONFIG.getRetryIntervalMs());
} catch (InterruptedException e) {}
continue;
}
addOrCancelMessages(response, succOffsets, failOffsets, round);
for (Long offset : succOffsets) {
carreraConsumer.ack(response.getContext(), offset);
}
for (Long offset : failOffsets) {
carreraConsumer.fail(response.getContext(), offset);
}
}
carreraConsumer.stop();
cdl.countDown();
}
public void start() {
new Thread(this).start();
}
private void addOrCancelMessages(PullResponse response, final List<Long> succOffsets, final List<Long> failOffsets, final long round) {
succOffsets.clear();
failOffsets.clear();
for (Message msg : response.getMessages()) {
if (MasterElection.isBackup()) {
final long zkQidOffset = MetaService.getZkQidOffsets().getOrDefault(response.getContext().getQid(), 0L);
if (msg.getOffset() > zkQidOffset) {
failOffsets.add(msg.getOffset());
continue;
}
}
String jsonString = null;
BodyExt bodyExt = null;
try {
jsonString = new String(msg.getValue());
// ๅฆๆjson่งฃๆไธๅบๆฅ, ่ฏดๆๆ ผๅผๆ้ฎ้ข
bodyExt = JsonUtils.fromJsonString(jsonString, BodyExt.class);
if (bodyExt == null) {
LOGGER.error("error while process message, msg.key:{}, msg.value:{}", msg.getKey(), jsonString);
succOffsets.add(msg.getOffset());
// ไธๆฅๆๅๅฐ็้ๆณๆถๆฏ
MetricService.incPullQps("unknown", MetricMsgAction.UNKNOWN, MetricMsgType.UNKNOWN, MetricPullMsgResult.INVALID);
continue;
}
final InternalKey internalKey = new InternalKey(bodyExt.getUniqDelayMsgId());
final InternalValue internalValue = new InternalValue(bodyExt);
if (bodyExt.getAction() == Actions.ADD.getValue()) {
addMessage(internalKey, internalValue, bodyExt.getAction());
}
if (bodyExt.getAction() == Actions.CANCEL.getValue()) {
cancelMessage(internalKey, bodyExt.getTopic(), bodyExt.getAction());
}
if (blockingQueue.size() != 0 && blockingQueue.size() % INTERNAL_PAIR_COUNT == 0) {
MqPushService.getInstance().sendConcurrent(blockingQueue, this.mqPullServiceName, round);
}
succOffsets.add(msg.getOffset());
} catch (Exception e) {
LOGGER.error("error while addOrCancelMessages, jsonString:{}, err:{}", jsonString, e.getMessage(), e);
succOffsets.add(msg.getOffset());
MetricService.incWriteQps(bodyExt.getTopic(), MetricMsgAction.UNKNOWN, MetricMsgType.UNKNOWN,
MetricMsgToOrFrom.UNKNOWN, MetricWriteMsgResult.FAIL);
}
}
BATCHER.flush();
if (blockingQueue.size() != 0) {
MqPushService.getInstance().sendConcurrent(blockingQueue, this.mqPullServiceName, round);
}
}
/**
* ๆทปๅ ๆถๆฏ
*
* @param internalKey
* @param internalValue
*/
private void addMessage(final InternalKey internalKey, final InternalValue internalValue, final int action) {
if (internalKey.getType() == MsgTypes.DELAY.getValue()) {
MetricService.incPullQps(internalValue.getTopic(), MetricMsgAction.ADD, MetricMsgType.DELAY);
if (BATCHER.checkAndPutToDefaultCF(internalKey, internalValue.toJsonString(), internalValue.getTopic(), action)) {
MetricService.incWriteQps(internalValue.getTopic(), MetricMsgAction.ADD, MetricMsgType.DELAY, MetricMsgToOrFrom.DB);
return;
}
MetricService.putMsgSizePercent(internalValue.getTopic(), internalValue.toJsonString().getBytes(Charsets.UTF_8).length);
MetricService.incWriteQps(internalValue.getTopic(), MetricMsgAction.ADD, MetricMsgType.DELAY, MetricMsgToOrFrom.SEND);
putToBlockingQueue(internalKey, internalValue);
} else if (internalKey.getType() == MsgTypes.LOOP_DELAY.getValue()
|| internalKey.getType() == MsgTypes.LOOP_EXPONENT_DELAY.getValue()) {
MetricMsgType msgType = MetricMsgType.LOOP_DELAY;
if (internalKey.getType() == MsgTypes.LOOP_EXPONENT_DELAY.getValue()) {
msgType = MetricMsgType.LOOP_EXPONENT_DELAY;
}
MetricService.incPullQps(internalValue.getTopic(), MetricMsgAction.ADD, msgType);
while (true) {
if (KeyUtils.isInvalidMsg(internalKey)) {
return;
}
// ๅพช็ฏๆถๆฏๅชๅๅ
ฅrocksdbไธๆฌก, seekๅฐ็ๆถๅๅ่ฟ่กๆทปๅ
if (BATCHER.checkAndPutToDefaultCF(internalKey, internalValue.toJsonString(), internalValue.getTopic(), action)) {
MetricService.incWriteQps(internalValue.getTopic(), MetricMsgAction.ADD, msgType, MetricMsgToOrFrom.DB);
return;
}
MetricService.incWriteQps(internalValue.getTopic(), MetricMsgAction.ADD, msgType, MetricMsgToOrFrom.SEND);
putToBlockingQueue(new InternalKey(internalKey), internalValue);
internalKey.nextUniqDelayMsgId();
}
} else {
MetricService.incPullQps(internalValue.getTopic(), MetricMsgAction.ADD, MetricMsgType.UNKNOWN);
LOGGER.error("should not go here, invalid message type:{}, internalKey:{}", internalKey.getType(),
internalKey.genUniqDelayMsgId());
}
}
/**
* ๅๆถๆถๆฏ
*
* @param internalKey
*/
private void cancelMessage(final InternalKey internalKey, final String topic, final int action) {
InternalKey tombStoneInternalKey = internalKey.cloneTombstoneInternalKey();
if (internalKey.getType() == MsgTypes.DELAY.getValue()) {
MetricService.incPullQps(topic, MetricMsgAction.CANCEL, MetricMsgType.DELAY);
BATCHER.putToDefaultCF(tombStoneInternalKey.genUniqDelayMsgId(),
new CancelWrap(internalKey.genUniqDelayMsgId(), topic).toJsonString(), topic, tombStoneInternalKey, action);
} else if (internalKey.getType() == MsgTypes.LOOP_DELAY.getValue()) {
MetricService.incPullQps(topic, MetricMsgAction.CANCEL, MetricMsgType.LOOP_DELAY);
BATCHER.putLoopTombstoneKey(tombStoneInternalKey, internalKey, topic, action);
} else if (internalKey.getType() == MsgTypes.LOOP_EXPONENT_DELAY.getValue()) {
MetricService.incPullQps(topic, MetricMsgAction.CANCEL, MetricMsgType.LOOP_EXPONENT_DELAY);
BATCHER.putLoopTombstoneKey(tombStoneInternalKey, internalKey, topic, action);
} else {
MetricService.incPullQps(topic, MetricMsgAction.CANCEL, MetricMsgType.UNKNOWN);
LOGGER.error("should not go here, invalid message type: {}, internalKey: {}", internalKey.getType(),
internalKey.genUniqDelayMsgId());
}
}
private void putToBlockingQueue(InternalKey internalKey, InternalValue internalValue) {
try {
blockingQueue.put(new InternalPair(internalKey, internalValue));
} catch (InterruptedException e) {
LOGGER.error("error while put to blockingQueue, dMsgId:{}", internalKey.genUniqDelayMsgId());
}
}
public void stop() {
final long start = System.currentTimeMillis();
LOGGER.info("carrera consumer will stop ...");
cdl = new CountDownLatch(1);
shouldStop = true;
while (!carreraConsumer.isStopped()) {
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
}
}
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
LOGGER.info("{} carrera consumer has stopped, cost:{}ms", mqPullServiceName, System.currentTimeMillis() - start);
}
}```
|
```package org.apache.rocketmq.tools.command.connection;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.impl.MQClientAPIImpl;
import org.apache.rocketmq.client.impl.MQClientManager;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.protocol.body.Connection;
import org.apache.rocketmq.common.protocol.body.ConsumerConnection;
import org.apache.rocketmq.common.protocol.heartbeat.ConsumeType;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData;
import org.apache.rocketmq.remoting.exception.RemotingConnectException;
import org.apache.rocketmq.remoting.exception.RemotingSendRequestException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExtImpl;
import org.apache.rocketmq.tools.command.SubCommandException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ConsumerConnectionSubCommandTest {
private static DefaultMQAdminExt defaultMQAdminExt;
private static DefaultMQAdminExtImpl defaultMQAdminExtImpl;
private static MQClientInstance mqClientInstance = MQClientManager.getInstance().getAndCreateMQClientInstance(new ClientConfig());
private static MQClientAPIImpl mQClientAPIImpl;
@BeforeClass
public static void init() throws NoSuchFieldException, IllegalAccessException, InterruptedException, RemotingTimeoutException, MQClientException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
mQClientAPIImpl = mock(MQClientAPIImpl.class);
defaultMQAdminExt = new DefaultMQAdminExt();
defaultMQAdminExtImpl = new DefaultMQAdminExtImpl(defaultMQAdminExt, 1000);
Field field = DefaultMQAdminExtImpl.class.getDeclaredField("mqClientInstance");
field.setAccessible(true);
field.set(defaultMQAdminExtImpl, mqClientInstance);
field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
field.setAccessible(true);
field.set(mqClientInstance, mQClientAPIImpl);
field = DefaultMQAdminExt.class.getDeclaredField("defaultMQAdminExtImpl");
field.setAccessible(true);
field.set(defaultMQAdminExt, defaultMQAdminExtImpl);
ConsumerConnection consumerConnection = new ConsumerConnection();
consumerConnection.setConsumeType(ConsumeType.CONSUME_PASSIVELY);
consumerConnection.setMessageModel(MessageModel.CLUSTERING);
HashSet<Connection> connections = new HashSet<>();
connections.add(new Connection());
consumerConnection.setConnectionSet(connections);
consumerConnection.setSubscriptionTable(new ConcurrentHashMap<String, SubscriptionData>());
consumerConnection.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
when(mQClientAPIImpl.getConsumerConnectionList(anyString(), anyString(), anyLong())).thenReturn(consumerConnection);
}
@AfterClass
public static void terminate() {
defaultMQAdminExt.shutdown();
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
ConsumerConnectionSubCommand cmd = new ConsumerConnectionSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-g default-consumer-group"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.tools.command.connection;
import java.util.Iterator;
import java.util.Map.Entry;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.rocketmq.common.MQVersion;
import org.apache.rocketmq.common.protocol.body.Connection;
import org.apache.rocketmq.common.protocol.body.ConsumerConnection;
import org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.command.SubCommand;
import org.apache.rocketmq.tools.command.SubCommandException;
public class ConsumerConnectionSubCommand implements SubCommand {
@Override
public String commandName() {
return "consumerConnection";
}
@Override
public String commandDesc() {
return "Query consumer's socket connection, client version and subscription";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("g", "consumerGroup", true, "consumer group name");
opt.setRequired(true);
options.addOption(opt);
return options;
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
defaultMQAdminExt.start();
String group = commandLine.getOptionValue('g').trim();
ConsumerConnection cc = defaultMQAdminExt.examineConsumerConnectionInfo(group);
int i = 1;
for (Connection conn : cc.getConnectionSet()) {
System.out.printf("%03d %-32s %-22s %-8s %s%n",
i++,
conn.getClientId(),
conn.getClientAddr(),
conn.getLanguage(),
MQVersion.getVersionDesc(conn.getVersion())
);
}
System.out.printf("%nBelow is subscription:");
Iterator<Entry<String, SubscriptionData>> it = cc.getSubscriptionTable().entrySet().iterator();
i = 1;
while (it.hasNext()) {
Entry<String, SubscriptionData> entry = it.next();
SubscriptionData sd = entry.getValue();
System.out.printf("%03d Topic: %-40s SubExpression: %s%n",
i++,
sd.getTopic(),
sd.getSubString()
);
}
System.out.printf("");
System.out.printf("ConsumeType: %s%n", cc.getConsumeType());
System.out.printf("MessageModel: %s%n", cc.getMessageModel());
System.out.printf("ConsumeFromWhere: %s%n", cc.getConsumeFromWhere());
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
}
```
|
```package com.xiaojukeji.carrera.consumer.thrift.client;
import org.junit.Test;
import java.util.Random;
import static com.xiaojukeji.carrera.consumer.thrift.client.CarreraConfig.GROUP_PATTERN;
import static org.junit.Assert.*;
public class CarreraConfigTest {
@Test
public void test() throws Exception {
CarreraConfig config = new CarreraConfig("some-group", "111.111.111.1:123;111.111.111.1:123;");
config.validate(false);
}
@Test
public void testGroupPattern() throws Exception {
//assertFalse(GROUP_PATTERN.matcher(null).matches()); exception!
assertFalse(GROUP_PATTERN.matcher("").matches());
assertFalse(GROUP_PATTERN.matcher(" ").matches());
assertFalse(GROUP_PATTERN.matcher("test group").matches());
assertTrue(GROUP_PATTERN.matcher("test-group").matches());
}
}```
|
Please help me generate a test for this class.
|
```package com.xiaojukeji.carrera.consumer.thrift.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.util.regex.Pattern;
public class CarreraConfig implements Cloneable, Serializable {
private static final long serialVersionUID = 3661212922184986125L;
private static final Logger LOGGER = LoggerFactory.getLogger(CarreraConfig.class);
public static int TIMEOUT = 5000;
public static int RETRY_INTERVAL = 50;
public static int SUBMIT_MAX_RETRIES = 3;
public static int MAX_BATCH_SIZE = 8;
public static int MAX_LINGER_TIME = 50;
static final Pattern GROUP_PATTERN = Pattern.compile("^[%|a-zA-Z0-9_-]+$");
static final Pattern SERVERS_PATTERN = Pattern.compile("^[\\d.:;]+$");
//ๆถ่ดน็ปๅ็งฐ
private String groupId;
//configs, could be updated by carrera service discovery
//!!!!add or delete need update the module about carrera service discovery
//clientๅproxy server็่ถ
ๆถๆถ้ด, ่ฆๅคงไบmaxLingerTime
private int timeout = TIMEOUT;
//ๆๅๆถๆฏๅคฑ่ดฅๆถ็ๅปถ่ฟ้่ฏ้ด้
private int retryInterval = RETRY_INTERVAL;
//ๆไบคๆถ่ดน็ถๆ็ๆๅคง้่ฏๆฌกๆฐ
private int submitMaxRetries = SUBMIT_MAX_RETRIES;
//ไธๆฌกๆๅ่ฝ่ทๅๅฐ็ๆๅคงๆถๆฏๆกๆฐ๏ผๆๅก็ซฏๆ นๆฎๆญคๅผๅๆๅก็ซฏ็้
็ฝฎ๏ผๅๆๅฐๅผ
private int maxBatchSize = MAX_BATCH_SIZE;
//ๆๅๆถๆฏๆถ๏ผๅจๆๅก็ซฏ็ญๅพ
ๆถๆฏ็ๆ้ฟๆถ้ด
private int maxLingerTime = MAX_LINGER_TIME;
//configs, report but could not be updated by carrera service discovery
//proxyๅ่กจ,ๆฌๅฐ้
็ฝฎproxyๆถๅฟ
่ฆๅๆฐ๏ผไฝฟ็จๆๅกๅ็ฐๆถ,ๅฆๆๆๅกๅ็ฐ่ทๅIP listๅคฑ่ดฅ๏ผๅไผไฝฟ็จๆญคlistไฝไธบ้ป่ฎค้
็ฝฎ
private String servers = null;
public CarreraConfig() {
}
public CarreraConfig(String groupId, String servers) {
this.groupId = groupId;
this.servers = servers;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public int getRetryInterval() {
return retryInterval;
}
public void setRetryInterval(int retryInterval) {
this.retryInterval = retryInterval;
}
public int getSubmitMaxRetries() {
return submitMaxRetries;
}
public void setSubmitMaxRetries(int submitMaxRetries) {
this.submitMaxRetries = submitMaxRetries;
}
public int getMaxBatchSize() {
return maxBatchSize;
}
public void setMaxBatchSize(int maxBatchSize) {
this.maxBatchSize = maxBatchSize;
}
public int getMaxLingerTime() {
return maxLingerTime;
}
public void setMaxLingerTime(int maxLingerTime) {
this.maxLingerTime = maxLingerTime;
}
public String getServers() {
return servers;
}
public void setServers(String servers) {
this.servers = servers;
}
@Override
public String toString() {
return "CarreraConfig{" +
"groupId='" + groupId + '\'' +
", timeout=" + timeout +
", retryInterval=" + retryInterval +
", submitMaxRetries=" + submitMaxRetries +
", maxBatchSize=" + maxBatchSize +
", maxLingerTime=" + maxLingerTime +
", servers='" + servers + '\'' +
'}';
}
@Override
public CarreraConfig clone() {
CarreraConfig config = new CarreraConfig();
config.groupId = this.groupId;
config.servers = this.servers;
config.timeout = this.timeout;
config.retryInterval = this.retryInterval;
config.submitMaxRetries = this.submitMaxRetries;
config.maxBatchSize = this.maxBatchSize;
config.maxLingerTime = this.maxLingerTime;
return config;
}
public void validate(boolean singleServer) {
if (groupId == null || !GROUP_PATTERN.matcher(groupId).matches()) {
throw new CarreraConfigError("Invalid groupId : " + groupId);
}
if (servers == null || !SERVERS_PATTERN.matcher(servers).matches()) {
throw new CarreraConfigError("Invalid servers : " + servers);
}
if (singleServer && servers.contains(";")) {
throw new CarreraConfigError("Invalid single server : " + servers);
}
if (timeout < 0) throw new CarreraConfigError("Invalid timeout : " + timeout);
if (retryInterval <= 0) throw new CarreraConfigError("Invalid retryInterval : " + retryInterval);
if (submitMaxRetries <= 0) throw new CarreraConfigError("Invalid submitMaxRetries : " + submitMaxRetries);
if (maxBatchSize <= 0) throw new CarreraConfigError("Invalid maxBatchSize : " + maxBatchSize);
if (maxLingerTime < 0) throw new CarreraConfigError("Invalid maxLingerTime : " + maxLingerTime);
if (timeout < maxLingerTime || maxLingerTime * 2 > timeout)
throw new CarreraConfigError("timeout must be more than 2 times maxLingerTime, timeout=" + timeout + ",maxLingerTime=" + maxLingerTime);
}
public static class CarreraConfigError extends RuntimeException {
public CarreraConfigError(String message) {
super(message);
}
}
}```
|
```package org.apache.rocketmq.tools.command.offset;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.impl.MQClientAPIImpl;
import org.apache.rocketmq.client.impl.MQClientManager;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.common.protocol.route.BrokerData;
import org.apache.rocketmq.common.protocol.route.QueueData;
import org.apache.rocketmq.common.protocol.route.TopicRouteData;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExtImpl;
import org.apache.rocketmq.tools.command.SubCommandException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ResetOffsetByTimeCommandTest {
private static DefaultMQAdminExt defaultMQAdminExt;
private static DefaultMQAdminExtImpl defaultMQAdminExtImpl;
private static MQClientInstance mqClientInstance = MQClientManager.getInstance().getAndCreateMQClientInstance(new ClientConfig());
private static MQClientAPIImpl mQClientAPIImpl;
@BeforeClass
public static void init() throws NoSuchFieldException, IllegalAccessException, InterruptedException, RemotingException, MQClientException, MQBrokerException {
mQClientAPIImpl = mock(MQClientAPIImpl.class);
defaultMQAdminExt = new DefaultMQAdminExt();
defaultMQAdminExtImpl = new DefaultMQAdminExtImpl(defaultMQAdminExt, 1000);
Field field = DefaultMQAdminExtImpl.class.getDeclaredField("mqClientInstance");
field.setAccessible(true);
field.set(defaultMQAdminExtImpl, mqClientInstance);
field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
field.setAccessible(true);
field.set(mqClientInstance, mQClientAPIImpl);
field = DefaultMQAdminExt.class.getDeclaredField("defaultMQAdminExtImpl");
field.setAccessible(true);
field.set(defaultMQAdminExt, defaultMQAdminExtImpl);
TopicRouteData topicRouteData = new TopicRouteData();
List<BrokerData> brokerDatas = new ArrayList<>();
HashMap<Long, String> brokerAddrs = new HashMap<>();
brokerAddrs.put(1234l, "127.0.0.1:10911");
BrokerData brokerData = new BrokerData();
brokerData.setCluster("default-cluster");
brokerData.setBrokerName("default-broker");
brokerData.setBrokerAddrs(brokerAddrs);
brokerDatas.add(brokerData);
topicRouteData.setBrokerDatas(brokerDatas);
topicRouteData.setQueueDatas(new ArrayList<QueueData>());
topicRouteData.setFilterServerTable(new HashMap<String, List<String>>());
when(mQClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(topicRouteData);
Map<MessageQueue, Long> messageQueueLongMap = new HashMap<>();
when(mQClientAPIImpl.invokeBrokerToResetOffset(anyString(), anyString(), anyString(), anyLong(), anyBoolean(), anyLong())).thenReturn(messageQueueLongMap);
}
@AfterClass
public static void terminate() {
defaultMQAdminExt.shutdown();
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
ResetOffsetByTimeCommand cmd = new ResetOffsetByTimeCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-g default-group", "-t unit-test", "-s 1412131213231", "-f false"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.tools.command.offset;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.common.protocol.ResponseCode;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.command.SubCommand;
import org.apache.rocketmq.tools.command.SubCommandException;
public class ResetOffsetByTimeCommand implements SubCommand {
@Override
public String commandName() {
return "resetOffsetByTime";
}
@Override
public String commandDesc() {
return "Reset consumer offset by timestamp(without client restart).";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("g", "group", true, "set the consumer group");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("t", "topic", true, "set the topic");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("s", "timestamp", true, "set the timestamp[now|currentTimeMillis|yyyy-MM-dd#HH:mm:ss:SSS]");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("f", "force", true, "set the force rollback by timestamp switch[true|false]");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("c", "cplus", false, "reset c++ client offset");
opt.setRequired(false);
options.addOption(opt);
return options;
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
String group = commandLine.getOptionValue("g").trim();
String topic = commandLine.getOptionValue("t").trim();
String timeStampStr = commandLine.getOptionValue("s").trim();
long timestamp = timeStampStr.equals("now") ? System.currentTimeMillis() : 0;
try {
if (timestamp == 0) {
timestamp = Long.parseLong(timeStampStr);
}
} catch (NumberFormatException e) {
timestamp = UtilAll.parseDate(timeStampStr, UtilAll.YYYY_MM_DD_HH_MM_SS_SSS).getTime();
}
boolean force = true;
if (commandLine.hasOption('f')) {
force = Boolean.valueOf(commandLine.getOptionValue("f").trim());
}
boolean isC = false;
if (commandLine.hasOption('c')) {
isC = true;
}
defaultMQAdminExt.start();
Map<MessageQueue, Long> offsetTable;
try {
offsetTable = defaultMQAdminExt.resetOffsetByTimestamp(topic, group, timestamp, force, isC);
} catch (MQClientException e) {
if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) {
ResetOffsetByTimeOldCommand.resetOffset(defaultMQAdminExt, group, topic, timestamp, force, timeStampStr);
return;
}
throw e;
}
System.out.printf("rollback consumer offset by specified group[%s], topic[%s], force[%s], timestamp(string)[%s], timestamp(long)[%s]%n",
group, topic, force, timeStampStr, timestamp);
System.out.printf("%-40s %-40s %-40s%n",
"#brokerName",
"#queueId",
"#offset");
Iterator<Map.Entry<MessageQueue, Long>> iterator = offsetTable.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<MessageQueue, Long> entry = iterator.next();
System.out.printf("%-40s %-40d %-40d%n",
UtilAll.frontStringAtLeast(entry.getKey().getBrokerName(), 32),
entry.getKey().getQueueId(),
entry.getValue());
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
}
```
|
```package com.xiaojukeji.carrera.consumer.thrift.client.util;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class VersionUtilsTest {
@Test
public void getVersion() throws Exception {
assertTrue(VersionUtils.getVersion().matches("java_([\\d.]+)([-]?)([\\w]*)"));
}
}```
|
Please help me generate a test for this class.
|
```package com.xiaojukeji.carrera.consumer.thrift.client.util;
import org.slf4j.Logger;
import java.util.Properties;
import static org.slf4j.LoggerFactory.getLogger;
public class VersionUtils {
public static final Logger LOGGER = getLogger(VersionUtils.class);
private static String version = "java";
static {
Properties properties = new Properties();
try {
properties.load(VersionUtils.class.getClassLoader().getResourceAsStream("carrera_consumer_sdk_version.properties"));
if (!properties.isEmpty()) {
version = properties.getProperty("version");
}
} catch (Exception e) {
LOGGER.warn("get carrera_consumer_sdk_version failed", e);
}
}
public static String getVersion() {
return version;
}
}```
|
```package org.apache.rocketmq.test.sendresult;
public class SendResult {
private boolean sendResult = false;
private String msgId = null;
private Exception sendException = null;
private String brokerIp = null;
public String getBrokerIp() {
return brokerIp;
}
public void setBrokerIp(String brokerIp) {
this.brokerIp = brokerIp;
}
public boolean isSendResult() {
return sendResult;
}
public void setSendResult(boolean sendResult) {
this.sendResult = sendResult;
}
public String getMsgId() {
return msgId;
}
public void setMsgId(String msgId) {
this.msgId = msgId;
}
public Exception getSendException() {
return sendException;
}
public void setSendException(Exception sendException) {
this.sendException = sendException;
}
@Override
public String toString() {
return String.format("sendstatus:%s msgId:%s", sendResult, msgId);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.client.producer;
public class TransactionSendResult extends SendResult {
private LocalTransactionState localTransactionState;
public TransactionSendResult() {
}
public LocalTransactionState getLocalTransactionState() {
return localTransactionState;
}
public void setLocalTransactionState(LocalTransactionState localTransactionState) {
this.localTransactionState = localTransactionState;
}
}
```
|
```package org.apache.rocketmq.common;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class BrokerConfigTest {
@Test
public void testConsumerFallBehindThresholdOverflow() {
long expect = 1024L * 1024 * 1024 * 16;
assertThat(new BrokerConfig().getConsumerFallbehindThreshold()).isEqualTo(expect);
}
}```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.common;
import org.apache.rocketmq.common.annotation.ImportantField;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.common.constant.PermName;
import org.apache.rocketmq.remoting.common.RemotingUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class BrokerConfig {
private static final Logger log = LoggerFactory.getLogger(LoggerName.COMMON_LOGGER_NAME);
private String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));
@ImportantField
private String namesrvAddr = System.getProperty(MixAll.NAMESRV_ADDR_PROPERTY, System.getenv(MixAll.NAMESRV_ADDR_ENV));
@ImportantField
private String brokerIP1 = RemotingUtil.getLocalAddress();
private String brokerIP2 = RemotingUtil.getLocalAddress();
@ImportantField
private String brokerName = localHostName();
@ImportantField
private String brokerClusterName = "DefaultCluster";
@ImportantField
private volatile long brokerId = MixAll.MASTER_ID;
private int brokerPermission = PermName.PERM_READ | PermName.PERM_WRITE;
private int defaultTopicQueueNums = 8;
@ImportantField
private boolean autoCreateTopicEnable = true;
private boolean clusterTopicEnable = true;
private boolean brokerTopicEnable = true;
@ImportantField
private boolean autoCreateSubscriptionGroup = true;
private String messageStorePlugIn = "";
private String zkPath = "";
private boolean metricReportEnable = true;
private String metricNs = "";
private String metricNsFilter = ".server";
private boolean roleConfigInit = false;
/**
* thread numbers for send message thread pool, since spin lock will be used by default since 4.0.x, the default
* value is 1.
*/
private int sendMessageThreadPoolNums = 1; //16 + Runtime.getRuntime().availableProcessors() * 4;
private int pullMessageThreadPoolNums = 16 + Runtime.getRuntime().availableProcessors() * 2;
private int queryMessageThreadPoolNums = 8 + Runtime.getRuntime().availableProcessors();
private int adminBrokerThreadPoolNums = 16;
private int clientManageThreadPoolNums = 32;
private int consumerManageThreadPoolNums = 32;
private int flushConsumerOffsetInterval = 1000 * 5;
private int flushConsumerOffsetHistoryInterval = 1000 * 60;
@ImportantField
private boolean rejectTransactionMessage = false;
@ImportantField
private boolean fetchNamesrvAddrByAddressServer = false;
private int sendThreadPoolQueueCapacity = 10000;
private int pullThreadPoolQueueCapacity = 100000;
private int queryThreadPoolQueueCapacity = 20000;
private int clientManagerThreadPoolQueueCapacity = 1000000;
private int consumerManagerThreadPoolQueueCapacity = 1000000;
private int filterServerNums = 0;
private boolean longPollingEnable = true;
private long shortPollingTimeMills = 1000;
private boolean notifyConsumerIdsChangedEnable = true;
private boolean highSpeedMode = false;
private boolean commercialEnable = true;
private int commercialTimerCount = 1;
private int commercialTransCount = 1;
private int commercialBigCount = 1;
private int commercialBaseCount = 1;
private boolean transferMsgByHeap = true;
private int maxDelayTime = 40;
private String regionId = MixAll.DEFAULT_TRACE_REGION_ID;
private int registerBrokerTimeoutMills = 6000;
private boolean slaveReadEnable = false;
private boolean disableConsumeIfConsumerReadSlowly = false;
private long consumerFallbehindThreshold = 1024L * 1024 * 1024 * 16;
private boolean brokerFastFailureEnable = true;
private long waitTimeMillsInSendQueue = 200;
private long waitTimeMillsInPullQueue = 5 * 1000;
private long startAcceptSendRequestTimeStamp = 0L;
private boolean traceOn = true;
// Switch of filter bit map calculation.
// If switch on:
// 1. Calculate filter bit map when construct queue.
// 2. Filter bit map will be saved to consume queue extend file if allowed.
private boolean enableCalcFilterBitMap = false;
// Expect num of consumers will use filter.
private int expectConsumerNumUseFilter = 32;
// Error rate of bloom filter, 1~100.
private int maxErrorRateOfBloomFilter = 20;
//how long to clean filter data after dead.Default: 24h
private long filterDataCleanTimeSpan = 24 * 3600 * 1000;
// whether do filter when retry.
private boolean filterSupportRetry = false;
private boolean enablePropertyFilter = false;
public boolean isTraceOn() {
return traceOn;
}
public void setTraceOn(final boolean traceOn) {
this.traceOn = traceOn;
}
public long getStartAcceptSendRequestTimeStamp() {
return startAcceptSendRequestTimeStamp;
}
public void setStartAcceptSendRequestTimeStamp(final long startAcceptSendRequestTimeStamp) {
this.startAcceptSendRequestTimeStamp = startAcceptSendRequestTimeStamp;
}
public long getWaitTimeMillsInSendQueue() {
return waitTimeMillsInSendQueue;
}
public void setWaitTimeMillsInSendQueue(final long waitTimeMillsInSendQueue) {
this.waitTimeMillsInSendQueue = waitTimeMillsInSendQueue;
}
public long getConsumerFallbehindThreshold() {
return consumerFallbehindThreshold;
}
public void setConsumerFallbehindThreshold(final long consumerFallbehindThreshold) {
this.consumerFallbehindThreshold = consumerFallbehindThreshold;
}
public boolean isBrokerFastFailureEnable() {
return brokerFastFailureEnable;
}
public void setBrokerFastFailureEnable(final boolean brokerFastFailureEnable) {
this.brokerFastFailureEnable = brokerFastFailureEnable;
}
public long getWaitTimeMillsInPullQueue() {
return waitTimeMillsInPullQueue;
}
public void setWaitTimeMillsInPullQueue(final long waitTimeMillsInPullQueue) {
this.waitTimeMillsInPullQueue = waitTimeMillsInPullQueue;
}
public boolean isDisableConsumeIfConsumerReadSlowly() {
return disableConsumeIfConsumerReadSlowly;
}
public void setDisableConsumeIfConsumerReadSlowly(final boolean disableConsumeIfConsumerReadSlowly) {
this.disableConsumeIfConsumerReadSlowly = disableConsumeIfConsumerReadSlowly;
}
public boolean isSlaveReadEnable() {
return slaveReadEnable;
}
public void setSlaveReadEnable(final boolean slaveReadEnable) {
this.slaveReadEnable = slaveReadEnable;
}
public static String localHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
log.error("Failed to obtain the host name", e);
}
return "DEFAULT_BROKER";
}
public int getRegisterBrokerTimeoutMills() {
return registerBrokerTimeoutMills;
}
public void setRegisterBrokerTimeoutMills(final int registerBrokerTimeoutMills) {
this.registerBrokerTimeoutMills = registerBrokerTimeoutMills;
}
public String getRegionId() {
return regionId;
}
public void setRegionId(final String regionId) {
this.regionId = regionId;
}
public boolean isTransferMsgByHeap() {
return transferMsgByHeap;
}
public void setTransferMsgByHeap(final boolean transferMsgByHeap) {
this.transferMsgByHeap = transferMsgByHeap;
}
public String getMessageStorePlugIn() {
return messageStorePlugIn;
}
public void setMessageStorePlugIn(String messageStorePlugIn) {
this.messageStorePlugIn = messageStorePlugIn;
}
public boolean isHighSpeedMode() {
return highSpeedMode;
}
public void setHighSpeedMode(final boolean highSpeedMode) {
this.highSpeedMode = highSpeedMode;
}
public String getRocketmqHome() {
return rocketmqHome;
}
public void setRocketmqHome(String rocketmqHome) {
this.rocketmqHome = rocketmqHome;
}
public String getBrokerName() {
return brokerName;
}
public void setBrokerName(String brokerName) {
this.brokerName = brokerName;
}
public int getBrokerPermission() {
return brokerPermission;
}
public void setBrokerPermission(int brokerPermission) {
this.brokerPermission = brokerPermission;
}
public int getDefaultTopicQueueNums() {
return defaultTopicQueueNums;
}
public void setDefaultTopicQueueNums(int defaultTopicQueueNums) {
this.defaultTopicQueueNums = defaultTopicQueueNums;
}
public boolean isAutoCreateTopicEnable() {
return autoCreateTopicEnable;
}
public void setAutoCreateTopicEnable(boolean autoCreateTopic) {
this.autoCreateTopicEnable = autoCreateTopic;
}
public String getBrokerClusterName() {
return brokerClusterName;
}
public void setBrokerClusterName(String brokerClusterName) {
this.brokerClusterName = brokerClusterName;
}
public String getBrokerIP1() {
return brokerIP1;
}
public void setBrokerIP1(String brokerIP1) {
this.brokerIP1 = brokerIP1;
}
public String getBrokerIP2() {
return brokerIP2;
}
public void setBrokerIP2(String brokerIP2) {
this.brokerIP2 = brokerIP2;
}
public int getSendMessageThreadPoolNums() {
return sendMessageThreadPoolNums;
}
public void setSendMessageThreadPoolNums(int sendMessageThreadPoolNums) {
this.sendMessageThreadPoolNums = sendMessageThreadPoolNums;
}
public int getPullMessageThreadPoolNums() {
return pullMessageThreadPoolNums;
}
public void setPullMessageThreadPoolNums(int pullMessageThreadPoolNums) {
this.pullMessageThreadPoolNums = pullMessageThreadPoolNums;
}
public int getQueryMessageThreadPoolNums() {
return queryMessageThreadPoolNums;
}
public void setQueryMessageThreadPoolNums(final int queryMessageThreadPoolNums) {
this.queryMessageThreadPoolNums = queryMessageThreadPoolNums;
}
public int getAdminBrokerThreadPoolNums() {
return adminBrokerThreadPoolNums;
}
public void setAdminBrokerThreadPoolNums(int adminBrokerThreadPoolNums) {
this.adminBrokerThreadPoolNums = adminBrokerThreadPoolNums;
}
public int getFlushConsumerOffsetInterval() {
return flushConsumerOffsetInterval;
}
public void setFlushConsumerOffsetInterval(int flushConsumerOffsetInterval) {
this.flushConsumerOffsetInterval = flushConsumerOffsetInterval;
}
public int getFlushConsumerOffsetHistoryInterval() {
return flushConsumerOffsetHistoryInterval;
}
public void setFlushConsumerOffsetHistoryInterval(int flushConsumerOffsetHistoryInterval) {
this.flushConsumerOffsetHistoryInterval = flushConsumerOffsetHistoryInterval;
}
public boolean isClusterTopicEnable() {
return clusterTopicEnable;
}
public void setClusterTopicEnable(boolean clusterTopicEnable) {
this.clusterTopicEnable = clusterTopicEnable;
}
public String getNamesrvAddr() {
return namesrvAddr;
}
public void setNamesrvAddr(String namesrvAddr) {
this.namesrvAddr = namesrvAddr;
}
public long getBrokerId() {
return brokerId;
}
public void setBrokerId(long brokerId) {
this.brokerId = brokerId;
}
public boolean isAutoCreateSubscriptionGroup() {
return autoCreateSubscriptionGroup;
}
public void setAutoCreateSubscriptionGroup(boolean autoCreateSubscriptionGroup) {
this.autoCreateSubscriptionGroup = autoCreateSubscriptionGroup;
}
public boolean isRejectTransactionMessage() {
return rejectTransactionMessage;
}
public void setRejectTransactionMessage(boolean rejectTransactionMessage) {
this.rejectTransactionMessage = rejectTransactionMessage;
}
public boolean isFetchNamesrvAddrByAddressServer() {
return fetchNamesrvAddrByAddressServer;
}
public void setFetchNamesrvAddrByAddressServer(boolean fetchNamesrvAddrByAddressServer) {
this.fetchNamesrvAddrByAddressServer = fetchNamesrvAddrByAddressServer;
}
public int getSendThreadPoolQueueCapacity() {
return sendThreadPoolQueueCapacity;
}
public void setSendThreadPoolQueueCapacity(int sendThreadPoolQueueCapacity) {
this.sendThreadPoolQueueCapacity = sendThreadPoolQueueCapacity;
}
public int getPullThreadPoolQueueCapacity() {
return pullThreadPoolQueueCapacity;
}
public void setPullThreadPoolQueueCapacity(int pullThreadPoolQueueCapacity) {
this.pullThreadPoolQueueCapacity = pullThreadPoolQueueCapacity;
}
public int getQueryThreadPoolQueueCapacity() {
return queryThreadPoolQueueCapacity;
}
public void setQueryThreadPoolQueueCapacity(final int queryThreadPoolQueueCapacity) {
this.queryThreadPoolQueueCapacity = queryThreadPoolQueueCapacity;
}
public boolean isBrokerTopicEnable() {
return brokerTopicEnable;
}
public void setBrokerTopicEnable(boolean brokerTopicEnable) {
this.brokerTopicEnable = brokerTopicEnable;
}
public int getFilterServerNums() {
return filterServerNums;
}
public void setFilterServerNums(int filterServerNums) {
this.filterServerNums = filterServerNums;
}
public boolean isLongPollingEnable() {
return longPollingEnable;
}
public void setLongPollingEnable(boolean longPollingEnable) {
this.longPollingEnable = longPollingEnable;
}
public boolean isNotifyConsumerIdsChangedEnable() {
return notifyConsumerIdsChangedEnable;
}
public void setNotifyConsumerIdsChangedEnable(boolean notifyConsumerIdsChangedEnable) {
this.notifyConsumerIdsChangedEnable = notifyConsumerIdsChangedEnable;
}
public long getShortPollingTimeMills() {
return shortPollingTimeMills;
}
public void setShortPollingTimeMills(long shortPollingTimeMills) {
this.shortPollingTimeMills = shortPollingTimeMills;
}
public int getClientManageThreadPoolNums() {
return clientManageThreadPoolNums;
}
public void setClientManageThreadPoolNums(int clientManageThreadPoolNums) {
this.clientManageThreadPoolNums = clientManageThreadPoolNums;
}
public boolean isCommercialEnable() {
return commercialEnable;
}
public void setCommercialEnable(final boolean commercialEnable) {
this.commercialEnable = commercialEnable;
}
public int getCommercialTimerCount() {
return commercialTimerCount;
}
public void setCommercialTimerCount(final int commercialTimerCount) {
this.commercialTimerCount = commercialTimerCount;
}
public int getCommercialTransCount() {
return commercialTransCount;
}
public void setCommercialTransCount(final int commercialTransCount) {
this.commercialTransCount = commercialTransCount;
}
public int getCommercialBigCount() {
return commercialBigCount;
}
public void setCommercialBigCount(final int commercialBigCount) {
this.commercialBigCount = commercialBigCount;
}
public int getMaxDelayTime() {
return maxDelayTime;
}
public void setMaxDelayTime(final int maxDelayTime) {
this.maxDelayTime = maxDelayTime;
}
public int getClientManagerThreadPoolQueueCapacity() {
return clientManagerThreadPoolQueueCapacity;
}
public void setClientManagerThreadPoolQueueCapacity(int clientManagerThreadPoolQueueCapacity) {
this.clientManagerThreadPoolQueueCapacity = clientManagerThreadPoolQueueCapacity;
}
public int getConsumerManagerThreadPoolQueueCapacity() {
return consumerManagerThreadPoolQueueCapacity;
}
public void setConsumerManagerThreadPoolQueueCapacity(int consumerManagerThreadPoolQueueCapacity) {
this.consumerManagerThreadPoolQueueCapacity = consumerManagerThreadPoolQueueCapacity;
}
public int getConsumerManageThreadPoolNums() {
return consumerManageThreadPoolNums;
}
public void setConsumerManageThreadPoolNums(int consumerManageThreadPoolNums) {
this.consumerManageThreadPoolNums = consumerManageThreadPoolNums;
}
public int getCommercialBaseCount() {
return commercialBaseCount;
}
public void setCommercialBaseCount(int commercialBaseCount) {
this.commercialBaseCount = commercialBaseCount;
}
public boolean isEnableCalcFilterBitMap() {
return enableCalcFilterBitMap;
}
public void setEnableCalcFilterBitMap(boolean enableCalcFilterBitMap) {
this.enableCalcFilterBitMap = enableCalcFilterBitMap;
}
public int getExpectConsumerNumUseFilter() {
return expectConsumerNumUseFilter;
}
public void setExpectConsumerNumUseFilter(int expectConsumerNumUseFilter) {
this.expectConsumerNumUseFilter = expectConsumerNumUseFilter;
}
public int getMaxErrorRateOfBloomFilter() {
return maxErrorRateOfBloomFilter;
}
public void setMaxErrorRateOfBloomFilter(int maxErrorRateOfBloomFilter) {
this.maxErrorRateOfBloomFilter = maxErrorRateOfBloomFilter;
}
public long getFilterDataCleanTimeSpan() {
return filterDataCleanTimeSpan;
}
public void setFilterDataCleanTimeSpan(long filterDataCleanTimeSpan) {
this.filterDataCleanTimeSpan = filterDataCleanTimeSpan;
}
public boolean isFilterSupportRetry() {
return filterSupportRetry;
}
public void setFilterSupportRetry(boolean filterSupportRetry) {
this.filterSupportRetry = filterSupportRetry;
}
public boolean isEnablePropertyFilter() {
return enablePropertyFilter;
}
public void setEnablePropertyFilter(boolean enablePropertyFilter) {
this.enablePropertyFilter = enablePropertyFilter;
}
public String getZkPath() {
return zkPath;
}
public void setZkPath(String zkPath) {
this.zkPath = zkPath;
}
public boolean isMetricReportEnable() {
return metricReportEnable;
}
public void setMetricReportEnable(boolean metricReportEnable) {
this.metricReportEnable = metricReportEnable;
}
public String getMetricNs() {
return metricNs;
}
public void setMetricNs(String metricNs) {
this.metricNs = metricNs;
}
public String getMetricNsFilter() {
return metricNsFilter;
}
public void setMetricNsFilter(String metricNsFilter) {
this.metricNsFilter = metricNsFilter;
}
public boolean isRoleConfigInit() {
return roleConfigInit;
}
public void setRoleConfigInit(boolean roleConfigInit) {
this.roleConfigInit = roleConfigInit;
}
}
```
|
```package org.apache.rocketmq.tools.command.broker;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.impl.MQClientAPIImpl;
import org.apache.rocketmq.client.impl.MQClientManager;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.remoting.exception.RemotingConnectException;
import org.apache.rocketmq.remoting.exception.RemotingSendRequestException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExtImpl;
import org.apache.rocketmq.tools.command.SubCommandException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import static org.mockito.Mockito.mock;
public class UpdateBrokerConfigSubCommandTest {
private static DefaultMQAdminExt defaultMQAdminExt;
private static DefaultMQAdminExtImpl defaultMQAdminExtImpl;
private static MQClientInstance mqClientInstance = MQClientManager.getInstance().getAndCreateMQClientInstance(new ClientConfig());
private static MQClientAPIImpl mQClientAPIImpl;
@BeforeClass
public static void init() throws NoSuchFieldException, IllegalAccessException, InterruptedException, RemotingTimeoutException, MQClientException, RemotingSendRequestException, RemotingConnectException, MQBrokerException, UnsupportedEncodingException {
mQClientAPIImpl = mock(MQClientAPIImpl.class);
defaultMQAdminExt = new DefaultMQAdminExt();
defaultMQAdminExtImpl = new DefaultMQAdminExtImpl(defaultMQAdminExt, 1000);
Field field = DefaultMQAdminExtImpl.class.getDeclaredField("mqClientInstance");
field.setAccessible(true);
field.set(defaultMQAdminExtImpl, mqClientInstance);
field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
field.setAccessible(true);
field.set(mqClientInstance, mQClientAPIImpl);
field = DefaultMQAdminExt.class.getDeclaredField("defaultMQAdminExtImpl");
field.setAccessible(true);
field.set(defaultMQAdminExt, defaultMQAdminExtImpl);
}
@AfterClass
public static void terminate() {
defaultMQAdminExt.shutdown();
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
UpdateBrokerConfigSubCommand cmd = new UpdateBrokerConfigSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster", "-k topicname", "-v unit_test"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.tools.command.broker;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.command.CommandUtil;
import org.apache.rocketmq.tools.command.SubCommand;
import org.apache.rocketmq.tools.command.SubCommandException;
public class UpdateBrokerConfigSubCommand implements SubCommand {
@Override
public String commandName() {
return "updateBrokerConfig";
}
@Override
public String commandDesc() {
return "Update broker's config";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("b", "brokerAddr", true, "update which broker");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("c", "clusterName", true, "update which cluster");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("k", "key", true, "config key");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("v", "value", true, "config value");
opt.setRequired(true);
options.addOption(opt);
for (int i = 1; i < 9; i++) {
opt = new Option("k" + i, "key" + i, true, "config key" + i);
opt.setRequired(false);
options.addOption(opt);
opt = new Option("v" + i, "value" + i, true, "config value" + i);
opt.setRequired(false);
options.addOption(opt);
}
return options;
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook, 20 * 1000);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
int index = 0;
Properties properties = new Properties();
while (true) {
String optionKey = index == 0 ? "k" : ("k" + index);
String optionValue = index == 0 ? "v" : ("v" + index);
if (!commandLine.hasOption(optionKey)) {
break;
}
String key = commandLine.getOptionValue(optionKey).trim();
String value = commandLine.getOptionValue(optionValue).trim();
properties.put(key, value);
index++;
}
System.out.printf("properties:%s\n", properties.toString());
if (commandLine.hasOption('b')) {
String brokerAddr = commandLine.getOptionValue('b').trim();
defaultMQAdminExt.start();
defaultMQAdminExt.updateBrokerConfig(brokerAddr, properties);
System.out.printf("update broker config success, broker:%s, config:%s\n", brokerAddr, properties.toString());
return;
} else if (commandLine.hasOption('c')) {
String clusterName = commandLine.getOptionValue('c').trim();
defaultMQAdminExt.start();
Set<String> masterSet =
CommandUtil.fetchMasterAddrByClusterName(defaultMQAdminExt, clusterName);
for (String brokerAddr : masterSet) {
try {
defaultMQAdminExt.updateBrokerConfig(brokerAddr, properties);
System.out.printf("update broker config success, broker:%s, config:%s\n", brokerAddr, properties.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
return;
}
ServerUtil.printCommandLineHelp("mqadmin " + this.commandName(), options);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
}
```
|
```package org.apache.rocketmq.store;
import java.io.File;
import java.io.IOException;
import org.apache.rocketmq.common.UtilAll;
import org.junit.After;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StoreCheckpointTest {
@Test
public void testWriteAndRead() throws IOException {
StoreCheckpoint storeCheckpoint = new StoreCheckpoint("target/checkpoint_test/0000");
long physicMsgTimestamp = 0xAABB;
long logicsMsgTimestamp = 0xCCDD;
storeCheckpoint.setPhysicMsgTimestamp(physicMsgTimestamp);
storeCheckpoint.setLogicsMsgTimestamp(logicsMsgTimestamp);
storeCheckpoint.flush();
long diff = physicMsgTimestamp - storeCheckpoint.getMinTimestamp();
assertThat(diff).isEqualTo(3000);
storeCheckpoint.shutdown();
storeCheckpoint = new StoreCheckpoint("target/checkpoint_test/0000");
assertThat(storeCheckpoint.getPhysicMsgTimestamp()).isEqualTo(physicMsgTimestamp);
assertThat(storeCheckpoint.getLogicsMsgTimestamp()).isEqualTo(logicsMsgTimestamp);
}
@After
public void destory() {
File file = new File("target/checkpoint_test");
UtilAll.deleteFile(file);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.store;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.constant.LoggerName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StoreCheckpoint {
private static final Logger log = LoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME);
private final RandomAccessFile randomAccessFile;
private final FileChannel fileChannel;
private final MappedByteBuffer mappedByteBuffer;
private volatile long physicMsgTimestamp = 0;
private volatile long logicsMsgTimestamp = 0;
private volatile long indexMsgTimestamp = 0;
public StoreCheckpoint(final String scpPath) throws IOException {
File file = new File(scpPath);
MappedFile.ensureDirOK(file.getParent());
boolean fileExists = file.exists();
this.randomAccessFile = new RandomAccessFile(file, "rw");
this.fileChannel = this.randomAccessFile.getChannel();
this.mappedByteBuffer = fileChannel.map(MapMode.READ_WRITE, 0, MappedFile.OS_PAGE_SIZE);
if (fileExists) {
log.info("store checkpoint file exists, " + scpPath);
this.physicMsgTimestamp = this.mappedByteBuffer.getLong(0);
this.logicsMsgTimestamp = this.mappedByteBuffer.getLong(8);
this.indexMsgTimestamp = this.mappedByteBuffer.getLong(16);
log.info("store checkpoint file physicMsgTimestamp " + this.physicMsgTimestamp + ", "
+ UtilAll.timeMillisToHumanString(this.physicMsgTimestamp));
log.info("store checkpoint file logicsMsgTimestamp " + this.logicsMsgTimestamp + ", "
+ UtilAll.timeMillisToHumanString(this.logicsMsgTimestamp));
log.info("store checkpoint file indexMsgTimestamp " + this.indexMsgTimestamp + ", "
+ UtilAll.timeMillisToHumanString(this.indexMsgTimestamp));
} else {
log.info("store checkpoint file not exists, " + scpPath);
}
}
public void shutdown() {
this.flush();
// unmap mappedByteBuffer
MappedFile.clean(this.mappedByteBuffer);
try {
this.fileChannel.close();
} catch (IOException e) {
log.error("Failed to properly close the channel", e);
}
}
public void flush() {
this.mappedByteBuffer.putLong(0, this.physicMsgTimestamp);
this.mappedByteBuffer.putLong(8, this.logicsMsgTimestamp);
this.mappedByteBuffer.putLong(16, this.indexMsgTimestamp);
this.mappedByteBuffer.force();
}
public long getPhysicMsgTimestamp() {
return physicMsgTimestamp;
}
public void setPhysicMsgTimestamp(long physicMsgTimestamp) {
this.physicMsgTimestamp = physicMsgTimestamp;
}
public long getLogicsMsgTimestamp() {
return logicsMsgTimestamp;
}
public void setLogicsMsgTimestamp(long logicsMsgTimestamp) {
this.logicsMsgTimestamp = logicsMsgTimestamp;
}
public long getMinTimestampIndex() {
return Math.min(this.getMinTimestamp(), this.indexMsgTimestamp);
}
public long getMinTimestamp() {
long min = Math.min(this.physicMsgTimestamp, this.logicsMsgTimestamp);
min -= 1000 * 3;
if (min < 0)
min = 0;
return min;
}
public long getIndexMsgTimestamp() {
return indexMsgTimestamp;
}
public void setIndexMsgTimestamp(long indexMsgTimestamp) {
this.indexMsgTimestamp = indexMsgTimestamp;
}
}
```
|
```package org.apache.rocketmq.tools.command.broker;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.Properties;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.impl.MQClientAPIImpl;
import org.apache.rocketmq.client.impl.MQClientManager;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.remoting.exception.RemotingConnectException;
import org.apache.rocketmq.remoting.exception.RemotingSendRequestException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExtImpl;
import org.apache.rocketmq.tools.command.SubCommandException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class GetBrokerConfigCommandTest {
private static DefaultMQAdminExt defaultMQAdminExt;
private static DefaultMQAdminExtImpl defaultMQAdminExtImpl;
private static MQClientInstance mqClientInstance = MQClientManager.getInstance().getAndCreateMQClientInstance(new ClientConfig());
private static MQClientAPIImpl mQClientAPIImpl;
@BeforeClass
public static void init() throws NoSuchFieldException, IllegalAccessException, InterruptedException, RemotingTimeoutException, MQClientException, RemotingSendRequestException, RemotingConnectException, MQBrokerException, UnsupportedEncodingException {
mQClientAPIImpl = mock(MQClientAPIImpl.class);
defaultMQAdminExt = new DefaultMQAdminExt();
defaultMQAdminExtImpl = new DefaultMQAdminExtImpl(defaultMQAdminExt, 1000);
Field field = DefaultMQAdminExtImpl.class.getDeclaredField("mqClientInstance");
field.setAccessible(true);
field.set(defaultMQAdminExtImpl, mqClientInstance);
field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
field.setAccessible(true);
field.set(mqClientInstance, mQClientAPIImpl);
field = DefaultMQAdminExt.class.getDeclaredField("defaultMQAdminExtImpl");
field.setAccessible(true);
field.set(defaultMQAdminExt, defaultMQAdminExtImpl);
Properties properties = new Properties();
properties.setProperty("maxMessageSize", "5000000");
properties.setProperty("flushDelayOffsetInterval", "15000");
properties.setProperty("serverSocketRcvBufSize", "655350");
when(mQClientAPIImpl.getBrokerConfig(anyString(), anyLong())).thenReturn(properties);
}
@AfterClass
public static void terminate() {
defaultMQAdminExt.shutdown();
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
GetBrokerConfigCommand cmd = new GetBrokerConfigCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.tools.command.broker;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.exception.RemotingConnectException;
import org.apache.rocketmq.remoting.exception.RemotingSendRequestException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.admin.MQAdminExt;
import org.apache.rocketmq.tools.command.CommandUtil;
import org.apache.rocketmq.tools.command.SubCommand;
import org.apache.rocketmq.tools.command.SubCommandException;
public class GetBrokerConfigCommand implements SubCommand {
@Override
public String commandName() {
return "getBrokerConfig";
}
@Override
public String commandDesc() {
return "Get broker config by cluster or special broker!";
}
@Override
public Options buildCommandlineOptions(final Options options) {
Option opt = new Option("b", "brokerAddr", true, "update which broker");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("c", "clusterName", true, "update which cluster");
opt.setRequired(false);
options.addOption(opt);
return options;
}
@Override
public void execute(final CommandLine commandLine, final Options options,
final RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
if (commandLine.hasOption('b')) {
String brokerAddr = commandLine.getOptionValue('b').trim();
defaultMQAdminExt.start();
getAndPrint(defaultMQAdminExt,
String.format("============%s============\n", brokerAddr),
brokerAddr);
} else if (commandLine.hasOption('c')) {
String clusterName = commandLine.getOptionValue('c').trim();
defaultMQAdminExt.start();
Map<String, List<String>> masterAndSlaveMap
= CommandUtil.fetchMasterAndSlaveDistinguish(defaultMQAdminExt, clusterName);
for (String masterAddr : masterAndSlaveMap.keySet()) {
getAndPrint(
defaultMQAdminExt,
String.format("============Master: %s============\n", masterAddr),
masterAddr
);
for (String slaveAddr : masterAndSlaveMap.get(masterAddr)) {
getAndPrint(
defaultMQAdminExt,
String.format("============My Master: %s=====Slave: %s============\n", masterAddr, slaveAddr),
slaveAddr
);
}
}
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
protected void getAndPrint(final MQAdminExt defaultMQAdminExt, final String printPrefix, final String addr)
throws InterruptedException, RemotingConnectException,
UnsupportedEncodingException, RemotingTimeoutException,
MQBrokerException, RemotingSendRequestException {
System.out.print(printPrefix);
Properties properties = defaultMQAdminExt.getBrokerConfig(addr);
if (properties == null) {
System.out.printf("Broker[%s] has no config property!\n", addr);
return;
}
for (Object key : properties.keySet()) {
System.out.printf("%-50s= %s\n", key, properties.get(key));
}
System.out.printf("%n");
}
}
```
|
```package org.apache.rocketmq.tools.command.broker;
import java.lang.reflect.Field;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.impl.MQClientAPIImpl;
import org.apache.rocketmq.client.impl.MQClientManager;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.remoting.exception.RemotingConnectException;
import org.apache.rocketmq.remoting.exception.RemotingSendRequestException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExtImpl;
import org.apache.rocketmq.tools.command.SubCommandException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CleanUnusedTopicCommandTest {
private static DefaultMQAdminExt defaultMQAdminExt;
private static DefaultMQAdminExtImpl defaultMQAdminExtImpl;
private static MQClientInstance mqClientInstance = MQClientManager.getInstance().getAndCreateMQClientInstance(new ClientConfig());
private static MQClientAPIImpl mQClientAPIImpl;
@BeforeClass
public static void init() throws NoSuchFieldException, IllegalAccessException, InterruptedException, RemotingTimeoutException, MQClientException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
mQClientAPIImpl = mock(MQClientAPIImpl.class);
defaultMQAdminExt = new DefaultMQAdminExt();
defaultMQAdminExtImpl = new DefaultMQAdminExtImpl(defaultMQAdminExt, 1000);
Field field = DefaultMQAdminExtImpl.class.getDeclaredField("mqClientInstance");
field.setAccessible(true);
field.set(defaultMQAdminExtImpl, mqClientInstance);
field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
field.setAccessible(true);
field.set(mqClientInstance, mQClientAPIImpl);
field = DefaultMQAdminExt.class.getDeclaredField("defaultMQAdminExtImpl");
field.setAccessible(true);
field.set(defaultMQAdminExt, defaultMQAdminExtImpl);
when(mQClientAPIImpl.cleanUnusedTopicByAddr(anyString(), anyLong())).thenReturn(true);
}
@AfterClass
public static void terminate() {
defaultMQAdminExt.shutdown();
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
CleanUnusedTopicCommand cmd = new CleanUnusedTopicCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
}
```
|
Please help me generate a test for this class.
|
```package org.apache.rocketmq.tools.command.broker;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.command.SubCommand;
import org.apache.rocketmq.tools.command.SubCommandException;
public class CleanUnusedTopicCommand implements SubCommand {
@Override
public String commandName() {
return "cleanUnusedTopic";
}
@Override
public String commandDesc() {
return "Clean unused topic on broker.";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("b", "brokerAddr", true, "Broker address");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("c", "cluster", true, "cluster name");
opt.setRequired(false);
options.addOption(opt);
return options;
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
boolean result = false;
defaultMQAdminExt.start();
if (commandLine.hasOption('b')) {
String addr = commandLine.getOptionValue('b').trim();
result = defaultMQAdminExt.cleanUnusedTopicByAddr(addr);
} else {
String cluster = commandLine.getOptionValue('c');
if (null != cluster)
cluster = cluster.trim();
result = defaultMQAdminExt.cleanUnusedTopicByAddr(cluster);
}
System.out.printf(result ? "success" : "false");
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
}
```
|