repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/Param.java | config-magic/src/main/java/org/skife/config/Param.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Param {
String value();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/DataAmountUnit.java | config-magic/src/main/java/org/skife/config/DataAmountUnit.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
public enum DataAmountUnit {
BYTE("B", 1l),
KIBIBYTE("KiB", 1024l),
MEBIBYTE("MiB", 1024l * 1024l),
GIBIBYTE("GiB", 1024l * 1024l * 1024l),
TEBIBYTE("TiB", 1024l * 1024l * 1024l * 1024l),
PEBIBYTE("PiB", 1024l * 1024l * 1024l * 1024l * 1024l),
EXIBYTE("EiB", 1024l * 1024l * 1024l * 1024l * 1024l * 1024l),
KILOBYTE("kB", 1000l),
MEGABYTE("MB", 1000l * 1000l),
GIGABYTE("GB", 1000l * 1000l * 1000l),
TERABYTE("TB", 1000l * 1000l * 1000l * 1000l),
PETABYTE("PB", 1000l * 1000l * 1000l * 1000l * 1000l),
EXABYTE("EB", 1000l * 1000l * 1000l * 1000l * 1000l * 1000l);
private final String symbol;
private final long factor;
DataAmountUnit(final String symbol, final long factor) {
this.symbol = symbol;
this.factor = factor;
}
public static DataAmountUnit fromString(final String text) {
for (final DataAmountUnit unit : DataAmountUnit.values()) {
if (unit.symbol.equals(text)) {
return unit;
}
}
throw new IllegalArgumentException("Unknown unit '" + text + "'");
}
public static DataAmountUnit fromStringCaseInsensitive(final String origText) {
final String text = origText.toLowerCase();
for (final DataAmountUnit unit : DataAmountUnit.values()) {
if (unit.symbol.equals(text)) {
return unit;
}
}
throw new IllegalArgumentException("Unknown unit '" + origText + "'");
}
public String getSymbol() {
return symbol;
}
public long getFactor() {
return factor;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/TimeSpan.java | config-magic/src/main/java/org/skife/config/TimeSpan.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TimeSpan {
private static final Pattern SPLIT = Pattern.compile("^(\\d+)\\s?(\\w+)$");
private static final HashMap<String, TimeUnit> UNITS = new HashMap<String, TimeUnit>();
static {
UNITS.put("ms", TimeUnit.MILLISECONDS);
UNITS.put("millisecond", TimeUnit.MILLISECONDS);
UNITS.put("milliseconds", TimeUnit.MILLISECONDS);
UNITS.put("s", TimeUnit.SECONDS);
UNITS.put("second", TimeUnit.SECONDS);
UNITS.put("seconds", TimeUnit.SECONDS);
UNITS.put("m", TimeUnit.MINUTES);
UNITS.put("min", TimeUnit.MINUTES);
UNITS.put("minute", TimeUnit.MINUTES);
UNITS.put("minutes", TimeUnit.MINUTES);
UNITS.put("h", TimeUnit.HOURS);
UNITS.put("hour", TimeUnit.HOURS);
UNITS.put("hours", TimeUnit.HOURS);
UNITS.put("d", TimeUnit.DAYS);
UNITS.put("day", TimeUnit.DAYS);
UNITS.put("days", TimeUnit.DAYS);
}
private final long period;
private final TimeUnit unit;
private final long millis;
public TimeSpan(final String spec) {
final Matcher m = SPLIT.matcher(spec);
if (!m.matches()) {
throw new IllegalArgumentException(String.format("%s is not a valid time spec", spec));
}
final String number = m.group(1);
final String type = m.group(2);
period = Long.parseLong(number);
unit = UNITS.get(type);
if (unit == null) {
throw new IllegalArgumentException(String.format("%s is not a valid time unit in %s", type, spec));
}
millis = TimeUnit.MILLISECONDS.convert(period, unit);
}
public TimeSpan(final long period, final TimeUnit unit) {
this.period = period;
this.unit = unit;
this.millis = TimeUnit.MILLISECONDS.convert(period, unit);
}
public long getMillis() {
return millis;
}
public long getPeriod() {
return period;
}
public TimeUnit getUnit() {
return unit;
}
@Override
public String toString() {
switch (unit) {
case SECONDS:
return period + "s";
case MINUTES:
return period + "m";
case HOURS:
return period + "h";
case DAYS:
return period + "d";
default:
return period + "ms";
}
}
@Override
public int hashCode() {
return 31 + (int) (millis ^ (millis >>> 32));
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TimeSpan other = (TimeSpan) obj;
return millis == other.millis;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/Description.java | config-magic/src/main/java/org/skife/config/Description.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Description {
String value() default ":nodoc:";
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/DefaultCoercibles.java | config-magic/src/main/java/org/skife/config/DefaultCoercibles.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
final class DefaultCoercibles {
public static final Coercible<?> CASE_INSENSITIVE_ENUM_COERCIBLE = new CaseInsensitiveEnumCoercible();
/**
* A Coercible that accepts any type with a static <code>valueOf(String)</code> method.
*/
static final Coercible<?> VALUE_OF_COERCIBLE = new Coercible<Object>() {
private final Map<Class<?>, Coercer<Object>> coercerMap = new HashMap<Class<?>, Coercer<Object>>();
public Coercer<Object> accept(final Class<?> type) {
if (coercerMap.containsKey(type)) {
// If a key exists, the value always gets returned. If a null value is in the map,
// the type was seen before and deemed not worthy.
return coercerMap.get(type);
}
Coercer<Object> coercer = null;
try {
// Method must be 'static valueOf(String)' and return the type in question.
Method candidate = type.getMethod("valueOf", String.class);
if (!Modifier.isStatic(candidate.getModifiers())) {
// not static.
candidate = null;
} else if (!candidate.getReturnType().isAssignableFrom(type)) {
// does not return the right type.
candidate = null;
}
if (candidate != null) {
final Method valueOfMethod = candidate;
coercer = new Coercer<Object>() {
public Object coerce(final String value) {
try {
return value == null ? null : valueOfMethod.invoke(null, value);
} catch (final Exception e) {
throw convertException(e);
}
}
};
}
} catch (final NoSuchMethodException nsme) {
// Don't do anything, the class does not have a method.
}
coercerMap.put(type, coercer);
return coercer;
}
};
/**
* A Coercible that accepts any type with a c'tor that takes a single string parameter.
*/
static final Coercible<?> STRING_CTOR_COERCIBLE = new Coercible<Object>() {
private final Map<Class<?>, Coercer<Object>> coercerMap = new HashMap<Class<?>, Coercer<Object>>();
public Coercer<Object> accept(final Class<?> type) {
if (coercerMap.containsKey(type)) {
// If a key exists, the value always gets returned. If a null value is in the map,
// the type was seen before and deemed not worthy.
return coercerMap.get(type);
}
Coercer<Object> coercer = null;
try {
final Constructor<?> ctor = type.getConstructor(String.class);
coercer = new Coercer<Object>() {
public Object coerce(final String value) {
try {
return value == null ? null : ctor.newInstance(value);
} catch (final Exception e) {
throw convertException(e);
}
}
};
} catch (final NoSuchMethodException nsme) {
// Don't do anything, the class does not have a matching c'tor
}
coercerMap.put(type, coercer);
return coercer;
}
};
/**
* A Coercible that accepts any type with a c'tor that takes a single Object parameter.
* <p>
* This one was lovingly prepared and added for Jodatime DateTime objects.
*/
static final Coercible<?> OBJECT_CTOR_COERCIBLE = new Coercible<Object>() {
private final Map<Class<?>, Coercer<Object>> coercerMap = new HashMap<Class<?>, Coercer<Object>>();
public Coercer<Object> accept(final Class<?> type) {
if (coercerMap.containsKey(type)) {
// If a key exists, the value always gets returned. If a null value is in the map,
// the type was seen before and deemed not worthy.
return coercerMap.get(type);
}
Coercer<Object> coercer = null;
try {
final Constructor<?> ctor = type.getConstructor(Object.class);
coercer = new Coercer<Object>() {
public Object coerce(final String value) {
try {
return ctor.newInstance(value);
} catch (final Exception e) {
throw convertException(e);
}
}
};
} catch (final NoSuchMethodException nsme) {
// Don't do anything, the class does not have a matching c'tor
}
coercerMap.put(type, coercer);
return coercer;
}
};
static final Coercer<Boolean> BOOLEAN_COERCER = new Coercer<Boolean>() {
@SuppressFBWarnings(value = "NP_BOOLEAN_RETURN_NULL", justification = "Using annotation because cannot excluded via xml")
public Boolean coerce(final String value) {
return value != null ? Boolean.valueOf(value) : null;
}
};
static final Coercible<Boolean> BOOLEAN_COERCIBLE = new Coercible<Boolean>() {
public Coercer<Boolean> accept(final Class<?> clazz) {
if (Boolean.class.isAssignableFrom(clazz) || Boolean.TYPE.isAssignableFrom(clazz)) {
return DefaultCoercibles.BOOLEAN_COERCER;
}
return null;
}
};
static final Coercer<Byte> BYTE_COERCER = new Coercer<Byte>() {
public Byte coerce(final String value) {
return value != null ? Byte.valueOf(value) : null;
}
};
static final Coercible<Byte> BYTE_COERCIBLE = new Coercible<Byte>() {
public Coercer<Byte> accept(final Class<?> clazz) {
if (Byte.class.isAssignableFrom(clazz) || Byte.TYPE.isAssignableFrom(clazz)) {
return DefaultCoercibles.BYTE_COERCER;
}
return null;
}
};
static final Coercer<Short> SHORT_COERCER = new Coercer<Short>() {
public Short coerce(final String value) {
return value != null ? Short.valueOf(value) : null;
}
};
static final Coercible<Short> SHORT_COERCIBLE = new Coercible<Short>() {
public Coercer<Short> accept(final Class<?> clazz) {
if (Short.class.isAssignableFrom(clazz) || Short.TYPE.isAssignableFrom(clazz)) {
return DefaultCoercibles.SHORT_COERCER;
}
return null;
}
};
static final Coercer<Integer> INTEGER_COERCER = new Coercer<Integer>() {
public Integer coerce(final String value) {
return value != null ? Integer.valueOf(value) : null;
}
};
static final Coercible<Integer> INTEGER_COERCIBLE = new Coercible<Integer>() {
public Coercer<Integer> accept(final Class<?> clazz) {
if (Integer.class.isAssignableFrom(clazz) || Integer.TYPE.isAssignableFrom(clazz)) {
return DefaultCoercibles.INTEGER_COERCER;
}
return null;
}
};
static final Coercer<Long> LONG_COERCER = new Coercer<Long>() {
public Long coerce(final String value) {
return value != null ? Long.valueOf(value) : null;
}
};
static final Coercible<Long> LONG_COERCIBLE = new Coercible<Long>() {
public Coercer<Long> accept(final Class<?> clazz) {
if (Long.class.isAssignableFrom(clazz) || Long.TYPE.isAssignableFrom(clazz)) {
return DefaultCoercibles.LONG_COERCER;
}
return null;
}
};
static final Coercer<Float> FLOAT_COERCER = new Coercer<Float>() {
public Float coerce(final String value) {
return value != null ? Float.valueOf(value) : null;
}
};
static final Coercible<Float> FLOAT_COERCIBLE = new Coercible<Float>() {
public Coercer<Float> accept(final Class<?> clazz) {
if (Float.class.isAssignableFrom(clazz) || Float.TYPE.isAssignableFrom(clazz)) {
return DefaultCoercibles.FLOAT_COERCER;
}
return null;
}
};
static final Coercer<Double> DOUBLE_COERCER = new Coercer<Double>() {
public Double coerce(final String value) {
return value != null ? Double.valueOf(value) : null;
}
};
static final Coercible<Double> DOUBLE_COERCIBLE = new Coercible<Double>() {
public Coercer<Double> accept(final Class<?> clazz) {
if (Double.class.isAssignableFrom(clazz) || Double.TYPE.isAssignableFrom(clazz)) {
return DefaultCoercibles.DOUBLE_COERCER;
}
return null;
}
};
static final Coercer<String> STRING_COERCER = new Coercer<String>() {
public String coerce(final String value) {
return value;
}
};
static final Coercible<String> STRING_COERCIBLE = new Coercible<String>() {
public Coercer<String> accept(final Class<?> clazz) {
if (String.class.equals(clazz)) {
return DefaultCoercibles.STRING_COERCER;
}
return null;
}
};
static final Coercer<URI> URI_COERCER = new Coercer<URI>() {
public URI coerce(final String value) {
return value != null ? URI.create(value) : null;
}
};
static final Coercible<URI> URI_COERCIBLE = new Coercible<URI>() {
public Coercer<URI> accept(final Class<?> clazz) {
if (URI.class.equals(clazz)) {
return DefaultCoercibles.URI_COERCER;
}
return null;
}
};
private DefaultCoercibles() {
}
public static final RuntimeException convertException(final Throwable t) {
if (t instanceof RuntimeException) {
return (RuntimeException) t;
} else if (t instanceof InvocationTargetException) {
return convertException(((InvocationTargetException) t).getTargetException());
} else {
return new RuntimeException(t);
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/ConfigSource.java | config-magic/src/main/java/org/skife/config/ConfigSource.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
public interface ConfigSource {
String getString(String propertyName);
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/clock/src/test/java/org/killbill/clock/TestClockMock.java | clock/src/test/java/org/killbill/clock/TestClockMock.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.clock;
import org.testng.annotations.Test;
public class TestClockMock extends TestClockMockBase {
@Test(groups = "fast")
public void testBasicClockOperations() throws Exception {
final ClockMock clock = new ClockMock();
testBasicClockOperations(clock);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/clock/src/test/java/org/killbill/clock/ClockMock.java | clock/src/test/java/org/killbill/clock/ClockMock.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.clock;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.Months;
import org.joda.time.Period;
import org.joda.time.ReadablePeriod;
import org.joda.time.Weeks;
import org.joda.time.Years;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClockMock implements Clock {
private static final Logger log = LoggerFactory.getLogger(ClockMock.class);
private DateTime mockDateTimeUTC;
private long initialDeltaMillis;
public ClockMock() {
reset();
}
@Override
public synchronized DateTime getNow(final DateTimeZone tz) {
return getUTCNow().toDateTime(tz);
}
@Override
public synchronized DateTime getUTCNow() {
return truncate(getReferenceDateTimeUTC().plus(System.currentTimeMillis() - initialDeltaMillis));
}
@Override
public LocalDate getUTCToday() {
return getToday(DateTimeZone.UTC);
}
@Override
public LocalDate getToday(final DateTimeZone timeZone) {
return new LocalDate(getUTCNow(), timeZone);
}
@Override
public String toString() {
return getUTCNow().toString();
}
public synchronized void addDays(final int days) {
adjustTo(Days.days(days));
}
public synchronized void addWeeks(final int weeks) {
adjustTo(Weeks.weeks(weeks));
}
public synchronized void addMonths(final int months) {
adjustTo(Months.months(months));
}
public synchronized void addYears(final int years) {
adjustTo(Years.years(years));
}
public synchronized void setDeltaFromReality(final long delta) {
// The name of the method is misleading - don't reset it here
addDeltaFromReality(delta);
}
public synchronized void addDeltaFromReality(final long delta) {
adjustTo(new Period(delta));
}
public synchronized void setDay(final LocalDate date) {
setTime(date.toDateTimeAtStartOfDay(DateTimeZone.UTC));
}
public synchronized void setTime(final DateTime time) {
final DateTime prev = getUTCNow();
reset(time);
logChange(prev);
}
public synchronized void resetDeltaFromReality() {
final DateTime prev = getUTCNow();
reset();
logChange(prev);
}
protected synchronized void reset() {
reset(realNow());
}
private void reset(final DateTime timeInAnyTimeZone) {
setReferenceDateTimeUTC(timeInAnyTimeZone.toDateTime(DateTimeZone.UTC));
initialDeltaMillis = System.currentTimeMillis();
}
private void adjustTo(final ReadablePeriod period) {
final DateTime prev = getUTCNow();
setReferenceDateTimeUTC(getReferenceDateTimeUTC().plus(period));
logChange(prev);
}
private void logChange(final DateTime prev) {
final DateTime now = getUTCNow();
log.info(String.format(" ************ ADJUSTING CLOCK FROM %s to %s ********************", prev, now));
}
private DateTime truncate(final DateTime time) {
return time.minus(time.getMillisOfSecond());
}
private DateTime realNow() {
return new DateTime(DateTimeZone.UTC);
}
protected void setReferenceDateTimeUTC(final DateTime mockDateTimeUTC) {
this.mockDateTimeUTC = mockDateTimeUTC;
}
protected DateTime getReferenceDateTimeUTC() {
return mockDateTimeUTC;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/clock/src/test/java/org/killbill/clock/TestClockMockBase.java | clock/src/test/java/org/killbill/clock/TestClockMockBase.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.clock;
import java.util.concurrent.Callable;
import org.awaitility.Awaitility;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.testng.Assert;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public abstract class TestClockMockBase {
protected void testBasicClockOperations(final ClockMock clock) throws Exception {
final DateTime startingTime = new DateTime(DateTimeZone.UTC);
// Lame, but required due to the truncation magic
Awaitility.await().atMost(1500, MILLISECONDS).until(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return clock.getUTCNow().isAfter(startingTime);
}
});
clock.setTime(new DateTime(2012, 5, 1, 1, 2, 3, DateTimeZone.UTC));
Assert.assertEquals(clock.getUTCToday(), new LocalDate(2012, 5, 1));
final DateTime utcNowAfterSetTime = clock.getUTCNow();
Assert.assertEquals(utcNowAfterSetTime.getHourOfDay(), 1);
Assert.assertEquals(utcNowAfterSetTime.getMinuteOfHour(), 2);
Assert.assertEquals(utcNowAfterSetTime.getSecondOfMinute(), 3);
clock.addDays(1);
Assert.assertEquals(clock.getUTCToday(), new LocalDate(2012, 5, 2));
clock.addMonths(1);
Assert.assertEquals(clock.getUTCToday(), new LocalDate(2012, 6, 2));
clock.addYears(1);
Assert.assertEquals(clock.getUTCToday(), new LocalDate(2013, 6, 2));
clock.setDay(new LocalDate(2045, 12, 12));
Assert.assertEquals(clock.getUTCToday(), new LocalDate(2045, 12, 12));
clock.resetDeltaFromReality();
Assert.assertTrue(clock.getUTCNow().isAfter(startingTime));
Assert.assertTrue(clock.getUTCNow().isBefore(startingTime.plusMinutes(1)));
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/clock/src/test/java/org/killbill/clock/TestClockUtil.java | clock/src/test/java/org/killbill/clock/TestClockUtil.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.clock;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestClockUtil {
@Test(groups = "fast")
public void testWithInputInThePast() {
final DateTimeZone inputTimeZone = DateTimeZone.forOffsetHours(1);
final LocalDate inputDateInTargetTimeZone = new LocalDate(2014, 10, 23);
final LocalTime inputTimeInUTC = new LocalTime(10, 23, 05);
final DateTime result = ClockUtil.toUTCDateTime(inputDateInTargetTimeZone, inputTimeInUTC, inputTimeZone);
Assert.assertEquals(result.compareTo(new DateTime(2014, 10, 23, 9, 23, 05, DateTimeZone.UTC)), 0);
// ClockUtil should have returned a DateTime which when converted back into a LocalDate in the inputTimeZone matches the input
Assert.assertEquals(result.toDateTime(inputTimeZone).toLocalDate().compareTo(inputDateInTargetTimeZone), 0);
}
@Test(groups = "fast")
public void testWithInputInTheFuture() {
final DateTimeZone inputTimeZone = DateTimeZone.forOffsetHours(-1);
final LocalDate inputDateInTargetTimeZone = new LocalDate(2014, 10, 23);
final LocalTime inputTimeInUTC = new LocalTime(10, 23, 05);
final DateTime result = ClockUtil.toUTCDateTime(inputDateInTargetTimeZone, inputTimeInUTC, inputTimeZone);
Assert.assertEquals(result.compareTo(new DateTime(2014, 10, 23, 11, 23, 05, DateTimeZone.UTC)), 0);
// ClockUtil should have returned a DateTime which when converted back into a LocalDate in the inputTimeZone matches the input
Assert.assertEquals(result.toDateTime(inputTimeZone).toLocalDate().compareTo(inputDateInTargetTimeZone), 0);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/clock/src/test/java/org/killbill/clock/TestDistributedClockMock.java | clock/src/test/java/org/killbill/clock/TestDistributedClockMock.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.clock;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import redis.embedded.RedisServer;
public class TestDistributedClockMock extends TestClockMockBase {
private RedisServer redisServer;
@BeforeMethod(groups = "slow")
public void setUp() {
if (System.getProperty("os.name").contains("Windows")) {
redisServer = RedisServer.builder()
.setting("maxheap 1gb")
.port(56379)
.build();
} else {
redisServer = new RedisServer(56379);
}
redisServer.start();
}
@AfterMethod(groups = "slow")
public void tearDown() {
redisServer.stop();
}
@Test(groups = "slow")
public void testBasicClockOperations() throws Exception {
final Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:56379");
final RedissonClient redissonClient = Redisson.create(config);
try {
final DistributedClockMock clock = new DistributedClockMock();
clock.setRedissonClient(redissonClient);
testBasicClockOperations(clock);
} finally {
redissonClient.shutdown();
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/clock/src/test/java/org/killbill/clock/DistributedClockMock.java | clock/src/test/java/org/killbill/clock/DistributedClockMock.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.clock;
import org.joda.time.DateTime;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
public class DistributedClockMock extends ClockMock {
private RedissonClient redissonClient;
// Work around reset being called in parent default constructor
public void setRedissonClient(final RedissonClient redissonClient) {
this.redissonClient = redissonClient;
reset();
}
@Override
protected void setReferenceDateTimeUTC(final DateTime mockDateTimeUTC) {
if (redissonClient == null) {
super.setReferenceDateTimeUTC(mockDateTimeUTC);
return;
}
final RAtomicLong referenceInstantUTC = getReferenceInstantUTC();
referenceInstantUTC.set(mockDateTimeUTC.getMillis());
}
@Override
protected DateTime getReferenceDateTimeUTC() {
if (redissonClient == null) {
return super.getReferenceDateTimeUTC();
}
final RAtomicLong referenceInstantUTC = getReferenceInstantUTC();
return new DateTime(referenceInstantUTC.get());
}
private RAtomicLong getReferenceInstantUTC() {
return redissonClient.getAtomicLong("ReferenceInstantUTC");
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/clock/src/main/java/org/killbill/clock/ClockUtil.java | clock/src/main/java/org/killbill/clock/ClockUtil.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.clock;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.IllegalInstantException;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;
public class ClockUtil {
/**
* Create a DateTime object using the specified reference time and timezone
*
* @param localDate LocalDate to convert
* @param referenceTime Reference local time
* @param dateTimeZone Target timezone
* @return DateTime representing the input localDate at the specified reference time, in UTC
*/
public static DateTime toUTCDateTime(final LocalDate localDate, final LocalTime referenceTime, final DateTimeZone dateTimeZone) {
DateTime targetDateTime;
try {
targetDateTime = new DateTime(localDate.getYear(),
localDate.getMonthOfYear(),
localDate.getDayOfMonth(),
referenceTime.getHourOfDay(),
referenceTime.getMinuteOfHour(),
referenceTime.getSecondOfMinute(),
dateTimeZone);
} catch (final IllegalInstantException e) {
// DST gap (shouldn't happen when using fixed offset timezones)
targetDateTime = localDate.toDateTimeAtStartOfDay(dateTimeZone);
}
return toUTCDateTime(targetDateTime);
}
/**
* Create a LocalDate object using the specified timezone
*
* @param dateTime DateTime to convert
* @param dateTimeZone Target timezone
* @return LocalDate representing the input dateTime in the specified timezone
*/
public static LocalDate toLocalDate(final DateTime dateTime, final DateTimeZone dateTimeZone) {
return new LocalDate(dateTime, dateTimeZone);
}
/**
* Create a DateTime object forcing the timezone to be UTC
*
* @param dateTime DateTime to convert
* @return DateTime representing the input dateTime in UTC
*/
public static DateTime toUTCDateTime(final DateTime dateTime) {
return toDateTime(dateTime, DateTimeZone.UTC);
}
/**
* Create a DateTime object using the specified timezone
*
* @param dateTime DateTime to convert
* @param accountTimeZone Target timezone
* @return DateTime representing the input dateTime in the specified timezone
*/
public static DateTime toDateTime(final DateTime dateTime, final DateTimeZone accountTimeZone) {
return dateTime.toDateTime(accountTimeZone);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/clock/src/main/java/org/killbill/clock/Clock.java | clock/src/main/java/org/killbill/clock/Clock.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.clock;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
public interface Clock {
public DateTime getNow(DateTimeZone tz);
public DateTime getUTCNow();
public LocalDate getUTCToday();
public LocalDate getToday(DateTimeZone timeZone);
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/clock/src/main/java/org/killbill/clock/DefaultClock.java | clock/src/main/java/org/killbill/clock/DefaultClock.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.clock;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
public class DefaultClock implements Clock {
@Override
public DateTime getNow(final DateTimeZone tz) {
final DateTime result = new DateTime(tz);
return truncateMs(result);
}
@Override
public DateTime getUTCNow() {
return getNow(DateTimeZone.UTC);
}
@Override
public LocalDate getUTCToday() {
return getToday(DateTimeZone.UTC);
}
@Override
public LocalDate getToday(final DateTimeZone timeZone) {
return new LocalDate(getUTCNow(), timeZone);
}
public static DateTime toUTCDateTime(final DateTime input) {
if (input == null) {
return null;
}
final DateTime result = input.toDateTime(DateTimeZone.UTC);
return truncateMs(result);
}
public static DateTime truncateMs(final DateTime input) {
return input.minus(input.getMillisOfSecond());
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/test/java/org/killbill/commons/skeleton/metrics/TestResourceTimer.java | skeleton/src/test/java/org/killbill/commons/skeleton/metrics/TestResourceTimer.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.metrics;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.Timer;
import org.killbill.commons.metrics.dropwizard.KillBillCodahaleMetricRegistry;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test(groups = "fast")
public class TestResourceTimer {
private static final String RESOURCE_METRICS_PREFIX = "kb_resource";
private MetricRegistry metricRegistry;
@BeforeMethod
public void setup() {
metricRegistry = new KillBillCodahaleMetricRegistry();
}
@Test
public void testMetricName() {
final String resourcePath = "/1.0/kb/payments";
final String escapedResourcePath = "/1_0/kb/payments";
final String resourceName = "getPayment";
final String httpMethod = "GET";
final ResourceTimer resourceTimer = new ResourceTimer(resourcePath, resourceName, httpMethod, null, metricRegistry);
resourceTimer.update(200, 1, TimeUnit.MILLISECONDS);
final String expectedMetricName = expectedMetricName(escapedResourcePath, resourceName, httpMethod, null, "2xx", 200);
final Timer timer = metricRegistry.getTimers().get(expectedMetricName);
Assert.assertNotNull(timer, "Failed to create metric with expected name");
Assert.assertEquals(1, timer.getCount());
}
private String expectedMetricName(final String resourcePath, final String resourceName, final String httpMethod, final String tagsValues, final String statusGroup, final int status) {
if (tagsValues == null || tagsValues.trim().isEmpty()) {
return String.format("%s.%s.%s.%s.%s.%s", RESOURCE_METRICS_PREFIX, resourcePath, resourceName, httpMethod, statusGroup, status);
}
return String.format("%s.%s.%s.%s.%s.%s.%s", RESOURCE_METRICS_PREFIX, resourcePath, resourceName, httpMethod, tagsValues, statusGroup, status);
}
@Test
public void testMetricNameWithTags() {
final String resourcePath = "/1.0/kb/payments";
final String escapeResourcePath = "/1_0/kb/payments";
final String resourceName = "create";
final String httpMethod = "POST";
final Map<String, Object> tags = Map.of("transactionType", "AUTHORIZE");
final ResourceTimer resourceTimer = new ResourceTimer(resourcePath, resourceName, httpMethod, tags, metricRegistry);
resourceTimer.update(501, 1, TimeUnit.MILLISECONDS);
final String expectedMetricName = expectedMetricName(escapeResourcePath, resourceName, httpMethod, "AUTHORIZE", "5xx", 501);
final Timer timer = metricRegistry.getTimers().get(expectedMetricName);
Assert.assertNotNull(timer, "Failed to create metric with expected name: " + expectedMetricName);
Assert.assertEquals(1, timer.getCount());
}
@Test
public void testMetricNameWithNullComponent() {
final String resourcePath = null;
final String resourceName = null;
final String httpMethod = null;
final ResourceTimer resourceTimer = new ResourceTimer(resourcePath, resourceName, httpMethod, null, metricRegistry);
resourceTimer.update(200, 1, TimeUnit.MILLISECONDS);
final String expectedMetricName = expectedMetricName(resourcePath, resourceName, httpMethod, null, "2xx", 200);
final Timer timer = metricRegistry.getTimers().get(expectedMetricName);
Assert.assertNotNull(timer, "Failed to create metric with expected name");
Assert.assertEquals(1, timer.getCount());
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/test/java/org/killbill/commons/skeleton/metrics/TestTimedResourceInterceptor.java | skeleton/src/test/java/org/killbill/commons/skeleton/metrics/TestTimedResourceInterceptor.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.metrics;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.List;
import java.util.Set;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.aopalliance.intercept.MethodInterceptor;
import org.glassfish.hk2.api.InterceptionService;
import org.glassfish.jersey.spi.ExceptionMappers;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.annotation.MetricTag;
import org.killbill.commons.metrics.api.annotation.TimedResource;
import org.killbill.commons.metrics.api.Timer;
import org.killbill.commons.metrics.dropwizard.KillBillCodahaleMetricRegistry;
import org.killbill.commons.skeleton.modules.TimedInterceptionService;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.Matchers;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;
@Test(groups = "fast")
public class TestTimedResourceInterceptor {
private MetricRegistry registry;
private TestResource interceptedResource;
@BeforeMethod
public void setup() throws Exception {
final Injector injector = Guice.createInjector(new TestResourceModule());
registry = injector.getInstance(MetricRegistry.class);
interceptedResource = injector.getInstance(TestResource.class);
}
public void testResourceWithResponse() {
final Response response = interceptedResource.createOk();
Assert.assertEquals(200, response.getStatus());
final Timer timer = registry.getTimers().get("kb_resource.path.createOk.POST.2xx.200");
Assert.assertNotNull(timer);
Assert.assertEquals(1, timer.getCount());
}
public void testResourceSimpleTag() {
final Response response = interceptedResource.createOk("AUTHORIZE");
Assert.assertEquals(200, response.getStatus());
final Timer timer = registry.getTimers().get("kb_resource.path.createOk.POST.AUTHORIZE.2xx.200");
Assert.assertNotNull(timer);
Assert.assertEquals(1, timer.getCount());
}
public void testResourceWithPropertyTag() {
final Response response = interceptedResource.createOk(new Payment("PURCHASE"));
Assert.assertEquals(201, response.getStatus());
final Timer timer = registry.getTimers().get("kb_resource.path.createOk.POST.PURCHASE.2xx.201");
Assert.assertNotNull(timer);
Assert.assertEquals(1, timer.getCount());
}
public void testResourceNullTag() {
final Response response = interceptedResource.createOk((String) null);
Assert.assertEquals(200, response.getStatus());
final Timer timer = registry.getTimers().get("kb_resource.path.createOk.POST.null.2xx.200");
Assert.assertNotNull(timer);
Assert.assertEquals(1, timer.getCount());
}
public void testResourceNullPropertyTag() {
final Response response = interceptedResource.createOk((Payment) null);
Assert.assertEquals(201, response.getStatus());
final Timer timer = registry.getTimers().get("kb_resource.path.createOk.POST.null.2xx.201");
Assert.assertNotNull(timer);
Assert.assertEquals(1, timer.getCount());
}
public void testResourceWithNullResponse() {
final Response response = interceptedResource.createNullResponse();
Assert.assertNull(response);
final Timer timer = registry.getTimers().get("kb_resource.path.createNullResponse.PUT.2xx.204");
Assert.assertNotNull(timer);
Assert.assertEquals(1, timer.getCount());
}
public void testResourceWithVoidResponse() {
interceptedResource.createNullResponse();
final Timer timer = registry.getTimers().get("kb_resource.path.createNullResponse.PUT.2xx.204");
Assert.assertNotNull(timer);
Assert.assertEquals(1, timer.getCount());
}
public void testResourceWithWebApplicationException() {
try {
interceptedResource.createWebApplicationException();
Assert.fail();
} catch (final WebApplicationException e) {
final Timer timer = registry.getTimers().get("kb_resource.path.createWebApplicationException.POST.4xx.404");
Assert.assertNotNull(timer);
Assert.assertEquals(1, timer.getCount());
}
}
public static class Payment {
private final String type;
public Payment(final String type) {
this.type = type;
}
public String getType() {
return type;
}
}
@Path("path")
public static class TestResource {
@TimedResource
@POST
public Response createOk() {
return Response.ok().build();
}
@TimedResource
@POST
public Response createOk(@MetricTag(tag = "transactionType") final String type) {
return Response.ok().build();
}
@TimedResource
@POST
public Response createOk(@MetricTag(tag = "transactionType", property = "type") final Payment payment) {
return Response.created(URI.create("about:blank")).build();
}
@TimedResource
@PUT
public Response createNullResponse() {
return null;
}
@TimedResource
@PUT
public void createVoidResponse() {
}
@TimedResource
@POST
public void createWebApplicationException() {
throw new WebApplicationException(404);
}
}
// In practice, this is done by HK2, not Guice, but for convenience, we use Guice here
public static class TestResourceModule extends AbstractModule {
@Override
protected void configure() {
bind(TestResource.class).asEagerSingleton();
final MetricRegistry metricRegistry = new KillBillCodahaleMetricRegistry();
bind(MetricRegistry.class).toInstance(metricRegistry);
final InterceptionService timedInterceptionService = new TimedInterceptionService(Set.of(this.getClass().getPackage().getName()),
Mockito.mock(ExceptionMappers.class),
metricRegistry);
bindListener(Matchers.any(), new TypeListener() {
@Override
public <I> void hear(final TypeLiteral<I> literal, final TypeEncounter<I> encounter) {
for (final Method method : literal.getRawType().getMethods()) {
final List<MethodInterceptor> methodInterceptors = timedInterceptionService.getMethodInterceptors(method);
if (methodInterceptors != null) {
encounter.bindInterceptor(Matchers.only(method), methodInterceptors.get(0));
}
}
}
});
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/test/java/org/killbill/commons/skeleton/modules/HelloFilter.java | skeleton/src/test/java/org/killbill/commons/skeleton/modules/HelloFilter.java | /*
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.modules;
import java.io.IOException;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import org.testng.Assert;
@Singleton
public class HelloFilter implements ContainerRequestFilter, ContainerResponseFilter {
private static boolean initialized = false;
static int invocations = 0;
@Inject
public HelloFilter() {
// Verify it's indeed a Singleton
Assert.assertFalse(initialized);
initialized = true;
}
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
invocations += 1;
}
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) throws IOException {
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/test/java/org/killbill/commons/skeleton/modules/AbstractBaseServerModuleTest.java | skeleton/src/test/java/org/killbill/commons/skeleton/modules/AbstractBaseServerModuleTest.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.modules;
import java.io.IOException;
import java.net.ServerSocket;
import javax.servlet.ServletContextEvent;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.killbill.commons.health.api.HealthCheckRegistry;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.servlets.HealthCheckServlet;
import org.killbill.commons.metrics.servlets.InstrumentedFilter;
import org.killbill.commons.metrics.servlets.MetricsServlet;
import org.testng.Assert;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.ConfigurationException;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.servlet.GuiceFilter;
import com.google.inject.servlet.GuiceServletContextListener;
public abstract class AbstractBaseServerModuleTest {
final String metricsUri = "/1.0/metrics";
final String threadsUri = "/1.0/threads";
final String healthCheckUri = "/1.0/healthcheck";
protected Server startServer(final Module... modules) throws Exception {
final Injector injector = Guice.createInjector(modules);
return startServer(injector);
}
protected Server startServer(final Injector injector) throws Exception {
final Server server = new Server(getPort());
final ServletContextHandler servletContextHandler = new ServletContextHandler();
servletContextHandler.addEventListener(new GuiceServletContextListener() {
@Override
protected Injector getInjector() {
return injector;
}
@Override
public void contextInitialized(final ServletContextEvent servletContextEvent) {
super.contextInitialized(servletContextEvent);
try {
// For Kill Bill, this is done in KillbillPlatformGuiceListener
final MetricRegistry metricRegistry = injector.getInstance(MetricRegistry.class);
servletContextEvent.getServletContext().setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, metricRegistry);
servletContextEvent.getServletContext().setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry);
servletContextEvent.getServletContext().setAttribute(MetricsServlet.OBJECT_MAPPER, injector.getInstance(ObjectMapper.class));
servletContextEvent.getServletContext().setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, injector.getInstance(HealthCheckRegistry.class));
} catch(final ConfigurationException ignored) {
// No MetricRegistry binding (no StatsModule)
}
}
});
servletContextHandler.addFilter(GuiceFilter.class, "/*", null);
servletContextHandler.addServlet(DefaultServlet.class, "/*");
server.setHandler(servletContextHandler);
server.start();
final Thread t = new Thread() {
@Override
public void run() {
try {
server.join();
} catch (final InterruptedException ignored) {
}
}
};
t.setDaemon(true);
t.start();
Assert.assertTrue(server.isRunning());
return server;
}
private int getPort() {
final int port;
try {
final ServerSocket socket = new ServerSocket(0);
port = socket.getLocalPort();
socket.close();
} catch (final IOException e) {
Assert.fail();
return -1;
}
return port;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/test/java/org/killbill/commons/skeleton/modules/SomeGuiceyDependency.java | skeleton/src/test/java/org/killbill/commons/skeleton/modules/SomeGuiceyDependency.java | /*
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.modules;
import javax.inject.Singleton;
@Singleton
public class SomeGuiceyDependency {
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/test/java/org/killbill/commons/skeleton/modules/TestJerseyBaseServerModule.java | skeleton/src/test/java/org/killbill/commons/skeleton/modules/TestJerseyBaseServerModule.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.modules;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;
import java.util.Map;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.killbill.commons.health.api.HealthCheck;
import org.killbill.commons.health.api.Result;
import org.killbill.commons.health.impl.HealthyResultBuilder;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.impl.NoOpMetricRegistry;
import org.killbill.commons.metrics.modules.StatsModule;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class TestJerseyBaseServerModule extends AbstractBaseServerModuleTest {
@Test(groups = "slow")
public void testJerseyIntegration() throws Exception {
final BaseServerModuleBuilder builder = new BaseServerModuleBuilder();
builder.addJerseyResourcePackage("org.killbill.commons.skeleton.modules");
builder.addJerseyResourceClass(HelloFilter.class.getName());
builder.addJerseyResourceClass(JacksonJsonProvider.class.getName());
builder.setJaxrsUriPattern("/hello|/hello/.*");
final Injector injector = Guice.createInjector(builder.build(),
new StatsModule(healthCheckUri, metricsUri, threadsUri, List.of(TestHealthCheck.class)),
new AbstractModule() {
@Override
protected void configure() {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
binder().bind(ObjectMapper.class).toInstance(objectMapper);
bind(MetricRegistry.class).to(NoOpMetricRegistry.class).asEagerSingleton();
}
});
final Server server = startServer(injector);
final HttpClient client = HttpClient.newHttpClient();
// Verify healthcheck integration
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://127.0.0.1:" + ((NetworkConnector) server.getConnectors()[0]).getPort() + "/1.0/healthcheck")).build();
String body = client.send(request, BodyHandlers.ofString()).body();
final Map<String, Map<String, ?>> deserializedChecks = injector.getInstance(ObjectMapper.class).readValue(body, new TypeReference<>() {});
Assert.assertEquals(deserializedChecks.get("org.killbill.commons.skeleton.modules.TestJerseyBaseServerModule$TestHealthCheck").get("healthy"), true);
Assert.assertEquals(deserializedChecks.get("org.killbill.commons.skeleton.modules.TestJerseyBaseServerModule$TestHealthCheck").get("message"), "this is working");
// Verify metrics integration
final MetricRegistry metricRegistry = injector.getInstance(MetricRegistry.class);
Assert.assertEquals(metricRegistry.getMetrics().size(), 0);
Assert.assertEquals(HelloFilter.invocations, 0);
// Do multiple passes to verify Singleton pattern
for (int i = 0; i < 5; i++) {
request = HttpRequest.newBuilder().uri(URI.create("http://127.0.0.1:" + ((NetworkConnector) server.getConnectors()[0]).getPort() + "/hello/alhuile/")).build();
body = client.send(request, BodyHandlers.ofString()).body();
Assert.assertEquals(body, "Hello alhuile");
Assert.assertEquals(HelloFilter.invocations, i + 1);
}
request = HttpRequest.newBuilder().uri(URI.create("http://127.0.0.1:" + ((NetworkConnector) server.getConnectors()[0]).getPort() + "/hello")).POST(HttpRequest.BodyPublishers.noBody()).build();
body = client.send(request, BodyHandlers.ofString()).body();
final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode node = objectMapper.readTree(body);
Assert.assertEquals(node.get("key").textValue(), "hello");
Assert.assertEquals(node.get("date").textValue(), "2010-01-01");
Assert.assertEquals(metricRegistry.getMetrics().size(), 2);
Assert.assertNotNull(metricRegistry.getMetrics().get("kb_resource.hello.hello.POST.2xx.200"));
Assert.assertNotNull(metricRegistry.getMetrics().get("kb_resource.hello.hello.GET.2xx.200"));
server.stop();
}
@Test(groups = "fast")
public void testJerseyParams() throws Exception {
final BaseServerModuleBuilder builder1 = new BaseServerModuleBuilder();
final JerseyBaseServerModule module1 = (JerseyBaseServerModule) builder1.build();
final Map<String, String> jerseyParams1 = module1.getJerseyParams();
Assert.assertEquals(jerseyParams1.size(), 2);
Assert.assertEquals(jerseyParams1.get(JerseyBaseServerModule.JERSEY_LOGGING_VERBOSITY), "HEADERS_ONLY");
Assert.assertEquals(jerseyParams1.get(JerseyBaseServerModule.JERSEY_LOGGING_LEVEL), "INFO");
final BaseServerModuleBuilder builder2 = new BaseServerModuleBuilder();
builder2.addJerseyParam(JerseyBaseServerModule.JERSEY_LOGGING_VERBOSITY, "PAYLOAD_TEXT")
.addJerseyParam(JerseyBaseServerModule.JERSEY_LOGGING_LEVEL, "FINE")
.addJerseyParam("foo", "qux");
final JerseyBaseServerModule module2 = (JerseyBaseServerModule) builder2.build();
final Map<String, String> jerseyParams2 = module2.getJerseyParams();
Assert.assertEquals(jerseyParams2.size(), 3);
Assert.assertEquals(jerseyParams2.get(JerseyBaseServerModule.JERSEY_LOGGING_VERBOSITY), "PAYLOAD_TEXT");
Assert.assertEquals(jerseyParams2.get(JerseyBaseServerModule.JERSEY_LOGGING_LEVEL), "FINE");
Assert.assertEquals(jerseyParams2.get("foo"), "qux");
}
private static class TestHealthCheck implements HealthCheck {
@Override
public Result check() throws Exception {
return new HealthyResultBuilder().setMessage("this is working").createHealthyResult();
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/test/java/org/killbill/commons/skeleton/modules/HelloResource.java | skeleton/src/test/java/org/killbill/commons/skeleton/modules/HelloResource.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.modules;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import org.joda.time.LocalDate;
import org.killbill.commons.metrics.api.annotation.TimedResource;
import org.testng.Assert;
import com.google.inject.Injector;
@Path("hello")
@Singleton
public class HelloResource {
private static boolean initialized = false;
@Inject
public HelloResource(final SomeGuiceyDependency someGuiceyDependency, final Injector guiceInjector) {
// Verify it's indeed a Singleton
Assert.assertFalse(initialized);
initialized = true;
// HelloResource is being created by HK2 but these injections come from Guice
// (my understanding is that HK2 won't do JIT binding by default: https://javaee.github.io/hk2/getting-started.html#automatic-service-population)
Assert.assertEquals(someGuiceyDependency, guiceInjector.getInstance(SomeGuiceyDependency.class));
}
@TimedResource
@GET
@Path("/{name}")
public String hello(@PathParam("name") final String name) {
return "Hello " + name;
}
@TimedResource
@POST
@Produces("application/json")
public Map<String, ?> hello() {
return Map.of("key", "hello", "date", new LocalDate("2010-01-01"));
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/test/java/org/killbill/commons/skeleton/modules/TestBaseServerModule.java | skeleton/src/test/java/org/killbill/commons/skeleton/modules/TestBaseServerModule.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.modules;
import org.eclipse.jetty.server.Server;
import org.killbill.commons.skeleton.modules.BaseServerModuleBuilder.JaxrsImplementation;
import org.testng.annotations.Test;
import com.google.inject.servlet.ServletModule;
public class TestBaseServerModule extends AbstractBaseServerModuleTest {
@Test(groups = "slow")
public void testJettyStartup() throws Exception {
final ServletModule module = new BaseServerModuleBuilder().setJaxrsImplementation(JaxrsImplementation.NONE).build();
final Server server = startServer(module);
server.stop();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/main/java/org/killbill/commons/skeleton/servlets/LogInvalidResourcesServlet.java | skeleton/src/main/java/org/killbill/commons/skeleton/servlets/LogInvalidResourcesServlet.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogInvalidResourcesServlet extends HttpServlet {
private static final Logger log = LoggerFactory.getLogger(LogInvalidResourcesServlet.class);
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
sendError(request, response);
}
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
sendError(request, response);
}
private void sendError(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
log.warn(String.format("The invalid resource [%s] was requested from servlet [%s] on path [%s]", request.getPathInfo(), getServletConfig().getServletName(), request.getServletPath()));
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/main/java/org/killbill/commons/skeleton/metrics/ResourceTimer.java | skeleton/src/main/java/org/killbill/commons/skeleton/metrics/ResourceTimer.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.metrics;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.Timer;
import org.killbill.commons.utils.Joiner;
public class ResourceTimer {
private static final Joiner METRIC_NAME_JOINER = Joiner.on('.');
private final String resourcePath;
private final String name;
private final String httpMethod;
private final Map<String, Object> tags;
private final MetricRegistry registry;
public ResourceTimer(final String resourcePath, final String name, final String httpMethod, @Nullable final Map<String, Object> tags, final MetricRegistry registry) {
this.resourcePath = resourcePath;
this.name = name;
this.httpMethod = httpMethod;
this.tags = tags == null ? null : new HashMap<>(tags);
this.registry = registry;
}
public void update(final int responseStatus, final long duration, final TimeUnit unit) {
final String metricName;
if (tags != null && !tags.isEmpty()) {
final String tags = METRIC_NAME_JOINER.join(getTagsValues());
metricName = METRIC_NAME_JOINER.join(
escapeMetrics("kb_resource", resourcePath, name, httpMethod, tags, responseStatusGroup(responseStatus), responseStatus));
} else {
metricName = METRIC_NAME_JOINER.join(
escapeMetrics("kb_resource", resourcePath, name, httpMethod, responseStatusGroup(responseStatus), responseStatus));
}
// Letting metric registry deal with unique metric creation
final Timer timer = registry.timer(metricName);
timer.update(duration, unit);
}
private List<String> escapeMetrics(final Object... names) {
final List<String> result = new ArrayList<String>(names.length);
for (final Object name : names) {
final String metricName = String.valueOf(name);
result.add(metricName.replaceAll("\\.", "_"));
}
return result;
}
private List<Object> getTagsValues() {
final List<Object> values = new ArrayList<Object>(tags.values().size());
for (final Object value : tags.values()) {
if (value != null) {
values.add(value);
} else {
values.add("null");
}
}
return values;
}
private String responseStatusGroup(final int responseStatus) {
return String.format("%sxx", responseStatus / 100);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/main/java/org/killbill/commons/skeleton/metrics/TimedResourceInterceptor.java | skeleton/src/main/java/org/killbill/commons/skeleton/metrics/TimedResourceInterceptor.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.metrics;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.glassfish.jersey.spi.ExceptionMappers;
import org.killbill.commons.metrics.api.annotation.MetricTag;
import org.killbill.commons.metrics.api.MetricRegistry;
/**
* A method interceptor which times the execution of the annotated resource method.
*/
public class TimedResourceInterceptor implements MethodInterceptor {
private final Map<String, Map<String, Object>> metricTagsByMethod = new ConcurrentHashMap<String, Map<String, Object>>();
private final ExceptionMappers exceptionMappers;
private final MetricRegistry metricRegistry;
private final String resourcePath;
private final String metricName;
private final String httpMethod;
public TimedResourceInterceptor(final ExceptionMappers exceptionMappers,
final MetricRegistry metricRegistry,
final String resourcePath,
final String metricName,
final String httpMethod) {
this.exceptionMappers = exceptionMappers;
this.metricRegistry = metricRegistry;
this.resourcePath = resourcePath;
this.metricName = metricName;
this.httpMethod = httpMethod;
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
final long startTime = System.nanoTime();
int responseStatus = 0;
try {
final Object response = invocation.proceed();
if (response instanceof Response) {
responseStatus = ((Response) response).getStatus();
} else if (response == null || response instanceof Void) {
responseStatus = Response.Status.NO_CONTENT.getStatusCode();
} else {
responseStatus = Response.Status.OK.getStatusCode();
}
return response;
} catch (final WebApplicationException e) {
responseStatus = e.getResponse().getStatus();
throw e;
} catch (final Throwable e) {
responseStatus = mapException(e);
throw e;
} finally {
final long endTime = System.nanoTime();
final ResourceTimer timer = timer(invocation);
timer.update(responseStatus, endTime - startTime, TimeUnit.NANOSECONDS);
}
}
private int mapException(final Throwable e) throws Exception {
final ExceptionMapper<Throwable> exceptionMapper = (exceptionMappers != null) ? exceptionMappers.findMapping(e) : null;
if (exceptionMapper != null) {
return exceptionMapper.toResponse(e).getStatus();
}
// If there's no mapping for it, assume 500
return Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
}
private ResourceTimer timer(final MethodInvocation invocation) {
final Map<String, Object> metricTags = metricTags(invocation);
return new ResourceTimer(resourcePath, metricName, httpMethod, metricTags, metricRegistry);
}
private Map<String, Object> metricTags(final MethodInvocation invocation) {
final Method method = invocation.getMethod();
// Expensive to compute
final String methodString = method.toString();
// Cache metric tags as Method.getParameterAnnotations() generates lots of garbage objects
Map<String, Object> metricTags = metricTagsByMethod.get(methodString);
if (metricTags != null) {
return metricTags;
}
metricTags = new LinkedHashMap<String, Object>();
final Annotation[][] parametersAnnotations = method.getParameterAnnotations();
for (int i = 0; i < parametersAnnotations.length; i++) {
final Annotation[] parameterAnnotations = parametersAnnotations[i];
final MetricTag metricTag = findMetricTagAnnotations(parameterAnnotations);
if (metricTag != null) {
final Object currentArgument = invocation.getArguments()[i];
final Object tagValue;
if (metricTag.property().trim().isEmpty()) {
tagValue = currentArgument;
} else {
tagValue = getProperty(currentArgument, metricTag.property());
}
metricTags.put(metricTag.tag(), tagValue);
}
}
metricTagsByMethod.put(methodString, metricTags);
return metricTags;
}
private static MetricTag findMetricTagAnnotations(final Annotation[] parameterAnnotations) {
for (final Annotation parameterAnnotation : parameterAnnotations) {
if (parameterAnnotation instanceof MetricTag) {
return (MetricTag) parameterAnnotation;
}
}
return null;
}
private static Object getProperty(final Object currentArgument, final String property) {
if (currentArgument == null) {
return null;
}
try {
final String[] methodNames = {"get" + capitalize(property), "is" + capitalize(property), property};
Method propertyMethod = null;
for (final String methodName : methodNames) {
try {
propertyMethod = currentArgument.getClass().getMethod(methodName);
break;
} catch (final NoSuchMethodException e) {}
}
if (propertyMethod == null) {
throw handleReadPropertyError(currentArgument, property, null);
}
return propertyMethod.invoke(currentArgument);
} catch (final IllegalAccessException e) {
throw handleReadPropertyError(currentArgument, property, e);
} catch (final InvocationTargetException e) {
throw handleReadPropertyError(currentArgument, property, e);
}
}
private static String capitalize(final String property) {
return property.substring(0, 1).toUpperCase() + property.substring(1);
}
private static IllegalArgumentException handleReadPropertyError(final Object object, final String property, final Exception e) {
return new IllegalArgumentException(String.format("Failed to read tag property \"%s\" value from object of type %s", property, object.getClass()), e);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/main/java/org/killbill/commons/skeleton/modules/ConfigModule.java | skeleton/src/main/java/org/killbill/commons/skeleton/modules/ConfigModule.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.modules;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import org.skife.config.ConfigSource;
import org.skife.config.AugmentedConfigurationObjectFactory;
import org.skife.config.SimplePropertyConfigSource;
import com.google.inject.AbstractModule;
public class ConfigModule extends AbstractModule {
private final ConfigSource configSource;
private final Iterable<Class> configs;
public ConfigModule() {
this(System.getProperties());
}
public ConfigModule(final Properties properties) {
this(Collections.emptyList(), new SimplePropertyConfigSource(properties));
}
public ConfigModule(final Class config) {
this(List.of(config));
}
public ConfigModule(final Class... configs) {
this(List.of(configs));
}
public ConfigModule(final Iterable<Class> configs) {
this(configs, new SimplePropertyConfigSource(System.getProperties()));
}
public ConfigModule(final Iterable<Class> configs, final ConfigSource configSource) {
this.configs = configs;
this.configSource = configSource;
}
@SuppressWarnings("unchecked")
@Override
protected void configure() {
for (final Class config : configs) {
bind(config).toInstance(new AugmentedConfigurationObjectFactory(configSource).build(config));
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/main/java/org/killbill/commons/skeleton/modules/JMXModule.java | skeleton/src/main/java/org/killbill/commons/skeleton/modules/JMXModule.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.modules;
import java.lang.management.ManagementFactory;
import java.util.Collections;
import java.util.List;
import javax.management.MBeanServer;
import org.weakref.jmx.guice.ExportBinder;
import org.weakref.jmx.guice.MBeanModule;
import com.google.inject.AbstractModule;
public class JMXModule extends AbstractModule {
// JMX beans to export
private final Iterable<Class<?>> beans;
public JMXModule() {
this(Collections.emptyList());
}
public JMXModule(final Class<?> bean) {
this(List.of(bean));
}
public JMXModule(final Class<?>... beans) {
this(List.of(beans));
}
public JMXModule(final Iterable<Class<?>> beans) {
this.beans = beans;
}
@Override
protected void configure() {
final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
binder().bind(MBeanServer.class).toInstance(mBeanServer);
install(new MBeanModule());
final ExportBinder builder = ExportBinder.newExporter(binder());
for (final Class<?> beanClass : beans) {
builder.export(beanClass).withGeneratedName();
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/main/java/org/killbill/commons/skeleton/modules/JerseyBaseServerModule.java | skeleton/src/main/java/org/killbill/commons/skeleton/modules/JerseyBaseServerModule.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.modules;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import javax.servlet.Filter;
import javax.servlet.http.HttpServlet;
import org.glassfish.jersey.server.ServerProperties;
import org.killbill.commons.utils.Joiner;
import org.killbill.commons.utils.Strings;
import org.killbill.commons.utils.annotation.VisibleForTesting;
public class JerseyBaseServerModule extends BaseServerModule {
private static final Joiner joiner = Joiner.on(";");
@VisibleForTesting
static final String JERSEY_LOGGING_VERBOSITY = "jersey.config.logging.verbosity";
static final String JERSEY_LOGGING_LEVEL = "jersey.config.logging.logger.level";
protected final Collection<String> jerseyResourcesAndProvidersPackages;
protected final Collection<String> jerseyResourcesAndProvidersClasses;
// See org.glassfish.jersey.servlet.ServletProperties and org.glassfish.jersey.logging.LoggingFeature
protected final Map<String, String> jerseyParams;
public JerseyBaseServerModule(final Map<String, ArrayList<Entry<Class<? extends Filter>, Map<String, String>>>> filters,
final Map<String, ArrayList<Entry<Class<? extends Filter>, Map<String, String>>>> filtersRegex,
final Map<String, Class<? extends HttpServlet>> servlets,
final Map<String, Class<? extends HttpServlet>> servletsRegex,
final Map<String, Class<? extends HttpServlet>> jaxrsServlets,
final Map<String, Class<? extends HttpServlet>> jaxrsServletsRegex,
final String jaxrsUriPattern,
final Collection<String> jerseyResourcesAndProvidersPackages,
final Collection<String> jerseyResourcesAndProvidersClasses,
final Map<String, String> jerseyParams) {
super(filters, filtersRegex, servlets, servletsRegex, jaxrsServlets, jaxrsServletsRegex, jaxrsUriPattern);
this.jerseyResourcesAndProvidersPackages = new ArrayList<>(jerseyResourcesAndProvidersPackages);
this.jerseyResourcesAndProvidersClasses = new ArrayList<>(jerseyResourcesAndProvidersClasses);
this.jerseyParams = new HashMap<>();
// The LoggingFilter will log the body by default, which breaks StreamingOutput
final String jerseyLoggingVerbosity = Objects.requireNonNullElse(Strings.emptyToNull(jerseyParams.remove(JERSEY_LOGGING_VERBOSITY)), "HEADERS_ONLY");
final String jerseyLoggingLevel = Objects.requireNonNullElse(Strings.emptyToNull(jerseyParams.remove(JERSEY_LOGGING_LEVEL)), "INFO");
this.jerseyParams.put(JERSEY_LOGGING_VERBOSITY, jerseyLoggingVerbosity);
this.jerseyParams.put(JERSEY_LOGGING_LEVEL, jerseyLoggingLevel);
this.jerseyParams.putAll(jerseyParams);
}
@Override
protected void configureResources() {
for (final Entry<String, Class<? extends HttpServlet>> entry : jaxrsServlets.entrySet()) {
serve(entry.getKey()).with(entry.getValue(), jerseyParams);
}
for (final Entry<String, Class<? extends HttpServlet>> entry : jaxrsServletsRegex.entrySet()) {
serveRegex(entry.getKey()).with(entry.getValue(), jerseyParams);
}
// Catch-all resources
if (!jerseyResourcesAndProvidersPackages.isEmpty()) {
jerseyParams.put(ServerProperties.PROVIDER_PACKAGES, joiner.join(jerseyResourcesAndProvidersPackages));
jerseyParams.put(ServerProperties.PROVIDER_CLASSNAMES, joiner.join(jerseyResourcesAndProvidersClasses));
serveJaxrsResources();
}
}
protected void serveJaxrsResources() {
bind(GuiceServletContainer.class).asEagerSingleton();
serveRegex(jaxrsUriPattern).with(GuiceServletContainer.class, jerseyParams);
}
@VisibleForTesting
Map<String, String> getJerseyParams() {
return jerseyParams;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/main/java/org/killbill/commons/skeleton/modules/BaseServerModuleBuilder.java | skeleton/src/main/java/org/killbill/commons/skeleton/modules/BaseServerModuleBuilder.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.modules;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.http.HttpServlet;
public class BaseServerModuleBuilder {
public enum JaxrsImplementation {
NONE,
JERSEY
}
// By default, proxy all requests to the Guice/Jax-RS servlet
private String jaxrsUriPattern = "/.*";
private final Map<String, ArrayList<Map.Entry<Class<? extends Filter>, Map<String, String>>>> filters = new HashMap<>();
private final Map<String, ArrayList<Map.Entry<Class<? extends Filter>, Map<String, String>>>> filtersRegex = new HashMap<>();
private final Map<String, Class<? extends HttpServlet>> jaxrsServlets = new HashMap<>();
private final Map<String, Class<? extends HttpServlet>> jaxrsServletsRegex = new HashMap<>();
private final Map<String, Class<? extends HttpServlet>> servlets = new HashMap<>();
private final Map<String, Class<? extends HttpServlet>> servletsRegex = new HashMap<>();
// Jersey specific
private final List<String> jerseyResourcesAndProvidersPackages = new ArrayList<>();
private final List<String> jerseyResourcesAndProvidersClasses = new ArrayList<>();
private final Map<String, String> jerseyParams = new HashMap<>();
private JaxrsImplementation jaxrsImplementation = JaxrsImplementation.JERSEY;
public BaseServerModuleBuilder() {
}
public BaseServerModuleBuilder addFilter(final String urlPattern, final Class<? extends Filter> filterKey) {
return addFilter(urlPattern, filterKey, new HashMap<>());
}
public BaseServerModuleBuilder addFilter(final String urlPattern, final Class<? extends Filter> filterKey, final Map<String, String> initParams) {
if (this.filters.get(urlPattern) == null) {
this.filters.put(urlPattern, new ArrayList<>());
}
this.filters.get(urlPattern).add(Map.entry(filterKey, initParams));
return this;
}
public BaseServerModuleBuilder addFilterRegex(final String urlPattern, final Class<? extends Filter> filterKey) {
return addFilterRegex(urlPattern, filterKey, new HashMap<>());
}
public BaseServerModuleBuilder addFilterRegex(final String urlPattern, final Class<? extends Filter> filterKey, final Map<String, String> initParams) {
if (this.filtersRegex.get(urlPattern) == null) {
this.filtersRegex.put(urlPattern, new ArrayList<>());
}
this.filtersRegex.get(urlPattern).add(Map.entry(filterKey, initParams));
return this;
}
public BaseServerModuleBuilder addServlet(final String urlPattern, final Class<? extends HttpServlet> filterKey) {
this.servlets.put(urlPattern, filterKey);
return this;
}
public BaseServerModuleBuilder addServletRegex(final String urlPattern, final Class<? extends HttpServlet> filterKey) {
this.servletsRegex.put(urlPattern, filterKey);
return this;
}
public BaseServerModuleBuilder addJaxrsServlet(final String urlPattern, final Class<? extends HttpServlet> filterKey) {
this.jaxrsServlets.put(urlPattern, filterKey);
return this;
}
public BaseServerModuleBuilder addJaxrsServletRegex(final String urlPattern, final Class<? extends HttpServlet> filterKey) {
this.jaxrsServletsRegex.put(urlPattern, filterKey);
return this;
}
/**
* Add a class for the Guice/Jersey servlet
*
* @param resource class to scan
* @return the current module builder
*/
public BaseServerModuleBuilder addJerseyResourceClass(final String resource) {
this.jerseyResourcesAndProvidersClasses.add(resource);
return this;
}
public BaseServerModuleBuilder addJerseyParam(final String key, final String value) {
this.jerseyParams.put(key, value);
return this;
}
/**
* Specify the Uri pattern to use for the Guice/Jersey servlet
*
* @param jaxrsUriPattern Any Java-style regular expression
* @return the current module builder
*/
public BaseServerModuleBuilder setJaxrsUriPattern(final String jaxrsUriPattern) {
this.jaxrsUriPattern = jaxrsUriPattern;
return this;
}
/**
* Add a package to be scanned for the Guice/Jersey servlet
*
* @param resource package to scan
* @return the current module builder
*/
public BaseServerModuleBuilder addJerseyResourcePackage(final String resource) {
this.jerseyResourcesAndProvidersPackages.add(resource);
return this;
}
public BaseServerModuleBuilder setJaxrsImplementation(final JaxrsImplementation jaxrsImplementation) {
this.jaxrsImplementation = jaxrsImplementation;
return this;
}
public BaseServerModule build() {
switch (jaxrsImplementation) {
case NONE:
return new BaseServerModule(filters,
filtersRegex,
servlets,
servletsRegex,
jaxrsServlets,
jaxrsServletsRegex,
jaxrsUriPattern);
case JERSEY:
return new JerseyBaseServerModule(filters,
filtersRegex,
servlets,
servletsRegex,
jaxrsServlets,
jaxrsServletsRegex,
jaxrsUriPattern,
jerseyResourcesAndProvidersPackages,
jerseyResourcesAndProvidersClasses,
jerseyParams);
default:
throw new IllegalArgumentException();
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/main/java/org/killbill/commons/skeleton/modules/GuiceServletContainer.java | skeleton/src/main/java/org/killbill/commons/skeleton/modules/GuiceServletContainer.java | /*
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.modules;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.ws.rs.ext.MessageBodyWriter;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.utilities.ServiceLocatorUtilities;
import org.glassfish.jersey.internal.inject.InjectionManager;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.servlet.WebConfig;
import org.glassfish.jersey.spi.ExceptionMappers;
import org.jvnet.hk2.guice.bridge.api.GuiceBridge;
import org.jvnet.hk2.guice.bridge.api.GuiceIntoHK2Bridge;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.utils.Strings;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.google.inject.Injector;
import com.google.inject.TypeLiteral;
@Singleton
public class GuiceServletContainer extends ServletContainer {
private final Injector injector;
@Inject
public GuiceServletContainer(final Injector injector) {
super();
this.injector = injector;
}
@Override
protected void init(final WebConfig webConfig) throws ServletException {
// This will instantiate a new instance of ResourceConfig (see WebComponent#createResourceConfig) initialized
// with the Jersey parameters we specified (see JerseyBaseServerModule)
super.init(webConfig);
// HK2 will instantiate the Jersey resources, but will delegate injection of the bindings it doesn't know about to Guice
final InjectionManager injectionManager = getApplicationHandler().getInjectionManager();
final ServiceLocator serviceLocator = injectionManager.getInstance(ServiceLocator.class);
GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
final GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
guiceBridge.bridgeGuiceInjector(injector);
// Metrics integration
final String scannedResourcePackagesString = webConfig.getInitParameter(ServerProperties.PROVIDER_PACKAGES);
if (Strings.emptyToNull(scannedResourcePackagesString) != null) {
final Set<String> scannedResourcePackages = Set.of(scannedResourcePackagesString.split("[ ,;\n]"));
ServiceLocatorUtilities.addOneConstant(serviceLocator,
new TimedInterceptionService(scannedResourcePackages,
// From HK2
injectionManager.getInstance(ExceptionMappers.class),
// From Guice
injector.getInstance(MetricRegistry.class)));
}
// Jackson integration
final boolean hasObjectMapperBinding = !injector.findBindingsByType(TypeLiteral.get(ObjectMapper.class)).isEmpty();
if (hasObjectMapperBinding) {
// JacksonJsonProvider is constructed by HK2, but we need to inject the ObjectMapper we constructed via Guice
final ObjectMapper objectMapper = injector.getInstance(ObjectMapper.class);
for (final MessageBodyWriter<?> messageBodyWriter : injectionManager.<MessageBodyWriter<?>>getAllInstances(MessageBodyWriter.class)) {
if (messageBodyWriter instanceof JacksonJsonProvider) {
((JacksonJsonProvider) messageBodyWriter).setMapper(objectMapper);
break;
}
}
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/main/java/org/killbill/commons/skeleton/modules/BaseServerModule.java | skeleton/src/main/java/org/killbill/commons/skeleton/modules/BaseServerModule.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.modules;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.Filter;
import javax.servlet.http.HttpServlet;
import com.google.inject.servlet.ServletModule;
public class BaseServerModule extends ServletModule {
private final Map<String, ArrayList<Map.Entry<Class<? extends Filter>, Map<String, String>>>> filters;
private final Map<String, ArrayList<Map.Entry<Class<? extends Filter>, Map<String, String>>>> filtersRegex;
private final Map<String, Class<? extends HttpServlet>> servlets;
private final Map<String, Class<? extends HttpServlet>> servletsRegex;
// JAX-RS resources
final Map<String, Class<? extends HttpServlet>> jaxrsServlets;
final Map<String, Class<? extends HttpServlet>> jaxrsServletsRegex;
final String jaxrsUriPattern;
public BaseServerModule(final Map<String, ArrayList<Entry<Class<? extends Filter>, Map<String, String>>>> filters,
final Map<String, ArrayList<Entry<Class<? extends Filter>, Map<String, String>>>> filtersRegex,
final Map<String, Class<? extends HttpServlet>> servlets,
final Map<String, Class<? extends HttpServlet>> servletsRegex,
final Map<String, Class<? extends HttpServlet>> jaxrsServlets,
final Map<String, Class<? extends HttpServlet>> jaxrsServletsRegex,
final String jaxrsUriPattern) {
this.filters = new HashMap<>(filters);
this.filtersRegex = new HashMap<>(filtersRegex);
this.servlets = new HashMap<>(servlets);
this.servletsRegex =new HashMap<>(servletsRegex);
this.jaxrsServlets = new HashMap<>(jaxrsServlets);
this.jaxrsServletsRegex = new HashMap<>(jaxrsServletsRegex);
this.jaxrsUriPattern = jaxrsUriPattern;
}
@Override
public void configureServlets() {
super.configureServlets();
configureFilters();
configureFiltersRegex();
configureRegularServlets();
configureRegularServletsRegex();
configureResources();
}
protected void configureFilters() {
for (final String urlPattern : filters.keySet()) {
for (final Map.Entry<Class<? extends Filter>, Map<String, String>> filter : filters.get(urlPattern)) {
filter(urlPattern).through(filter.getKey(), filter.getValue());
}
}
}
protected void configureFiltersRegex() {
for (final String urlPattern : filtersRegex.keySet()) {
for (final Map.Entry<Class<? extends Filter>, Map<String, String>> filter : filtersRegex.get(urlPattern)) {
filterRegex(urlPattern).through(filter.getKey(), filter.getValue());
}
}
}
protected void configureRegularServlets() {
for (final String urlPattern : servlets.keySet()) {
serve(urlPattern).with(servlets.get(urlPattern));
}
}
protected void configureRegularServletsRegex() {
for (final String urlPattern : servletsRegex.keySet()) {
serveRegex(urlPattern).with(servletsRegex.get(urlPattern));
}
}
protected void configureResources() {
for (final String urlPattern : jaxrsServlets.keySet()) {
serve(urlPattern).with(jaxrsServlets.get(urlPattern));
}
for (final String urlPattern : jaxrsServletsRegex.keySet()) {
serveRegex(urlPattern).with(jaxrsServletsRegex.get(urlPattern));
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/main/java/org/killbill/commons/skeleton/modules/TimedInterceptionService.java | skeleton/src/main/java/org/killbill/commons/skeleton/modules/TimedInterceptionService.java | /*
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.modules;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Singleton;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Path;
import org.aopalliance.intercept.ConstructorInterceptor;
import org.aopalliance.intercept.MethodInterceptor;
import org.glassfish.hk2.api.Descriptor;
import org.glassfish.hk2.api.Filter;
import org.glassfish.hk2.api.InterceptionService;
import org.glassfish.jersey.spi.ExceptionMappers;
import org.killbill.commons.metrics.api.annotation.TimedResource;
import org.killbill.commons.skeleton.metrics.TimedResourceInterceptor;
import org.killbill.commons.metrics.api.MetricRegistry;
@Singleton
public class TimedInterceptionService implements InterceptionService {
private final Set<String> resourcePackages;
private final ExceptionMappers exceptionMappers;
private final MetricRegistry metricRegistry;
public TimedInterceptionService(final Set<String> resourcePackage,
final ExceptionMappers exceptionMappers,
final MetricRegistry metricRegistry) {
this.resourcePackages = new HashSet<>(resourcePackage);
this.exceptionMappers = exceptionMappers;
this.metricRegistry = metricRegistry;
}
@Override
public Filter getDescriptorFilter() {
return new Filter() {
@Override
public boolean matches(final Descriptor d) {
final String clazz = d.getImplementation();
for (final String resourcePackage : resourcePackages) {
if (clazz.startsWith(resourcePackage)) {
return true;
}
}
return false;
}
};
}
@Override
public List<MethodInterceptor> getMethodInterceptors(final Method method) {
final TimedResource annotation = method.getAnnotation(TimedResource.class);
if (annotation == null) {
return null;
}
final Path pathAnnotation = method.getDeclaringClass().getAnnotation(Path.class);
if (pathAnnotation == null) {
return null;
}
final String resourcePath = pathAnnotation.value();
final HttpMethod httpMethod = resourceHttpMethod(method);
if (httpMethod == null) {
return null;
}
final String metricName;
if (!annotation.name().trim().isEmpty()) {
metricName = annotation.name();
} else {
metricName = method.getName();
}
final MethodInterceptor timedResourceInterceptor = new TimedResourceInterceptor(exceptionMappers,
metricRegistry,
resourcePath,
metricName,
httpMethod.value());
return List.of(timedResourceInterceptor);
}
private HttpMethod resourceHttpMethod(final Method method) {
for (final Annotation annotation : method.getAnnotations()) {
final HttpMethod httpMethod = annotation.annotationType().getAnnotation(HttpMethod.class);
if (httpMethod != null) {
return httpMethod;
}
}
return null;
}
@Override
public List<ConstructorInterceptor> getConstructorInterceptors(final Constructor<?> constructor) {
return null;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/main/java/org/killbill/commons/skeleton/listeners/GuiceServletContextListener.java | skeleton/src/main/java/org/killbill/commons/skeleton/listeners/GuiceServletContextListener.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.listeners;
import java.util.List;
import javax.servlet.ServletContextEvent;
import org.killbill.commons.utils.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;
/**
* Start up the base module when the server comes up. This gets configured in web.xml:
* <p/>
* <pre>
* <context-param>
* <param-name>guiceModuleClassName</param-name>
* <param-value>org.killbill.commons.skeleton.listeners.GuiceServletContextListener</param-value>
* </context-param>
* </pre>
*/
public class GuiceServletContextListener extends com.google.inject.servlet.GuiceServletContextListener {
private static final Logger log = LoggerFactory.getLogger(GuiceServletContextListener.class);
protected Iterable<? extends Module> guiceModules = null;
@Override
public void contextInitialized(final ServletContextEvent event) {
// Check if the module was overridden in subclasses
if (guiceModules == null) {
guiceModules = List.of(initializeGuiceModuleFromWebXML(event));
}
super.contextInitialized(event);
}
private Module initializeGuiceModuleFromWebXML(final ServletContextEvent event) {
final String moduleClassName = event.getServletContext().getInitParameter("guiceModuleClassName");
if (Strings.isNullOrEmpty(moduleClassName)) {
throw new IllegalStateException("Missing parameter for the base Guice module!");
}
try {
final Class<?> moduleClass = Class.forName(moduleClassName);
if (!Module.class.isAssignableFrom(moduleClass)) {
throw new IllegalStateException(String.format("%s exists but is not a Guice Module!", moduleClassName));
}
final Module module = (Module) moduleClass.newInstance();
log.info("Instantiated " + moduleClassName + " as the main guice module.");
return module;
} catch (final ClassNotFoundException cnfe) {
throw new IllegalStateException(cnfe);
} catch (final InstantiationException ie) {
throw new IllegalStateException(ie);
} catch (final IllegalAccessException iae) {
throw new IllegalStateException(iae);
}
}
/**
* Do *not* use this method to retrieve the injector. It actually creates a new instance
* of a Guice injector which in turn will upset Guice.
*/
@Override
protected Injector getInjector() {
if (guiceModules == null) {
throw new IllegalStateException("Never found the Guice Module to use!");
}
return Guice.createInjector(Stage.PRODUCTION, guiceModules);
}
/**
* This method can be called by classes extending GuiceServletContextListener to retrieve
* the actual injector. This requires some inside knowledge on where it is
* stored, but the actual key is not visible outside the guice packages.
*/
public Injector injector(final ServletContextEvent event) {
return (Injector) event.getServletContext().getAttribute(Injector.class.getName());
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/skeleton/src/main/java/org/killbill/commons/skeleton/listeners/JULServletContextListener.java | skeleton/src/main/java/org/killbill/commons/skeleton/listeners/JULServletContextListener.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.skeleton.listeners;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.slf4j.bridge.SLF4JBridgeHandler;
/**
* Takes java.util.logging and redirects it into slf4j
*/
public class JULServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(final ServletContextEvent event) {
// We first remove the default handler(s)
final Logger rootLogger = LogManager.getLogManager().getLogger("");
final Handler[] handlers = rootLogger.getHandlers();
if (handlers != null) {
for (final Handler handler : handlers) {
rootLogger.removeHandler(handler);
}
}
// Remove all handlers attached to root JUL logger
removeHandlersForRootLoggerHierarchy();
// And then we let jul-to-sfl4j do its magic so that jersey messages go to sfl4j
SLF4JBridgeHandler.install();
}
//
// @See SLF4JBridgeHandler#removeHandlersForRootLogger
//
// The issue with SLF4JBridgeHandler#removeHandlersForRootLogger is that in
// some situations (e.g tomcat deployments), the root logger is *not* actually
// the root (e.g it has parents which have CONSOLE handlers attached) and we
// end up duplicating the JUL logs to console and bridge
//
private static void removeHandlersForRootLoggerHierarchy() {
java.util.logging.Logger rootLogger = LogManager.getLogManager().getLogger("");
while (rootLogger != null) {
removeHandlersForRootLogger(rootLogger);
rootLogger = rootLogger.getParent();
}
}
private static void removeHandlersForRootLogger(java.util.logging.Logger rootLogger) {
java.util.logging.Handler[] handlers = rootLogger.getHandlers();
for (int i = 0; i < handlers.length; i++) {
rootLogger.removeHandler(handlers[i]);
}
}
@Override
public void contextDestroyed(final ServletContextEvent event) {
SLF4JBridgeHandler.uninstall();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/app/src/test/java/com/dmallcott/dismissibleimageview/ExampleUnitTest.java | app/src/test/java/com/dmallcott/dismissibleimageview/ExampleUnitTest.java | package com.dmallcott.dismissibleimageview;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/app/src/test/java/com/dmallcott/dismissibleimageview/example/ExampleUnitTest.java | app/src/test/java/com/dmallcott/dismissibleimageview/example/ExampleUnitTest.java | package com.dmallcott.dismissibleimageview.example;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/app/src/main/java/com/dmallcott/dismissibleimageview/example/MainActivity.java | app/src/main/java/com/dmallcott/dismissibleimageview/example/MainActivity.java | package com.dmallcott.dismissibleimageview.example;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.dmallcott.dismissibleimageview.DismissibleImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DismissibleImageView dismissibleImageView = (DismissibleImageView) findViewById(R.id.activity_main_dismissibleImageView);
dismissibleImageView.setFinalUrl("https://images.pexels.com/photos/96938/pexels-photo-96938.jpeg?w=1260&h=750&dpr=2&auto=compress&cs=tinysrgb");
Picasso.with(this).load("https://images.pexels.com/photos/96938/pexels-photo-96938.jpeg?w=640&h=393&dpr=2&auto=compress&cs=tinysrgb").into(dismissibleImageView);
}
}
| java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/app/src/androidTest/java/com/dmallcott/dismissibleimageview/ExampleInstrumentedTest.java | app/src/androidTest/java/com/dmallcott/dismissibleimageview/ExampleInstrumentedTest.java | package com.dmallcott.dismissibleimageview;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.dmallcott.dismissibleimageview", appContext.getPackageName());
}
}
| java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/app/src/androidTest/java/com/dmallcott/dismissibleimageview/example/ExampleInstrumentedTest.java | app/src/androidTest/java/com/dmallcott/dismissibleimageview/example/ExampleInstrumentedTest.java | package com.dmallcott.dismissibleimageview.example;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.dmallcott.dismissibleimageview", appContext.getPackageName());
}
}
| java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/library/src/test/java/com/dmallcott/dismissibleimageview/ExampleUnitTest.java | library/src/test/java/com/dmallcott/dismissibleimageview/ExampleUnitTest.java | package com.dmallcott.dismissibleimageview;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/library/src/main/java/com/dmallcott/dismissibleimageview/DismissibleOnDragListener.java | library/src/main/java/com/dmallcott/dismissibleimageview/DismissibleOnDragListener.java | package com.dmallcott.dismissibleimageview;
import android.support.annotation.NonNull;
import android.view.DragEvent;
import android.view.View;
class DismissibleOnDragListener implements View.OnDragListener {
abstract static class OnDropListener {
abstract void onDragStarted();
abstract void onDrop();
abstract void onDragEnded();
abstract void onDragLocation(float x, float y);
}
@NonNull
private final OnDropListener onDropListener;
DismissibleOnDragListener(@NonNull final OnDropListener onDropListener) {
this.onDropListener = onDropListener;
}
@Override
public boolean onDrag(View v, DragEvent event) {
switch(event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
onDropListener.onDragStarted();
return true;
case DragEvent.ACTION_DRAG_ENTERED:
return true;
case DragEvent.ACTION_DRAG_LOCATION:
// Ignore the event
onDropListener.onDragLocation(event.getX(), event.getY());
return true;
case DragEvent.ACTION_DRAG_EXITED:
return true;
case DragEvent.ACTION_DROP:
onDropListener.onDrop();
return true;
case DragEvent.ACTION_DRAG_ENDED:
onDropListener.onDragEnded();
return true;
default:
break;
}
return false;
}
}
| java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/library/src/main/java/com/dmallcott/dismissibleimageview/DismissibleImageView.java | library/src/main/java/com/dmallcott/dismissibleimageview/DismissibleImageView.java | package com.dmallcott.dismissibleimageview;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
public class DismissibleImageView extends android.support.v7.widget.AppCompatImageView implements View.OnClickListener {
private String finalUrl;
private boolean blurOnLoading = true; // Defaults to true
@Nullable private FragmentManager fragmentManager;
public DismissibleImageView(Context context) {
this(context, null);
}
public DismissibleImageView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public DismissibleImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOnClickListener(this);
setDrawingCacheEnabled(true); // todo remember to clear it on set image
setAdjustViewBounds(true);
}
public void setFinalUrl(@NonNull final String url) {
this.finalUrl = url;
}
public void blurOnLoading(final boolean blurOnLoading) {
this.blurOnLoading = blurOnLoading;
}
public void setSupportFragmentManager(@NonNull final FragmentManager fragmentManager) {
this.fragmentManager = fragmentManager;
}
/**
* @deprecated Please override {@link #onClick(View)}} instead, otherwise you lose the full screen functionality.
*/
@Deprecated
@Override
public void setOnClickListener(@Nullable OnClickListener l) {
super.setOnClickListener(l);
}
@CallSuper
@Override
public void onClick(View v) {
FragmentManager fragmentManager = null;
if (this.fragmentManager != null) {
fragmentManager = this.fragmentManager;
} else if (getContext() instanceof FragmentActivity) {
fragmentManager = ((AppCompatActivity) getContext()).getSupportFragmentManager();
}
if (fragmentManager != null) {
FullScreenImageFragment fragment;
if (TextUtils.isEmpty(finalUrl)) {
fragment = new FullScreenImageFragment.Builder(getDrawingCache(true))
.withLoadingBlur(blurOnLoading).build();
} else {
fragment = new FullScreenImageFragment.Builder(finalUrl)
.withLoadingBitmap(getDrawingCache(true))
.withLoadingBlur(blurOnLoading).build();
}
fragment.show(fragmentManager);
}
}
}
| java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/library/src/main/java/com/dmallcott/dismissibleimageview/DismissibleDragShadowBuilder.java | library/src/main/java/com/dmallcott/dismissibleimageview/DismissibleDragShadowBuilder.java | package com.dmallcott.dismissibleimageview;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
class DismissibleDragShadowBuilder extends View.DragShadowBuilder {
private final Drawable shadow;
private final Point offset;
DismissibleDragShadowBuilder(ImageView imageView, Point offset) {
super(imageView);
this.offset = offset;
this.shadow = new ColorDrawable(Color.LTGRAY);
}
@Override
public void onProvideShadowMetrics (Point size, Point touch) {
final int width, height;
width = (int) (getView().getWidth());
height = (int) (getView().getHeight());
shadow.setBounds(0, 0, width, height);
size.set(width, height);
touch.set(offset.x, offset.y);
}
@Override
public void onDrawShadow(Canvas canvas) {
shadow.draw(canvas);
getView().draw(canvas);
}
}
| java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/library/src/main/java/com/dmallcott/dismissibleimageview/FullScreenImageFragment.java | library/src/main/java/com/dmallcott/dismissibleimageview/FullScreenImageFragment.java | package com.dmallcott.dismissibleimageview;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import com.dmallcott.dismissibleimageview.blur_transformation.BlurTransformation;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.squareup.picasso.Transformation;
import java.util.ArrayList;
import java.util.List;
public class FullScreenImageFragment extends DialogFragment {
private ImageView imageView;
private View topBorderView;
private View bottomBorderView;
private View leftBorderView;
private View rightBorderView;
private static final String ARGUMENT_URL = "ARGUMENT_URL";
private static final String ARGUMENT_LOADING_URL = "ARGUMENT_LOADING_URL";
private static final String ARGUMENT_BITMAP = "ARGUMENT_BITMAP";
private static final String ARGUMENT_LOADING_BITMAP = "ARGUMENT_LOADING_BITMAP";
private static final String ARGUMENT_LOADING_BLUR = "ARGUMENT_LOADING_BLUR";
// TODO : Handle rotation
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = super.onCreateDialog(savedInstanceState);
final LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = layoutInflater.inflate(R.layout.fragment_full_screen_image, null);
try {
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
} catch (NullPointerException e) {
// Do nothing
}
initialiseViews(view);
handleArguments((savedInstanceState != null ) ? savedInstanceState : getArguments());
dialog.setContentView(view);
return dialog;
}
@Override
public void onActivityCreated(Bundle arg0) {
super.onActivityCreated(arg0);
if (getDialog() != null) {
getDialog().getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
}
}
@Override
public void onStart() {
super.onStart();
if (getDialog() != null) {
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof BitmapDrawable) {
outState.putParcelable(
ARGUMENT_BITMAP, Bitmap.createBitmap(((BitmapDrawable) drawable).getBitmap())
);
}
}
public void show(@NonNull final FragmentManager fragmentManager) {
show(fragmentManager, "FullScreenImageFragment");
}
private void initialiseViews(@NonNull final View view) {
imageView = (ImageView) view.findViewById(R.id.fragment_full_screen_imageView);
topBorderView = view.findViewById(R.id.fragment_full_screen_top_border);
bottomBorderView = view.findViewById(R.id.fragment_full_screen_bottom_border);
leftBorderView = view.findViewById(R.id.fragment_full_screen_left_border);
rightBorderView = view.findViewById(R.id.fragment_full_screen_right_border);
// TODO - I know, this is really ugly. Keep in mind, it's an MVP.
leftBorderView.setOnDragListener(new DismissibleOnDragListener(new DismissibleOnDragListener.OnDropListener() {
@Override
void onDragStarted() {
imageView.setVisibility(View.INVISIBLE);
}
@Override
public void onDrop() {
dismiss();
}
@Override
void onDragEnded() {
imageView.setVisibility(View.VISIBLE);
view.setAlpha(1f);
}
@Override
void onDragLocation(float x, float y) {
view.setAlpha(x / leftBorderView.getWidth());
}
}));
rightBorderView.setOnDragListener(new DismissibleOnDragListener(new DismissibleOnDragListener.OnDropListener() {
@Override
void onDragStarted() {
imageView.setVisibility(View.INVISIBLE);
}
@Override
public void onDrop() {
dismiss();
}
@Override
void onDragEnded() {
imageView.setVisibility(View.VISIBLE);
view.setAlpha(1f);
}
@Override
void onDragLocation(float x, float y) {
view.setAlpha(1f - x / rightBorderView.getWidth());
}
}));
topBorderView.setOnDragListener(new DismissibleOnDragListener(new DismissibleOnDragListener.OnDropListener() {
@Override
void onDragStarted() {
imageView.setVisibility(View.INVISIBLE);
}
@Override
public void onDrop() {
dismiss();
}
@Override
void onDragEnded() {
imageView.setVisibility(View.VISIBLE);
view.setAlpha(1f);
}
@Override
void onDragLocation(float x, float y) {
view.setAlpha(y / topBorderView.getHeight());
}
}));
bottomBorderView.setOnDragListener(new DismissibleOnDragListener(new DismissibleOnDragListener.OnDropListener() {
@Override
void onDragStarted() {
imageView.setVisibility(View.INVISIBLE);
}
@Override
public void onDrop() {
dismiss();
}
@Override
void onDragEnded() {
imageView.setVisibility(View.VISIBLE);
view.setAlpha(1f);
}
@Override
void onDragLocation(float x, float y) {
view.setAlpha(1f - y / topBorderView.getHeight());
}
}));
imageView.setAdjustViewBounds(true);
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
final Point offset = new Point((int) event.getX(), (int) event.getY());
final View.DragShadowBuilder shadowBuilder = new DismissibleDragShadowBuilder(imageView, offset);
imageView.startDrag(null, shadowBuilder, imageView, 0);
return true;
}
return false;
}
});
}
private void handleArguments(@NonNull final Bundle bundle) {
final Bitmap bitmap = bundle.getParcelable(ARGUMENT_BITMAP);
final Bitmap loadingBitmap = bundle.getParcelable(ARGUMENT_LOADING_BITMAP);
final String url = bundle.getString(ARGUMENT_URL);
final String loadingUrl = bundle.getString(ARGUMENT_LOADING_URL);
final boolean loadingBlur = bundle.getBoolean(ARGUMENT_LOADING_BLUR);
if (bitmap != null) {
// If you have the final bitmap what's the point of loading behaviour?
loadBitmap(bitmap);
} else if (!TextUtils.isEmpty(url)) {
if (loadingBitmap != null) {
loadLoadingBitmap(loadingBitmap, url, loadingBlur);
} else if (!TextUtils.isEmpty(loadingUrl)) {
loadLoadingUrl(url, loadingUrl, loadingBlur);
}
}
}
private void loadLoadingBitmap(@NonNull final Bitmap bitmap, @NonNull final String url, final boolean loadingBlur) {
if (loadingBlur) {
final BlurTransformation transformation = new BlurTransformation(getContext());
final Bitmap blurredBitmap = transformation.transform(bitmap);
loadUrl(url, blurredBitmap);
} else {
loadBitmap(bitmap);
}
}
private void loadLoadingUrl(@NonNull final String url, @NonNull final String loadingUrl, final boolean loadingBlur) {
final List<Transformation> transformations = new ArrayList<>();
if (loadingBlur) {
transformations.add(new BlurTransformation(getContext()));
}
Picasso.with(getContext()).load(loadingUrl).transform(transformations).into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
loadUrl(url, bitmap);
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
private void loadUrl(@NonNull final String url, @NonNull final Bitmap bitmap) {
clearImageView();
Picasso.with(getContext()).load(url)
.placeholder(new BitmapDrawable(getResources(), bitmap))
.into(imageView);
}
private void clearImageView() {
imageView.setImageDrawable(null);
}
private void loadBitmap(@NonNull final Bitmap bitmap) {
clearImageView();
imageView.setImageBitmap(bitmap);
}
// todo document Bitmap > Url
public static class Builder {
private String url;
private String loadingUrl;
private Bitmap bitmap;
private Bitmap loadingBitmap;
private boolean loadingBlur = true;
public Builder(@NonNull final String url) {
this.url = url;
}
public Builder(@NonNull final Bitmap bitmap) {
this.bitmap = bitmap;
}
public Builder withLoadingUrl(@NonNull final String loadingUrl) {
this.loadingUrl = loadingUrl;
return this;
}
public Builder withLoadingBitmap(@NonNull final Bitmap loadingBitmap) {
this.loadingBitmap = loadingBitmap;
return this;
}
public Builder withLoadingBlur(final boolean loadingBlur) {
this.loadingBlur = loadingBlur;
return this;
}
public FullScreenImageFragment build() {
final FullScreenImageFragment fragment = new FullScreenImageFragment();
final Bundle bundle = new Bundle();
if (this.url != null) {
bundle.putString(ARGUMENT_URL, this.url);
}
if (this.loadingUrl!= null) {
bundle.putString(ARGUMENT_LOADING_URL, this.loadingUrl);
}
if (this.bitmap != null) {
bundle.putParcelable(ARGUMENT_BITMAP, this.bitmap);
}
if (this.loadingBitmap != null) {
bundle.putParcelable(ARGUMENT_LOADING_BITMAP, this.loadingBitmap);
}
bundle.putBoolean(ARGUMENT_LOADING_BLUR, loadingBlur);
fragment.setArguments(bundle);
return fragment;
}
}
}
| java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/library/src/main/java/com/dmallcott/dismissibleimageview/blur_transformation/FastBlur.java | library/src/main/java/com/dmallcott/dismissibleimageview/blur_transformation/FastBlur.java | package com.dmallcott.dismissibleimageview.blur_transformation;
import android.graphics.Bitmap;
/**
* Copyright (C) 2017 Wasabeef
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class FastBlur {
public static Bitmap blur(Bitmap sentBitmap, int radius, boolean canReuseInBitmap) {
// Stack Blur v1.0 from
// http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
//
// Java Author: Mario Klingemann <mario at quasimondo.com>
// http://incubator.quasimondo.com
// created Feburary 29, 2004
// Android port : Yahel Bouaziz <yahel at kayenko.com>
// http://www.kayenko.com
// ported april 5th, 2012
// This is a compromise between Gaussian Blur and Box blur
// It creates much better looking blurs than Box Blur, but is
// 7x faster than my Gaussian Blur implementation.
//
// I called it Stack Blur because this describes best how this
// filter works internally: it creates a kind of moving stack
// of colors whilst scanning through the image. Thereby it
// just has to add one new block of color to the right side
// of the stack and remove the leftmost color. The remaining
// colors on the topmost layer of the stack are either added on
// or reduced by one, depending on if they are on the right or
// on the left side of the stack.
//
// If you are using this algorithm in your code please add
// the following line:
//
// Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>
Bitmap bitmap;
if (canReuseInBitmap) {
bitmap = sentBitmap;
} else {
bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
}
if (radius < 1) {
return (null);
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int[] pix = new int[w * h];
bitmap.getPixels(pix, 0, w, 0, 0, w, h);
int wm = w - 1;
int hm = h - 1;
int wh = w * h;
int div = radius + radius + 1;
int r[] = new int[wh];
int g[] = new int[wh];
int b[] = new int[wh];
int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
int vmin[] = new int[Math.max(w, h)];
int divsum = (div + 1) >> 1;
divsum *= divsum;
int dv[] = new int[256 * divsum];
for (i = 0; i < 256 * divsum; i++) {
dv[i] = (i / divsum);
}
yw = yi = 0;
int[][] stack = new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
int r1 = radius + 1;
int routsum, goutsum, boutsum;
int rinsum, ginsum, binsum;
for (y = 0; y < h; y++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
for (i = -radius; i <= radius; i++) {
p = pix[yi + Math.min(wm, Math.max(i, 0))];
sir = stack[i + radius];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rbs = r1 - Math.abs(i);
rsum += sir[0] * rbs;
gsum += sir[1] * rbs;
bsum += sir[2] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
}
stackpointer = radius;
for (x = 0; x < w; x++) {
r[yi] = dv[rsum];
g[yi] = dv[gsum];
b[yi] = dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (y == 0) {
vmin[x] = Math.min(x + radius + 1, wm);
}
p = pix[yw + vmin[x]];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[(stackpointer) % div];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi++;
}
yw += w;
}
for (x = 0; x < w; x++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
yp = -radius * w;
for (i = -radius; i <= radius; i++) {
yi = Math.max(0, yp) + x;
sir = stack[i + radius];
sir[0] = r[yi];
sir[1] = g[yi];
sir[2] = b[yi];
rbs = r1 - Math.abs(i);
rsum += r[yi] * rbs;
gsum += g[yi] * rbs;
bsum += b[yi] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
if (i < hm) {
yp += w;
}
}
yi = x;
stackpointer = radius;
for (y = 0; y < h; y++) {
// Preserve alpha channel: ( 0xff000000 & pix[yi] )
pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (x == 0) {
vmin[y] = Math.min(y + r1, hm) * w;
}
p = x + vmin[y];
sir[0] = r[p];
sir[1] = g[p];
sir[2] = b[p];
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi += w;
}
}
bitmap.setPixels(pix, 0, w, 0, 0, w, h);
return (bitmap);
}
}
| java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/library/src/main/java/com/dmallcott/dismissibleimageview/blur_transformation/RsBlur.java | library/src/main/java/com/dmallcott/dismissibleimageview/blur_transformation/RsBlur.java | package com.dmallcott.dismissibleimageview.blur_transformation;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RSRuntimeException;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
/**
* Copyright (C) 2017 Wasabeef
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class RsBlur {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public static Bitmap blur(Context context, Bitmap bitmap, int radius) throws RSRuntimeException {
RenderScript rs = null;
Allocation input = null;
Allocation output = null;
ScriptIntrinsicBlur blur = null;
try {
rs = RenderScript.create(context);
rs.setMessageHandler(new RenderScript.RSMessageHandler());
input = Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE,
Allocation.USAGE_SCRIPT);
output = Allocation.createTyped(rs, input.getType());
blur = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
blur.setInput(input);
blur.setRadius(radius);
blur.forEach(output);
output.copyTo(bitmap);
} finally {
if (rs != null) {
rs.destroy();
}
if (input != null) {
input.destroy();
}
if (output != null) {
output.destroy();
}
if (blur != null) {
blur.destroy();
}
}
return bitmap;
}
}
| java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/library/src/main/java/com/dmallcott/dismissibleimageview/blur_transformation/BlurTransformation.java | library/src/main/java/com/dmallcott/dismissibleimageview/blur_transformation/BlurTransformation.java | package com.dmallcott.dismissibleimageview.blur_transformation;
/**
* Copyright (C) 2017 Wasabeef
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.renderscript.RSRuntimeException;
import com.squareup.picasso.Transformation;
public class BlurTransformation implements Transformation {
private static int MAX_RADIUS = 25;
private static int DEFAULT_DOWN_SAMPLING = 1;
private Context mContext;
private int mRadius;
private int mSampling;
public BlurTransformation(Context context) {
this(context, MAX_RADIUS, DEFAULT_DOWN_SAMPLING);
}
public BlurTransformation(Context context, int radius) {
this(context, radius, DEFAULT_DOWN_SAMPLING);
}
public BlurTransformation(Context context, int radius, int sampling) {
mContext = context.getApplicationContext();
mRadius = radius;
mSampling = sampling;
}
@Override public Bitmap transform(Bitmap source) {
int scaledWidth = source.getWidth() / mSampling;
int scaledHeight = source.getHeight() / mSampling;
Bitmap bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.scale(1 / (float) mSampling, 1 / (float) mSampling);
Paint paint = new Paint();
paint.setFlags(Paint.FILTER_BITMAP_FLAG);
canvas.drawBitmap(source, 0, 0, paint);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
try {
bitmap = RsBlur.blur(mContext, bitmap, mRadius);
} catch (RSRuntimeException e) {
bitmap = FastBlur.blur(bitmap, mRadius, true);
}
} else {
bitmap = FastBlur.blur(bitmap, mRadius, true);
}
//source.recycle();
return bitmap;
}
@Override public String key() {
return "BlurTransformation(radius=" + mRadius + ", sampling=" + mSampling + ")";
}
}
| java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
dmallcott/DismissibleImageView | https://github.com/dmallcott/DismissibleImageView/blob/f6a970d614c7d9725f2dfb702dfded8651126846/library/src/androidTest/java/com/dmallcott/dismissibleimageview/ExampleInstrumentedTest.java | library/src/androidTest/java/com/dmallcott/dismissibleimageview/ExampleInstrumentedTest.java | package com.dmallcott.dismissibleimageview;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.dmallcott.dismissibleimageview.test", appContext.getPackageName());
}
}
| java | Apache-2.0 | f6a970d614c7d9725f2dfb702dfded8651126846 | 2026-01-05T02:38:47.877787Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/test/java/id/web/ard/springbootwebfluxjjwt/SpringBootWebfluxJjwtApplicationTests.java | src/test/java/id/web/ard/springbootwebfluxjjwt/SpringBootWebfluxJjwtApplicationTests.java | package id.web.ard.springbootwebfluxjjwt;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
}
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/SpringBootWebfluxJjwtApplication.java | src/main/java/com/ard333/springbootwebfluxjjwt/SpringBootWebfluxJjwtApplication.java | package com.ard333.springbootwebfluxjjwt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootWebfluxJjwtApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootWebfluxJjwtApplication.class, args);
}
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/service/UserService.java | src/main/java/com/ard333/springbootwebfluxjjwt/service/UserService.java | package com.ard333.springbootwebfluxjjwt.service;
import com.ard333.springbootwebfluxjjwt.model.User;
import com.ard333.springbootwebfluxjjwt.model.security.Role;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
/**
* This is just an example, you can load the user from the database from the repository.
*
*/
@Service
public class UserService {
private Map<String, User> data;
@PostConstruct
public void init() {
data = new HashMap<>();
//username:passwowrd -> user:user
data.put("user", new User("user", "cBrlgyL2GI2GINuLUUwgojITuIufFycpLG4490dhGtY=", true, Arrays.asList(Role.ROLE_USER)));
//username:passwowrd -> admin:admin
data.put("admin", new User("admin", "dQNjUIMorJb8Ubj2+wVGYp6eAeYkdekqAcnYp+aRq5w=", true, Arrays.asList(Role.ROLE_ADMIN)));
}
public Mono<User> findByUsername(String username) {
return Mono.justOrEmpty(data.get(username));
}
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/model/Message.java | src/main/java/com/ard333/springbootwebfluxjjwt/model/Message.java | package com.ard333.springbootwebfluxjjwt.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Message {
private String content;
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/model/User.java | src/main/java/com/ard333/springbootwebfluxjjwt/model/User.java | package com.ard333.springbootwebfluxjjwt.model;
import com.ard333.springbootwebfluxjjwt.model.security.Role;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User implements UserDetails {
private static final long serialVersionUID = 1L;
private String username;
private String password;
@Getter @Setter
private Boolean enabled;
@Getter @Setter
private List<Role> roles;
@Override
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public boolean isAccountNonExpired() {
return false;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
}
@Override
public boolean isEnabled() {
return this.enabled;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.roles.stream().map(authority -> new SimpleGrantedAuthority(authority.name())).collect(Collectors.toList());
}
@JsonIgnore
@Override
public String getPassword() {
return password;
}
@JsonProperty
public void setPassword(String password) {
this.password = password;
}
} | java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/model/security/AuthRequest.java | src/main/java/com/ard333/springbootwebfluxjjwt/model/security/AuthRequest.java | package com.ard333.springbootwebfluxjjwt.model.security;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AuthRequest {
private String username;
private String password;
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/model/security/AuthResponse.java | src/main/java/com/ard333/springbootwebfluxjjwt/model/security/AuthResponse.java | package com.ard333.springbootwebfluxjjwt.model.security;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AuthResponse {
private String token;
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/model/security/Role.java | src/main/java/com/ard333/springbootwebfluxjjwt/model/security/Role.java | package com.ard333.springbootwebfluxjjwt.model.security;
public enum Role {
ROLE_USER, ROLE_ADMIN
} | java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/security/WebSecurityConfig.java | src/main/java/com/ard333/springbootwebfluxjjwt/security/WebSecurityConfig.java | package com.ard333.springbootwebfluxjjwt.security;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import lombok.AllArgsConstructor;
import reactor.core.publisher.Mono;
@AllArgsConstructor
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class WebSecurityConfig {
private AuthenticationManager authenticationManager;
private SecurityContextRepository securityContextRepository;
@Bean
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
return http
.exceptionHandling()
.authenticationEntryPoint((swe, e) ->
Mono.fromRunnable(() -> swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED))
).accessDeniedHandler((swe, e) ->
Mono.fromRunnable(() -> swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN))
).and()
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.authenticationManager(authenticationManager)
.securityContextRepository(securityContextRepository)
.authorizeExchange()
.pathMatchers(HttpMethod.OPTIONS).permitAll()
.pathMatchers("/login").permitAll()
.anyExchange().authenticated()
.and().build();
}
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/security/JWTUtil.java | src/main/java/com/ard333/springbootwebfluxjjwt/security/JWTUtil.java | package com.ard333.springbootwebfluxjjwt.security;
import com.ard333.springbootwebfluxjjwt.model.User;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class JWTUtil {
@Value("${springbootwebfluxjjwt.jjwt.secret}")
private String secret;
@Value("${springbootwebfluxjjwt.jjwt.expiration}")
private String expirationTime;
private Key key;
@PostConstruct
public void init() {
this.key = Keys.hmacShaKeyFor(secret.getBytes());
}
public Claims getAllClaimsFromToken(String token) {
return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
}
public String getUsernameFromToken(String token) {
return getAllClaimsFromToken(token).getSubject();
}
public Date getExpirationDateFromToken(String token) {
return getAllClaimsFromToken(token).getExpiration();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
public String generateToken(User user) {
Map<String, Object> claims = new HashMap<>();
claims.put("role", user.getRoles());
return doGenerateToken(claims, user.getUsername());
}
private String doGenerateToken(Map<String, Object> claims, String username) {
Long expirationTimeLong = Long.parseLong(expirationTime); //in second
final Date createdDate = new Date();
final Date expirationDate = new Date(createdDate.getTime() + expirationTimeLong * 1000);
return Jwts.builder()
.setClaims(claims)
.setSubject(username)
.setIssuedAt(createdDate)
.setExpiration(expirationDate)
.signWith(key)
.compact();
}
public Boolean validateToken(String token) {
return !isTokenExpired(token);
}
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/security/PBKDF2Encoder.java | src/main/java/com/ard333/springbootwebfluxjjwt/security/PBKDF2Encoder.java | package com.ard333.springbootwebfluxjjwt.security;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
@Component
public class PBKDF2Encoder implements PasswordEncoder {
@Value("${springbootwebfluxjjwt.password.encoder.secret}")
private String secret;
@Value("${springbootwebfluxjjwt.password.encoder.iteration}")
private Integer iteration;
@Value("${springbootwebfluxjjwt.password.encoder.keylength}")
private Integer keylength;
/**
* More info (https://www.owasp.org/index.php/Hashing_Java) 404 :(
* @param cs password
* @return encoded password
*/
@Override
public String encode(CharSequence cs) {
try {
byte[] result = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")
.generateSecret(new PBEKeySpec(cs.toString().toCharArray(), secret.getBytes(), iteration, keylength))
.getEncoded();
return Base64.getEncoder().encodeToString(result);
} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
throw new RuntimeException(ex);
}
}
@Override
public boolean matches(CharSequence cs, String string) {
return encode(cs).equals(string);
}
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/security/AuthenticationManager.java | src/main/java/com/ard333/springbootwebfluxjjwt/security/AuthenticationManager.java | package com.ard333.springbootwebfluxjjwt.security;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.stream.Collectors;
@Component
@AllArgsConstructor
public class AuthenticationManager implements ReactiveAuthenticationManager {
private JWTUtil jwtUtil;
@Override
@SuppressWarnings("unchecked")
public Mono<Authentication> authenticate(Authentication authentication) {
String authToken = authentication.getCredentials().toString();
String username = jwtUtil.getUsernameFromToken(authToken);
return Mono.just(jwtUtil.validateToken(authToken))
.filter(valid -> valid)
.switchIfEmpty(Mono.empty())
.map(valid -> {
Claims claims = jwtUtil.getAllClaimsFromToken(authToken);
List<String> rolesMap = claims.get("role", List.class);
return new UsernamePasswordAuthenticationToken(
username,
null,
rolesMap.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList())
);
});
}
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/security/CORSFilter.java | src/main/java/com/ard333/springbootwebfluxjjwt/security/CORSFilter.java | package com.ard333.springbootwebfluxjjwt.security;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.config.CorsRegistry;
import org.springframework.web.reactive.config.EnableWebFlux;
import org.springframework.web.reactive.config.WebFluxConfigurer;
@Configuration
@EnableWebFlux
public class CORSFilter implements WebFluxConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*");
}
} | java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/security/SecurityContextRepository.java | src/main/java/com/ard333/springbootwebfluxjjwt/security/SecurityContextRepository.java | package com.ard333.springbootwebfluxjjwt.security;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class SecurityContextRepository implements ServerSecurityContextRepository {
private AuthenticationManager authenticationManager;
public SecurityContextRepository(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public Mono<Void> save(ServerWebExchange swe, SecurityContext sc) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Mono<SecurityContext> load(ServerWebExchange swe) {
return Mono.justOrEmpty(swe.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION))
.filter(authHeader -> authHeader.startsWith("Bearer "))
.flatMap(authHeader -> {
String authToken = authHeader.substring(7);
Authentication auth = new UsernamePasswordAuthenticationToken(authToken, authToken);
return this.authenticationManager.authenticate(auth).map(SecurityContextImpl::new);
});
}
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/security/model/AuthRequest.java | src/main/java/com/ard333/springbootwebfluxjjwt/security/model/AuthRequest.java | package com.ard333.springbootwebfluxjjwt.security.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
*
* @author ard333
*/
@Data @NoArgsConstructor @AllArgsConstructor @ToString
public class AuthRequest {
private String username;
private String password;
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/security/model/AuthResponse.java | src/main/java/com/ard333/springbootwebfluxjjwt/security/model/AuthResponse.java | package com.ard333.springbootwebfluxjjwt.security.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
*
* @author ard333
*/
@Data @NoArgsConstructor @AllArgsConstructor @ToString
public class AuthResponse {
private String token;
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/security/model/Role.java | src/main/java/com/ard333/springbootwebfluxjjwt/security/model/Role.java | package com.ard333.springbootwebfluxjjwt.security.model;
/**
*
* @author ard333
*/
public enum Role {
ROLE_USER, ROLE_ADMIN
} | java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/rest/AuthenticationREST.java | src/main/java/com/ard333/springbootwebfluxjjwt/rest/AuthenticationREST.java | package com.ard333.springbootwebfluxjjwt.rest;
import com.ard333.springbootwebfluxjjwt.model.security.AuthRequest;
import com.ard333.springbootwebfluxjjwt.model.security.AuthResponse;
import com.ard333.springbootwebfluxjjwt.security.JWTUtil;
import com.ard333.springbootwebfluxjjwt.security.PBKDF2Encoder;
import com.ard333.springbootwebfluxjjwt.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import lombok.AllArgsConstructor;
import reactor.core.publisher.Mono;
@AllArgsConstructor
@RestController
public class AuthenticationREST {
private JWTUtil jwtUtil;
private PBKDF2Encoder passwordEncoder;
private UserService userService;
@PostMapping("/login")
public Mono<ResponseEntity<AuthResponse>> login(@RequestBody AuthRequest ar) {
return userService.findByUsername(ar.getUsername())
.filter(userDetails -> passwordEncoder.encode(ar.getPassword()).equals(userDetails.getPassword()))
.map(userDetails -> ResponseEntity.ok(new AuthResponse(jwtUtil.generateToken(userDetails))))
.switchIfEmpty(Mono.just(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()));
}
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
ard333/spring-boot-webflux-jjwt | https://github.com/ard333/spring-boot-webflux-jjwt/blob/8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51/src/main/java/com/ard333/springbootwebfluxjjwt/rest/ResourceREST.java | src/main/java/com/ard333/springbootwebfluxjjwt/rest/ResourceREST.java | package com.ard333.springbootwebfluxjjwt.rest;
import com.ard333.springbootwebfluxjjwt.model.Message;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class ResourceREST {
@GetMapping("/resource/user")
@PreAuthorize("hasRole('USER')")
public Mono<ResponseEntity<Message>> user() {
return Mono.just(ResponseEntity.ok(new Message("Content for user")));
}
@GetMapping("/resource/admin")
@PreAuthorize("hasRole('ADMIN')")
public Mono<ResponseEntity<Message>> admin() {
return Mono.just(ResponseEntity.ok(new Message("Content for admin")));
}
@GetMapping("/resource/user-or-admin")
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public Mono<ResponseEntity<Message>> userOrAdmin() {
return Mono.just(ResponseEntity.ok(new Message("Content for user or admin")));
}
}
| java | Apache-2.0 | 8a9dabc6e1e00ff93176aaa2c6fcc109e1c1dc51 | 2026-01-05T02:39:38.144815Z | false |
rjsvieira/circularView | https://github.com/rjsvieira/circularView/blob/2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3/circularview/src/main/java/rjsv/circularview/CircleView.java | circularview/src/main/java/rjsv/circularview/CircleView.java | package rjsv.circularview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import rjsv.circularview.utils.GeneralUtils;
public class CircleView extends View {
// -90 offset indicates that the progress starts from 0h
private static final int ANGLE_OFFSET = -90;
private static final int CLICK_THRESHOLD = 5;
private static int circlePadding = 25;
private boolean isCircleClockwise = true;
private boolean isRotationEnabled = true;
/**
* Circle View values. Current, Minimum and Maximum
*/
private float progressCurrentValue = 0;
private float progressMinimumValue = 0;
private float progressMaximumValue = 100;
/**
* Progress Arc Configuration
*/
private float progressWidth = 20;
private float progressAngle = 0;
private float progressStep = 0;
private boolean progressStepAsInteger = false;
private Paint progressPaint;
/**
* Arc Configuration
*/
private Paint arcPaint;
private Paint arcBorderPaint;
private RectF arcRect = new RectF();
private boolean arcHasBorder = false;
private int arcWidth = 20;
private int arcRadius = 0;
/**
* Indicator Configuration
*/
private boolean hasIndicator = false;
private boolean progressBarSquared = false;
private int indicatorRadius = 4;
private Paint indicatorPaint;
/**
* Value Text Configuration
*/
private boolean textEnabled = true;
private float textSize = 72;
private int textColor;
private int textDecimalPlaces = 1;
private Paint textPaint;
private Rect textRect = new Rect();
private Typeface textTypeFace = Typeface.DEFAULT;
/**
* Suffix Text Configuration
*/
private boolean suffixEnabled = false;
private String suffixValue = "";
private Paint suffixPaint;
private Rect suffixRect;
/**
* Auxiliary Variables
*/
private float translationOnX;
private float translationOnY;
private float indicationPositionX;
private float indicationPositionY;
private float touchStartX;
private float touchStartY;
// Listener
private CircleViewChangeListener circleViewChangeListener;
// Constructors
public CircleView(Context context) {
super(context);
init(context, null);
}
public CircleView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
float density = getResources().getDisplayMetrics().density;
// Defaults, may need to link this into theme settings
int arcColor = getColor(context, R.color.color_arc);
int arcBorderColor = getColor(context, R.color.color_arc_border);
int progressColor = getColor(context, R.color.color_progress);
textColor = getColor(context, R.color.color_text);
int indicatorColor = getColor(context, R.color.color_indicator);
progressWidth = (int) (progressWidth * density);
arcWidth = (int) (arcWidth * density);
textSize = (int) (textSize * density);
if (attrs != null) {
// Attribute initialization
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView, 0, 0);
progressCurrentValue = a.getFloat(R.styleable.CircleView_progressCurrentValue, progressCurrentValue);
progressMinimumValue = a.getFloat(R.styleable.CircleView_progressMinimumValue, progressMinimumValue);
progressMaximumValue = a.getFloat(R.styleable.CircleView_progressMaximumValue, progressMaximumValue);
progressStep = a.getFloat(R.styleable.CircleView_progressStepValue, progressStep);
progressStepAsInteger = a.getBoolean(R.styleable.CircleView_progressStepAsInteger, progressStepAsInteger);
progressWidth = (int) a.getDimension(R.styleable.CircleView_progressWidth, progressWidth);
progressColor = a.getColor(R.styleable.CircleView_progressColor, progressColor);
arcWidth = (int) a.getDimension(R.styleable.CircleView_arcWidth, arcWidth);
arcColor = a.getColor(R.styleable.CircleView_arcColor, arcColor);
arcBorderColor = a.getColor(R.styleable.CircleView_arcBorderColor, arcBorderColor);
arcHasBorder = a.getBoolean(R.styleable.CircleView_arcHasBorder, arcHasBorder);
textSize = (int) a.getDimension(R.styleable.CircleView_textSize, textSize);
textColor = a.getColor(R.styleable.CircleView_textColor, textColor);
textDecimalPlaces = a.getInteger(R.styleable.CircleView_textDecimalPlaces, textDecimalPlaces);
textEnabled = a.getBoolean(R.styleable.CircleView_textEnabled, textEnabled);
String textTypeFacePath = a.getString(R.styleable.CircleView_textFont);
if (textTypeFacePath != null && GeneralUtils.fileExistsInAssets(getContext(), textTypeFacePath)) {
textTypeFace = Typeface.createFromAsset(getResources().getAssets(), textTypeFacePath);
}
suffixEnabled = a.getBoolean(R.styleable.CircleView_suffixEnabled, suffixEnabled);
suffixValue = a.getString(R.styleable.CircleView_suffixValue);
hasIndicator = a.getBoolean(R.styleable.CircleView_hasIndicator, hasIndicator);
progressBarSquared = a.getBoolean(R.styleable.CircleView_progressBarSquared, progressBarSquared);
indicatorRadius = a.getInt(R.styleable.CircleView_indicatorRadius, indicatorRadius);
indicatorColor = a.getColor(R.styleable.CircleView_indicatorColor, indicatorColor);
isCircleClockwise = a.getBoolean(R.styleable.CircleView_clockwise, isCircleClockwise);
isRotationEnabled = a.getBoolean(R.styleable.CircleView_enabled, isRotationEnabled);
a.recycle();
}
// range check
progressCurrentValue = (progressCurrentValue > progressMaximumValue) ? progressMaximumValue : progressCurrentValue;
progressCurrentValue = (progressCurrentValue < progressMinimumValue) ? progressMinimumValue : progressCurrentValue;
progressAngle = progressCurrentValue / valuePerDegree(progressMaximumValue);
arcPaint = new Paint();
arcPaint.setColor(arcColor);
arcPaint.setAntiAlias(true);
arcPaint.setStrokeCap(Paint.Cap.ROUND);
arcPaint.setStrokeJoin(Paint.Join.ROUND);
arcPaint.setStyle(Paint.Style.STROKE);
arcPaint.setStrokeWidth(arcWidth);
arcBorderPaint = new Paint();
arcBorderPaint.setColor(arcBorderColor);
arcBorderPaint.setAntiAlias(true);
arcBorderPaint.setStrokeCap(Paint.Cap.ROUND);
arcBorderPaint.setStrokeJoin(Paint.Join.ROUND);
arcBorderPaint.setStyle(Paint.Style.STROKE);
arcBorderPaint.setStrokeWidth((float) (arcWidth * 1.2));
progressPaint = new Paint();
progressPaint.setColor(progressColor);
progressPaint.setAntiAlias(true);
progressPaint.setStrokeCap(progressBarSquared ? Paint.Cap.SQUARE : Paint.Cap.ROUND);
progressPaint.setStrokeJoin(Paint.Join.ROUND);
progressPaint.setStyle(Paint.Style.STROKE);
progressPaint.setStrokeWidth(arcHasBorder ? progressWidth : arcWidth);
indicatorPaint = new Paint();
indicatorPaint.setColor(indicatorColor);
indicatorPaint.setAntiAlias(true);
indicatorPaint.setStrokeCap(Paint.Cap.ROUND);
indicatorPaint.setStrokeJoin(Paint.Join.ROUND);
indicatorPaint.setStyle(Paint.Style.FILL_AND_STROKE);
indicatorPaint.setStrokeWidth(indicatorRadius);
textPaint = new Paint();
textPaint.setColor(textColor);
textPaint.setAntiAlias(true);
textPaint.setStyle(Paint.Style.FILL);
textPaint.setTextSize(textSize);
textPaint.setTypeface(textTypeFace);
if (suffixEnabled) {
suffixRect = new Rect();
suffixPaint = new Paint();
suffixPaint.setColor(textColor);
suffixPaint.setAntiAlias(true);
suffixPaint.setStyle(Paint.Style.FILL);
suffixPaint.setTextSize(textSize / 2);
suffixPaint.setTypeface(textTypeFace);
}
}
// Overridden View Methods
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
final int min = Math.min(width, height);
translationOnX = width * 0.5f;
translationOnY = height * 0.5f;
int arcDiameter = min - circlePadding - indicatorRadius;
arcRadius = arcDiameter / 2;
float top = height / 2 - (arcDiameter / 2);
float left = width / 2 - (arcDiameter / 2);
arcRect.set(left, top, left + arcDiameter, top + arcDiameter);
updateIndicatorPosition();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
this.setBackgroundColor(Color.TRANSPARENT);
if (!isCircleClockwise) {
canvas.scale(-1, 1, arcRect.centerX(), arcRect.centerY());
}
if (textEnabled) {
String textPoint = progressStepAsInteger ? String.valueOf((int) progressCurrentValue) : String.valueOf(progressCurrentValue);
textPaint.getTextBounds(textPoint, 0, textPoint.length(), textRect);
// center the text
int xPos = canvas.getWidth() / 2 - textRect.width() / 2;
int yPos = (int) ((arcRect.centerY()) - ((textPaint.descent() + textPaint.ascent()) / 2));
canvas.drawText(textPoint, xPos, yPos, textPaint);
if (suffixEnabled) {
String suffix = suffixValue;
suffixPaint.getTextBounds(suffix, 0, suffix.length(), suffixRect);
xPos += textRect.width() * 1.5;
canvas.drawText(suffix, xPos, yPos, suffixPaint);
}
}
if (arcHasBorder) {
canvas.drawArc(arcRect, ANGLE_OFFSET, 360, false, arcBorderPaint);
}
canvas.drawArc(arcRect, ANGLE_OFFSET + progressAngle, 360 - progressAngle, false, arcPaint);
canvas.drawArc(arcRect, ANGLE_OFFSET, progressAngle, false, progressPaint);
if (isRotationEnabled && hasIndicator) {
canvas.translate(translationOnX - indicationPositionX, translationOnY - indicationPositionY);
canvas.drawCircle(0, 0, indicatorRadius, indicatorPaint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (isRotationEnabled) {
this.getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchStartX = event.getX();
touchStartY = event.getY();
if (circleViewChangeListener != null) {
circleViewChangeListener.onStartTracking(this);
}
break;
case MotionEvent.ACTION_MOVE:
float touchAngle = convertTouchEventPointToAngle(event.getX(), event.getY());
updateProgress(touchAngle, true, GeneralUtils.isAClick(CLICK_THRESHOLD, touchStartX, event.getX(), touchStartY, event.getY()));
break;
case MotionEvent.ACTION_UP:
if (progressStep > 0) {
applyProgressStepRestriction();
}
if (circleViewChangeListener != null) {
circleViewChangeListener.onStopTracking(this);
}
this.getParent().requestDisallowInterceptTouchEvent(false);
break;
case MotionEvent.ACTION_CANCEL:
if (circleViewChangeListener != null) {
circleViewChangeListener.onStopTracking(this);
}
this.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
return true;
}
return false;
}
// General Methods and Utils
public float convertAngleToProgress(float angle) {
return valuePerDegree(progressMaximumValue) * angle;
}
public float convertProgressToAngle(float progress) {
return (progress / progressMaximumValue) * 360.f;
}
private float convertTouchEventPointToAngle(float xPos, float yPos) {
float x = xPos - translationOnX;
float y = yPos - translationOnY;
x = (isCircleClockwise) ? x : -x;
float angle = (float) Math.toDegrees(Math.atan2(y, x) + (Math.PI / 2));
angle = (angle < 0) ? (angle + 360) : angle;
return angle;
}
private float valuePerDegree(float max) {
return max / 360.0f;
}
private int getColor(Context context, int id) {
final int version = Build.VERSION.SDK_INT;
if (version >= 23) {
return ContextCompat.getColor(context, id);
} else {
return context.getResources().getColor(id);
}
}
private void updateIndicatorPosition() {
float thumbAngle = progressAngle + 90;
indicationPositionX = (float) (arcRadius * Math.cos(Math.toRadians(thumbAngle)));
indicationPositionY = (float) (arcRadius * Math.sin(Math.toRadians(thumbAngle)));
}
private void updateProgress(float newValue, boolean isAngle, boolean isAClick) {
if (isAngle) {
if (!isAClick) {
newValue = getValueForQuadrantCrossing(progressAngle, newValue);
}
progressCurrentValue = GeneralUtils.round(convertAngleToProgress(newValue), textDecimalPlaces);
progressAngle = newValue;
} else {
progressCurrentValue = GeneralUtils.round(newValue, textDecimalPlaces);
progressAngle = convertProgressToAngle(newValue);
}
if (circleViewChangeListener != null) {
circleViewChangeListener.onPointsChanged(this, progressCurrentValue);
}
updateIndicatorPosition();
invalidate();
}
private float getValueForQuadrantCrossing(float oldProgress, float newProgress) {
float result = newProgress;
int oldProgressQuadrant = getProgressQuadrant(oldProgress);
int newProgressQuadrant = getProgressQuadrant(newProgress);
if (oldProgressQuadrant == 4 && (newProgressQuadrant != 4 && newProgressQuadrant != 3)) {
result = 360.0f;
} else if (oldProgressQuadrant == 1 && (newProgressQuadrant != 2 && newProgressQuadrant != 1)) {
result = 0.0f;
}
return result;
}
private int getProgressQuadrant(float progress) {
int quadrant;
if (progress >= 0 && progress <= 90.0f) {
quadrant = 1;
} else if (progress <= 180) {
quadrant = 2;
} else if (progress <= 270) {
quadrant = 3;
} else {
quadrant = 4;
}
return quadrant;
}
private void applyProgressStepRestriction() {
float floor = (float) Math.floor(progressCurrentValue);
float ceiling = (float) Math.ceil(progressCurrentValue);
float roundToNextStep;
if (progressCurrentValue - floor <= ceiling - progressCurrentValue) {
roundToNextStep = floor;
} else {
roundToNextStep = ceiling;
}
setProgressValue(roundToNextStep);
}
public float getProgressValue() {
return progressCurrentValue;
}
public void setProgressValue(float progressValue) {
if (progressValue >= progressMinimumValue) {
if (progressValue > progressMaximumValue) {
progressValue = progressValue % progressMaximumValue;
}
updateProgress(progressValue, false, false);
}
}
// Setters and Getters
public boolean isSuffixEnabled() {
return suffixEnabled;
}
public void setSuffixEnabled(boolean suffixEnabled) {
this.suffixEnabled = suffixEnabled;
}
public String getSuffixValue() {
return suffixValue;
}
public void setSuffixValue(String suffixValue) {
this.suffixValue = suffixValue;
}
public boolean isProgressStepAsInteger() {
return progressStepAsInteger;
}
public void setProgressStepAsInteger(boolean progressStepAsInteger) {
this.progressStepAsInteger = progressStepAsInteger;
}
public float getProgressAngle() {
return progressAngle;
}
public void setProgressAngle(float progressAngle) {
if (progressAngle >= 0) {
if (progressAngle >= 360.0f) {
progressAngle = progressAngle % 360.f;
}
updateProgress(progressAngle, true, false);
}
}
public float getProgressWidth() {
return progressWidth;
}
public void setProgressWidth(int progressWidth) {
this.progressWidth = progressWidth;
progressPaint.setStrokeWidth(progressWidth);
}
public int getArcWidth() {
return arcWidth;
}
public void setArcWidth(int arcWidth) {
this.arcWidth = arcWidth;
arcPaint.setStrokeWidth(arcWidth);
}
public boolean isClockwise() {
return isCircleClockwise;
}
public void setClockwise(boolean isClockwise) {
isCircleClockwise = isClockwise;
}
public boolean isEnabled() {
return isRotationEnabled;
}
public void setEnabled(boolean enabled) {
this.isRotationEnabled = enabled;
}
public int getProgressColor() {
return progressPaint.getColor();
}
public void setProgressColor(int color) {
progressPaint.setColor(color);
invalidate();
}
public int getArcColor() {
return arcPaint.getColor();
}
public void setArcColor(int color) {
arcPaint.setColor(color);
invalidate();
}
public void setTextColor(int textColor) {
textPaint.setColor(textColor);
invalidate();
}
public void setTextSize(float textSize) {
this.textSize = textSize;
textPaint.setTextSize(textSize);
invalidate();
}
public float getMaximumValue() {
return progressMaximumValue;
}
public void setMaximumValue(int progressMaximumValue) {
if (progressMaximumValue >= progressMinimumValue) {
this.progressMaximumValue = progressMaximumValue;
}
}
public float getMinimumValue() {
return progressMinimumValue;
}
public void setMinimumValue(int min) {
if (progressMaximumValue >= min) {
progressMinimumValue = min;
}
}
public float getProgressStep() {
return progressStep;
}
public void setProgressStep(int step) {
progressStep = step;
}
public Typeface getTextTypeFace() {
return textTypeFace;
}
public void setTextTypeFace(Typeface textTypeFace) {
this.textTypeFace = textTypeFace;
}
public void setOnCircleViewChangeListener(CircleViewChangeListener onCircleViewChangeListener) {
circleViewChangeListener = onCircleViewChangeListener;
}
}
| java | Apache-2.0 | 2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3 | 2026-01-05T02:39:38.864843Z | false |
rjsvieira/circularView | https://github.com/rjsvieira/circularView/blob/2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3/circularview/src/main/java/rjsv/circularview/CircleViewChangeListener.java | circularview/src/main/java/rjsv/circularview/CircleViewChangeListener.java | package rjsv.circularview;
public interface CircleViewChangeListener {
void onPointsChanged(CircleView circleView, float points);
void onStartTracking(CircleView circleView);
void onStopTracking(CircleView circleView);
}
| java | Apache-2.0 | 2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3 | 2026-01-05T02:39:38.864843Z | false |
rjsvieira/circularView | https://github.com/rjsvieira/circularView/blob/2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3/circularview/src/main/java/rjsv/circularview/CircleViewAnimation.java | circularview/src/main/java/rjsv/circularview/CircleViewAnimation.java | package rjsv.circularview;
import android.os.Handler;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import rjsv.circularview.enumerators.AnimationStyle;
import rjsv.circularview.utils.CircleViewAnimationListener;
import rjsv.circularview.utils.Disposable;
/**
* Description
*
* @author <a href="mailto:ricardo.vieira@xpand-it.com">RJSV</a>
* @version $Revision : 1 $
*/
public class CircleViewAnimation extends Animation implements Disposable {
private CircleView circleView;
private float startValue;
private float endValue;
private float currentValue;
private long duration;
private boolean isAnimationRunning = false;
private AnimationStyle circleViewAnimationStyle;
private Interpolator circleViewInterpolator;
private CircleViewAnimationListener circleViewAnimationListener;
private Handler timerManager;
private Runnable timerOperation;
// Constructor
public CircleViewAnimation() {
this.startValue = 0;
this.endValue = 0;
this.circleViewAnimationStyle = AnimationStyle.PERIODIC;
this.circleViewAnimationListener = new CircleViewAnimationListener();
this.timerManager = new Handler();
this.timerOperation = new Runnable() {
public void run() {
//
}
};
setInterpolator(new LinearInterpolator());
}
public CircleViewAnimation setCircleView(CircleView circleView) {
this.circleView = circleView;
return this;
}
public CircleViewAnimation setDuration(float durationInMilliseconds) {
setDuration((long) durationInMilliseconds);
return this;
}
public CircleViewAnimation setDuration(int durationInMilliseconds) {
setDuration((long) durationInMilliseconds);
return this;
}
public CircleViewAnimation setAnimationStyle(AnimationStyle style) {
this.circleViewAnimationStyle = style;
return this;
}
public CircleViewAnimation setCustomAnimationListener(AnimationListener listener) {
this.circleViewAnimationListener.registerAnimationListener(listener);
setAnimationListener(listener != null ? circleViewAnimationListener : null);
return this;
}
public CircleViewAnimation setCustomInterpolator(Interpolator i) {
this.circleViewInterpolator = i;
super.setInterpolator(circleViewInterpolator);
return this;
}
public CircleViewAnimation setTimerOperationOnFinish(Runnable r) {
if (r != null) {
timerOperation = r;
}
return this;
}
// Overridden values
public void start(float startValue, float endValue) {
if (circleView != null && !isAnimationRunning) {
this.startValue = startValue;
this.endValue = endValue;
setDuration(duration == 0 ? startValue - endValue : duration);
isAnimationRunning = true;
circleView.startAnimation(this);
timerManager.postDelayed(timerOperation, duration * 1000);
}
}
public void stop() {
if (circleView != null && isAnimationRunning) {
isAnimationRunning = false;
timerManager.removeCallbacks(timerOperation);
circleView.clearAnimation();
}
}
@Override
public void start() {
start(circleView.getProgressValue(), 0);
}
@Override
public void setDuration(long durationInMilliseconds) {
duration = durationInMilliseconds;
super.setDuration(duration);
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation transformation) {
if (interpolatedTime == 1.0) {
stop();
}
currentValue = startValue + ((endValue - startValue) * interpolatedTime);
float changingValue = currentValue;
if (AnimationStyle.PERIODIC.equals(circleViewAnimationStyle)) {
changingValue = (int) changingValue;
}
circleView.setProgressValue(changingValue);
}
@Override
public void disposeData() {
this.setInterpolator(null);
circleViewInterpolator = null;
if (circleViewAnimationListener != null) {
circleViewAnimationListener.unregisterAnimationListeners();
circleViewAnimationListener = null;
}
if (timerManager != null) {
if (timerOperation != null) {
timerManager.removeCallbacks(timerOperation);
}
timerOperation = null;
timerManager = null;
}
}
} | java | Apache-2.0 | 2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3 | 2026-01-05T02:39:38.864843Z | false |
rjsvieira/circularView | https://github.com/rjsvieira/circularView/blob/2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3/circularview/src/main/java/rjsv/circularview/utils/Disposable.java | circularview/src/main/java/rjsv/circularview/utils/Disposable.java | package rjsv.circularview.utils;
/**
* Description
*
* @author <a href="mailto:ricardo.vieira@xpand-it.com">RJSV</a>
* @version $Revision : 1 $
*/
public interface Disposable {
void disposeData();
}
| java | Apache-2.0 | 2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3 | 2026-01-05T02:39:38.864843Z | false |
rjsvieira/circularView | https://github.com/rjsvieira/circularView/blob/2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3/circularview/src/main/java/rjsv/circularview/utils/CircleViewAnimationListener.java | circularview/src/main/java/rjsv/circularview/utils/CircleViewAnimationListener.java | package rjsv.circularview.utils;
import android.view.animation.Animation;
import java.util.ArrayList;
import java.util.List;
/**
* Description
*
* @author <a href="mailto:ricardo.vieira@xpand-it.com">RJSV</a>
* @version $Revision : 1 $
*/
public class CircleViewAnimationListener implements Animation.AnimationListener {
private List<Animation.AnimationListener> listeners;
public CircleViewAnimationListener() {
this.listeners = new ArrayList<>();
}
public void registerAnimationListener(Animation.AnimationListener listener) {
if (listener != null) {
this.listeners.add(listener);
} else {
this.unregisterAnimationListeners();
}
}
public void unregisterAnimationListeners() {
this.listeners.clear();
}
@Override
public void onAnimationStart(Animation animation) {
for (Animation.AnimationListener listener : listeners) {
listener.onAnimationStart(animation);
}
}
@Override
public void onAnimationEnd(Animation animation) {
for (Animation.AnimationListener listener : listeners) {
listener.onAnimationEnd(animation);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
for (Animation.AnimationListener listener : listeners) {
listener.onAnimationRepeat(animation);
}
}
}
| java | Apache-2.0 | 2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3 | 2026-01-05T02:39:38.864843Z | false |
rjsvieira/circularView | https://github.com/rjsvieira/circularView/blob/2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3/circularview/src/main/java/rjsv/circularview/utils/GeneralUtils.java | circularview/src/main/java/rjsv/circularview/utils/GeneralUtils.java | package rjsv.circularview.utils;
import android.content.Context;
import android.content.res.AssetManager;
import java.io.IOException;
import java.io.InputStream;
/**
* Description
*
* @author <a href="mailto:ricardo.vieira@xpand-it.com">RJSV</a>
* @version $Revision : 1 $
*/
public class GeneralUtils {
// Mathematical
public static double round(double value, int places) {
if (places < 0) {
return value;
}
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
public static float round(float number, int scale) {
int pow = 10;
for (int i = 1; i < scale; i++)
pow *= 10;
float tmp = number * pow;
return (float) (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) / pow;
}
public static boolean fileExistsInAssets(Context context, String pathInAssets) {
boolean result = false;
if (context != null) {
AssetManager mg = context.getResources().getAssets();
InputStream is;
try {
is = mg.open(pathInAssets);
result = true;
if (is != null) {
is.close();
}
} catch (IOException ex) {
result = false;
}
}
return result;
}
public static boolean isAClick(int threshold, float startX, float endX, float startY, float endY) {
float differenceX = Math.abs(startX - endX);
float differenceY = Math.abs(startY - endY);
if (differenceX > threshold || differenceY > threshold) {
return false;
}
return true;
}
}
| java | Apache-2.0 | 2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3 | 2026-01-05T02:39:38.864843Z | false |
rjsvieira/circularView | https://github.com/rjsvieira/circularView/blob/2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3/circularview/src/main/java/rjsv/circularview/enumerators/AnimationStyle.java | circularview/src/main/java/rjsv/circularview/enumerators/AnimationStyle.java | package rjsv.circularview.enumerators;
/**
* Description
*
* @author <a href="mailto:ricardo.vieira@xpand-it.com">RJSV</a>
* @version $Revision : 1 $
*/
public enum AnimationStyle {
CONTINUOUS,
PERIODIC
}
| java | Apache-2.0 | 2c8b3b8cb2e2fefbc19a891d5c4ae73532b846b3 | 2026-01-05T02:39:38.864843Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/Main.java | data_struct_study/src/Main.java |
/**
* 数据结构地图:
* 1、线性结构:动态数组、普通队列、栈、链表、哈希表。
* 2、树形结构:二分搜索树、AVL 树、红黑树
* 堆、线段树
* 多叉树:Trie、并查集
* 3、图结构:邻接表(与链地址法的哈希表很像,它是一个有 n 个链表的数组,
* arr[i] 存储的就是和 i 这个顶点相连接的其它顶点或和 i 这个顶点相连接的边。
* 邻接矩阵(一个 n * n 的二维数组,G(i,j) 表示从 i 到 j 有一个边)。
* 4、抽象数据结构:
* 线性表:动态数组、链表。
* 栈、队列。
* 集合、映射:
* 有序集合,有序映射
* 无序集合、无序映射
*
* 《算法导论》学习:第一、二遍学习时需要忽略其中的数学推导部分。
*
*/
public class Main {
public static void main(String[] args) {
int[] arr = new int[20];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
int[] scores = new int[]{88,99,100};
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
for (int score:scores){
System.out.println(score);
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution167.java | data_struct_study/src/array_problem/Solution167.java | package array_problem;
import java.util.Arrays;
/**
* 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
* 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
*
* 说明:
* 返回的下标值(index1 和 index2)不是从零开始的。
* 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
* 示例:
*
* 输入: numbers = [2, 7, 11, 15], target = 9
* 输出: [1,2]
* 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
*
* 1、如果没有解?保证有解。
* 2、如果有多个解?返回任意解。
* 3、双层遍历 O(n^2)。(没有利用有序)
* 4、循环 + 二分查找 O(nlogn):在有序数组中寻找 target - nums[i]。
* 5、对撞指针:使用两个索引,两个索引在中间的位置靠近。
*
* O(n ^ 2)
* O(1)
*/
public class Solution167 {
// 1、双层遍历每一种可能的组合:时间复杂度 O(n^2)。(没有利用有序)
public int[] twoSum(int[] arr, int target) {
// 1、有效性判断
int n = arr.length;
if (n < 2) {
throw new IllegalArgumentException("length of arr is illegal");
}
// 2、双层for循环查找每一种可能的组合
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] + arr[j] == target) {
int[] res = {i + 1, j + 1};
return res;
}
}
}
throw new IllegalArgumentException("no target!");
}
public static void main(String[] args) {
int[] arr = {2, 7, 11, 15};
System.out.println(Arrays.toString(new Solution167().twoSum(arr, 9)));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution674.java | data_struct_study/src/array_problem/Solution674.java | package array_problem;
public class Solution674 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution26.java | data_struct_study/src/array_problem/Solution26.java | package array_problem;
public class Solution26 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution33.java | data_struct_study/src/array_problem/Solution33.java | package array_problem;
/**
* 搜索旋转排序数组:先二分查找旋转点(迭代或者递推),
* 再二分查找目标(递推)。二分查找可以用递归/循环,
* 是很常见的写法。需注意分段和索引范围问题
* (没有必要为了排除某个别索引把分段弄得特别严谨)。
*/
public class Solution33 {
public int search(int[] nums, int target) {
int len = nums.length;
if (len==0) return -1;
if (len==1) return nums[0]==target? 0:-1;
int r = findRotation(nums,0,len-1);
if (r==-1) return findTarget(nums,0,len-1, target);
if (nums[0]>target) return findTarget(nums,r,len-1,target);
else if (nums[0]<target) return findTarget(nums,0,r-1,target);
else return 0;
}
private int findRotation(int[] nums, int a, int b)
{
if (b == a) return -1;
// iteration is also okay here
int m = (a+b)/2;
if (nums[m]>nums[m+1]) return m+1;
else return (Math.max(findRotation(nums,a,m),findRotation(nums,m+1,b)));
}
private int findTarget(int[] nums, int a, int b, int target)
{
if (a==b) return nums[a]==target? a:-1;
if (target>nums[b]||target<nums[a]) return -1;
int m = (a+b)/2;
if (nums[m]>target) return findTarget(nums,a,m,target);
else if (nums[m]<target) return findTarget(nums,m+1,b,target);
else return m;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution167_2.java | data_struct_study/src/array_problem/Solution167_2.java | package array_problem;
import java.util.Arrays;
/**
* 二分查找
* O(nlogn)
* O(1)
*/
public class Solution167_2 {
// 2、循环 + 二分查找:在有序数组中查找 target - arr[i], 时间复杂度O(nlogn)
public int[] twoSum(int[] arr, int target) {
// 1、异常边界处理
int n = arr.length;
if (n < 2) {
throw new IllegalArgumentException("len of arr is illegal!");
}
// 2、循环 + 二分查找:在有序数组中查找target-nums[i]
for (int i = 0; i < n; i++) {
int j = binarySearch(arr, i + 1, n - 1, target - arr[i]);
if (j != -1) {
int[] res = {i + 1, j + 1};
return res;
}
}
// 3、如果没有找到,则抛出异常
throw new IllegalArgumentException("no target!");
}
private int binarySearch(int[] arr, int l, int r, int target) {
// 1、左右边界异常处理
int n = arr.length;
if (l < 0 || l > n - 1) {
throw new IllegalArgumentException("l is illegal!");
}
if (r < 0 || r > n - 1) {
throw new IllegalArgumentException("r is illegal!");
}
// 2、二分搜索
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == target) {
return m;
} else if (arr[m] < target) {
l = m + 1;
} else {
r = m - 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {2, 7, 11, 15};
System.out.println(Arrays.toString(new Solution167().twoSum(arr, 9)));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution167_3.java | data_struct_study/src/array_problem/Solution167_3.java | package array_problem;
import java.util.Arrays;
/**
* 对撞指针
* O(n)
* O(1)
*/
public class Solution167_3 {
// 3、对撞指针:使用左右边界索引,使用这2个索引不断往中间靠拢,时间复杂度O(n), 空间复杂度O(1)
public int[] twoSum(int[] arr, int target) {
// 1、异常边界处理
int n = arr.length;
if (n < 2) {
throw new IllegalArgumentException("len of arr is illegal!");
}
// 2、对撞指针
int l = 0, r = n - 1;
while (l < r) {
// 1)、如果两者之和与target相等,则返回
if (arr[l] + arr[r] == target) {
int[] res = {l + 1, r + 1};
return res;
} else if (arr[l] + arr[r] < target) {
// 2)、如果两者之和小于target,则要增大左边界对应的值,即使l+1
l ++;
} else {
// 3)、否则要增大右边界对应的值,即使r-1
r --;
}
}
throw new IllegalArgumentException("no target!");
}
public static void main(String[] args) {
int[] arr = {2, 7, 11, 15};
System.out.println(Arrays.toString(new Solution167_3().twoSum(arr, 9)));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution56.java | data_struct_study/src/array_problem/Solution56.java | package array_problem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* 首先根据左端点排序,这样只需比较每一次合并后区间的右端点和一个区间的左端点即可。
*
* 输入: intervals = [[1,3],[2,6],[8,10],[15,18]]
* 输出: [[1,6],[8,10],[15,18]]
* 解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
*/
public class Solution56 {
public int[][] merge(int[][] intervals) {
// 1、异常边界处理
if (intervals == null || intervals.length == 0) {
return new int[0][];
}
// 2、初始化一个记录区间的列表
List<int[]> list = new ArrayList<>();
// 3、根据每一个区间的左边界排序
Arrays.sort(intervals, (o1, o2) -> o1[0]-o2[0]);
// 4、遍历每一个区间
int i = 0;
while (i < intervals.length) {
// 1)、拿到当前区间的左右边界
int l = intervals[i][0], r = intervals[i][1];
// 2)、当下一个区间存在 & 下一个区间的左边界小于当前区间的右边界,
// 则更新当前区间右边界为 当前区间右边界与下一个区间右边界 两者中的最大值
i++;
while (i < intervals.length && intervals[i][0] <= r){
r = Math.max(r, intervals[i][1]);
i++;
}
// 3)、添加合并后的区间到列表
list.add(new int[]{l, r});
}
return list.toArray(new int[0][]);
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution11.java | data_struct_study/src/array_problem/Solution11.java | package array_problem;
/**
* 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。
* 在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。
* 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
*
* 说明:你不能倾斜容器,且 n 的值至少为 2。
* 图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,
* 容器能够容纳水(表示为蓝色部分)的最大值为 49。
*
* 示例:
* 输入:[1,8,6,2,5,4,8,3,7]
* 输出:49
*/
public class Solution11 {
public int maxArea(int[] height) {
// 1、初始化记录窗口左右边界的位置 & 最大面积
int l = 0, r = height.length - 1;
int max = 0;
// 2、当左边界小于右边界时
while (l < r) {
// 1)、统计当前窗口的面积大小:左右边界中较低的高 * 窗口大小
int cur = Math.min(height[l], height[r]) * (r - l);
// 2)、维护窗口最大面积
max = Math.max(max, cur);
// 3)、如果当前窗口左边界的高度小于右边界的高度,则左边界往里移动1步,否则右边界往里移动一步
if (height[l] < height[r]) {
l++;
} else {
r--;
}
}
return max;
}
public static void main(String[] args) {
int[] arr = new int[]{1,8,6,2,5,4,8,3,7};
System.out.println(new Solution11().maxArea(arr));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution567.java | data_struct_study/src/array_problem/Solution567.java | package array_problem;
public class Solution567 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution75.java | data_struct_study/src/array_problem/Solution75.java | package array_problem;
//https://leetcode-cn.com/problems/sort-colors/:颜色分类
/**
* 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
*
* 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
*
* 注意:
* 不能使用代码库中的排序函数来解决这道题。
*
* 示例:
*
* 输入: [2,0,2,1,1,0]
* 输出: [0,0,1,1,2,2]
* 进阶:
*
* 一个直观的解决方案是使用计数排序的两趟扫描算法。
* 首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
* 你能想出一个仅使用常数空间的一趟扫描算法吗?
*
* 1、计数排序:分别统计0、1、2元素的个数。
* 2、三路快排。
*
* 计数排序思路,对整个数组遍历了两遍
* O(n)
* O(K),k为元素的取值范围
*/
public class Solution75 {
public void sortColors(int[] nums) {
// 使用一个数组统计每个值出现的频率
int[] count = {0, 0, 0};
for (int i = 0; i < nums.length; i++) {
assert nums[i] >= 0 && nums[i] <= 2;
count[nums[i]] ++;
}
// 拼装成 0、1、2 排序的新数组
int k = 0;
for (int i = 0; i < count[0]; i++) {
nums[k++] = 0;
}
for (int i = 0; i < count[1]; i++) {
nums[k++] = 1;
}
for (int i = 0; i < count[2]; i++) {
nums[k++] = 2;
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution344.java | data_struct_study/src/array_problem/Solution344.java | package array_problem;
/**
* 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
* 不要创建另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
* 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
*
* 示例 1:
* 输入:["h","e","l","l","o"]
* 输出:["o","l","l","e","h"]
*
* 示例 2:
* 输入:["H","a","n","n","a","h"]
* 输出:["h","a","n","n","a","H"]
*/
public class Solution344 {
// 1、递归解法会占用递归栈空间
public String reverseString(String s) {
// 1、初始化数组长度 & 当长度<=1说明不需要反转
int len = s.length();
if (len <=1 ) {
return s;
}
// 2、在递归的过程中不断反转当前字符串的左子字符串与右子字符串,注意右在前,左在后,就是为了实现反转的效果
String leftStr = s.substring(0, len / 2);
String rightStr = s.substring(len / 2, len);
return reverseString(rightStr) + reverseString(leftStr);
}
// 2、双指针解法,不断交换数组当前的首元素与尾元素,一个for循环搞定
// 时间复杂度:O(n),空间复杂度:O(1)
public void reverseString(char[] nums) {
// 1、初始化数组长度
int len = nums.length;
// 2、在for循环中不断交换当前的首元素与尾元素
for (int l = 0, r = len - 1; l < r; ++l, --r) {
char t = nums[l];
nums[l] = nums[r];
nums[r] = t;
}
}
public static void main(String[] args) {
// ["h","e","l","l","o"]
String s = "hello";
System.out.println(new Solution344().reverseString(s));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution125.java | data_struct_study/src/array_problem/Solution125.java | package array_problem;
//https://leetcode-cn.com/problems/valid-palindrome/:验证回文串
/**
* 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
*
* 说明:本题中,我们将空字符串定义为有效的回文串。
*
* 示例 1:
*
* 输入: "A man, a plan, a canal: Panama"
* 输出: true
* 示例 2:
*
* 输入: "race a car"
* 输出: false
*
* 1、空字符串如何看?
* 2、字符的定义。
* 3、大小写问题。
* 4、对撞指针。
*/
public class Solution125 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution42.java | data_struct_study/src/array_problem/Solution42.java | package array_problem;
/**
* 每一个柱子的高度方向可以接的雨水的数量 =
* min(从当前柱子向左看的最高柱子高度, 从当前柱子向右看的最高柱子高度) - 当前柱子高度
* 1)两个数组left、right分别保存:从左往右遍历时下标i最高柱子高度,和从右往左遍历时下标i最高柱子高度。
* 2)再遍历一遍每个位置,只有当height[i]的高度,比left[i]和right[i]都要小的时候才能接住雨水(否则总有一边会漏,接不到雨水)
* 3)将所有可以接到雨水的柱子的数量加起来
*/
public class Solution42 {
public int trap(int[] height) {
int length = height.length;
int[] left = new int[length];//保存从左往右遍历时,每一个下标位置当前的最高柱子高度
int[] right = new int[length];//保存从右往左遍历时,每一个下标位置当前的最高柱子高度
int leftMax = 0;
int rightMax = 0;
int sum = 0;
//计算left和right数组
for (int i = 0; i < length; i++) {
if (height[i] > leftMax) {
leftMax = height[i];
}
left[i] = leftMax;
if (height[length-1-i] > rightMax) {
rightMax = height[length-1-i];
}
right[length-1-i] = rightMax;
}
//遍历,只有当前柱子往左看、往右看的最高柱子都比当前柱子高,才能接住雨水
for (int j = 0; j < length; j++) {
if (height[j] < left[j] && height[j] < right[j]) {
sum = sum + Math.min(left[j], right[j]) - height[j];
}
}
return sum;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution80.java | data_struct_study/src/array_problem/Solution80.java | package array_problem;
//https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/:删除排序数组中的重复项 II
/**
* 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。
*
* 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
*
* 示例 1:
*
* 给定 nums = [1,1,1,2,2,3],
*
* 函数应返回新长度 length = 5, 并且原数组的前五个元素被修改为 1, 1, 2, 2, 3 。
*
* 你不需要考虑数组中超出新长度后面的元素。
* 示例 2:
*
* 给定 nums = [0,0,1,1,1,1,2,3,3],
*
* 函数应返回新长度 length = 7, 并且原数组的前五个元素被修改为 0, 0, 1, 1, 2, 3, 3 。
*
* 你不需要考虑数组中超出新长度后面的元素。
* 说明:
*
* 为什么返回数值是整数,但输出的答案是数组呢?
*
* 请注意,输入数组是以“引用”方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。
*
* 你可以想象内部操作如下:
*
* // nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
* int len = removeDuplicates(nums);
*
* // 在函数里修改输入数组对于调用者是可见的。
* // 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
* for (int i = 0; i < len; i++) {
* print(nums[i]);
* }
*
*/
public class Solution80 {
// public int removeDuplicates(int[] nums) {
//
// }
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution283_2.java | data_struct_study/src/array_problem/Solution283_2.java | package array_problem;
/**
* O(n)
* O(1)
*/
public class Solution283_2 {
public void moveZeroes(int[] nums) {
// [0,k)中的元素都用来保存原地的非零元素
int k = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[k++] = nums[i];
}
}
for (int i = k; i < nums.length; i++) {
nums[i] = 0;
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution438.java | data_struct_study/src/array_problem/Solution438.java | package array_problem;
import java.util.ArrayList;
import java.util.List;
/**
* 438:
* 1、字符集范围?英文小写字母。
* 2、返回的解的顺序?任意。
*
* 找到字符串中所有字母异位词:【滑动窗口】。
*/
public class Solution438 {
public List<Integer> findAnagrams(String s, String p) {
if(p==null||s==null||p.length()==0||s.length()==0
||p.length()>s.length())
return new ArrayList<Integer>();
int[] record=new int[26];
List<Integer> list=new ArrayList<>();
int sum=0;
for(int i=0; i<p.length(); i++){
char c=p.charAt(i);
record[c-'a']++; sum++;
}
for(int i=0; i<p.length(); i++){
char c=s.charAt(i);
record[c-'a']--;
if (record[c-'a']>=0) sum--;
}
if (sum==0) list.add(0);
for (int i=p.length(); i<s.length(); i++){
char c=s.charAt(i-p.length());
record[c-'a']++;
if (record[c-'a']>0) sum++;
c=s.charAt(i);
record[c-'a']--;
if (record[c-'a']>=0) sum--;
if (sum==0) list.add(i-p.length()+1);
}
return list;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution283_4.java | data_struct_study/src/array_problem/Solution283_4.java | package array_problem;
public class Solution283_4 {
public void moveZeroes(int[] nums) {
int k = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
if (i != k) {
swap(nums, k++, i);
} else {
k++;
}
}
}
}
private void swap(int[] nums, int k, int i) {
int temp = nums[k];
nums[k] = nums[i];
nums[i] = temp;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/BinarySearch2.java | data_struct_study/src/array_problem/BinarySearch2.java | package array_problem;
/**
* 对于有序数列,才能使用二分查找法(排序的作用)。
* 100 万的数据量只需零点几秒。
* 注意搜索开闭区间的设定,例如 [0, n - 1] 或 [0, n)。
* 1962 才意识到的 bug:mid = (l + r) / 2 可能会产生整形溢出,推荐使用减法:l + (r-l)/2。
*
* 如何写出正确的程序?
* 1、明确变量的含义。
* 2、循环不变量。
* 3、小数据量调试。
* 4、大数据量测试。
*/
public class BinarySearch2 {
public static int binarySearch(Comparable[] arr, int n, Comparable target) {
int l = 0, r = n;
while (l < r) {
int mid = l + (r - l) / 2;
if (target.compareTo(arr[mid]) == 0) {
return mid;
}
if (target.compareTo(arr[mid]) > 0) {
l = mid + 1;
} else {
r = mid;
}
}
return -1;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution128.java | data_struct_study/src/array_problem/Solution128.java | package array_problem;
import java.util.HashMap;
public class Solution128 {
public int longestConsecutive(int[] nums) {
// 1、创建 值:频率 哈希表
HashMap<Integer, Integer> countForNum = new HashMap<>();
for (int num:nums) {
countForNum.put(num, 1);
}
// 2、求出哈希表中每一个值对应的最大序列长度
for (int num:nums) {
forward(countForNum, num);
}
// 3、统计哈希表中存储的最大序列长度
return maxLen(countForNum);
}
private int forward(HashMap<Integer, Integer> countForNum, int num) {
if (!countForNum.containsKey(num)) {
return 0;
}
int cnt = countForNum.get(num);
if (cnt > 1) {
return cnt;
}
cnt = forward(countForNum, num + 1) + 1;
countForNum.put(num, cnt);
return cnt;
}
private int maxLen(HashMap<Integer, Integer> countForNum) {
int max = 0;
for (int num:countForNum.keySet()) {
max = Math.max(max, countForNum.get(num));
}
return max;
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution_1.java | data_struct_study/src/array_problem/Solution_1.java | package array_problem;
/**
* 数组中只出现一次的数字:一个整型数组里除了两个数字之外,
* 其他的数字都出现了两次,找出这两个数。
*/
public class Solution_1 {
// 1、哈希法:遍历数组,用map记录所有元素出现的次数,然后再遍历数组,找出只出现一次的数。
// 时间复杂度:O(n), 空间复杂度:O(n)
// 2、位运算:两个不相等的元素在位级表示上必定会有一位存在不同,将数组的所有元素异或得到的结果
// 为不存在重复的两个元素异或的结果。
// diff &= -diff 得出 diff 最低位的1,也就是不存在重复的两个元素在位级表示上最右侧不同
// 的那一位,利用这一位就可以将两个元素区分开来。
// 时间复杂度:O(n), 空间复杂度:O(1)
public void FindNumsAppearOnce(int[] nums, int num1[], int num2[]) {
// 1、利用 0 ^ x = x 和 x ^ y = 1、x ^ x = 0 的性质来遍历数组,
// 最后得到的值就是两个不同元素异或的值
int diff = 0;
for(int num:nums) {
diff ^= num;
}
// 2、利用 x & -x 得到x最低位的1
diff &= -diff;
// 3、遍历数组:利用 最低位1 & 当前元素是否为0来分离两个不同的元素
for(int num:nums) {
// 注意这里加括号
if ((diff & num) == 0) {
num1[0] ^= num;
} else {
num2[0] ^= num;
}
}
}
public static void main(String[] args) {
int[] nums = new int[]{1, 2, 3, 2, 1, 4};
int[] num1 = new int[]{0};
int[] num2 = new int[]{0};
new Solution_1().FindNumsAppearOnce(nums, num1, num2);
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution43.java | data_struct_study/src/array_problem/Solution43.java | package array_problem;
public class Solution43 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution547.java | data_struct_study/src/array_problem/Solution547.java | package array_problem;
public class Solution547 {
private int n;
public int findCircleNNum(int[][] M) {
n = M.length;
boolean[] visited = new boolean[n];
int max = 0;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(M, i, visited);
max++;
}
}
return max;
}
private void dfs(int[][] M, int i, boolean[] visited) {
visited[i] = true;
for (int k = 0; k < n; k++) {
if (M[i][k] == 1 && !visited[k]) {
dfs(M, k, visited);
}
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution283_3.java | data_struct_study/src/array_problem/Solution283_3.java | package array_problem;
/**
* O(n)
* O(1)
*/
public class Solution283_3 {
public void moveZeroes(int[] nums) {
int k = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
swap(nums, k++, i);
}
}
}
private void swap(int[] nums, int k, int i) {
int temp = nums[k];
nums[k] = nums[i];
nums[i] = temp;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution76.java | data_struct_study/src/array_problem/Solution76.java | package array_problem;
/**
* 1、字符集范围
* 2、若没有解?返回""
* 3、若有多个解?保证只有一个解
* 4、什么叫包含所有字符?S="a",T="aa"
*/
public class Solution76 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.