file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
RuleService.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-domain/src/main/java/com/gepardec/hogarama/domain/unitmanagement/service/RuleService.java | package com.gepardec.hogarama.domain.unitmanagement.service;
import com.gepardec.hogarama.domain.unitmanagement.context.UserContext;
import com.gepardec.hogarama.domain.unitmanagement.dao.RuleDAO;
import com.gepardec.hogarama.domain.unitmanagement.entity.LowWaterWateringRule;
import jakarta.enterprise.event.Event;
import jakarta.inject.Inject;
import jakarta.ws.rs.NotFoundException;
import java.util.List;
public class RuleService {
@Inject
private RuleDAO dao;
@Inject
private UserContext userContext;
@Inject
Event<LowWaterWateringRule> ruleChanged;
public void createRule(LowWaterWateringRule rule) {
rule.verifyIsOwned(userContext.getUser());
dao.save(rule);
}
public void deleteRule(Long ruleId) {
LowWaterWateringRule rule = this.dao.getById(ruleId)
.orElseThrow(() -> new NotFoundException(String.format("Rule with id [%d] not found", ruleId)));
ruleChanged.fire(rule);
dao.delete(rule);
}
public void updateRule(LowWaterWateringRule rule) {
rule.verifyIsOwned(userContext.getUser());
ruleChanged.fire(rule);
dao.update(rule);
}
public List<LowWaterWateringRule> getAllRulesForUser() {
return dao.getAllRulesForUser(userContext.getUser());
}
}
| 1,310 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
SensorTypeCache.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-domain/src/main/java/com/gepardec/hogarama/domain/unitmanagement/cache/SensorTypeCache.java | package com.gepardec.hogarama.domain.unitmanagement.cache;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gepardec.hogarama.domain.unitmanagement.entity.QSensorType;
import com.gepardec.hogarama.domain.unitmanagement.entity.SensorType;
import com.querydsl.jpa.impl.JPAQuery;
@ApplicationScoped
public class SensorTypeCache {
private static final Logger LOG = LoggerFactory.getLogger(SensorTypeCache.class);
@PersistenceContext
protected EntityManager entityManager;
private Map<Long, SensorType> sensorTypeMap = new HashMap<>();
public Optional<SensorType> byId(Long id) {
Optional<SensorType> type = getCachedType(id);
if (type.isPresent() ) {
return type;
}
return loadType(id);
}
private Optional<SensorType> getCachedType(Long id) {
return Optional.ofNullable(sensorTypeMap.get(id));
}
private synchronized Optional<SensorType> loadType(Long id) {
Optional<SensorType> type = getCachedType(id);
if (type.isPresent() ) {
return type;
}
LOG.warn("No sensor with id {} found - refresh cache.", id);
JPAQuery<SensorType> query = new JPAQuery<>(entityManager);
QSensorType sensorType = QSensorType.sensorType;
sensorTypeMap = query.select(sensorType).from(sensorType).fetch().stream()
.collect(Collectors.toMap(
SensorType::getId,
Function.identity()));
return getCachedType(id);
}
}
| 1,838 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
ActorCache.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-domain/src/main/java/com/gepardec/hogarama/domain/unitmanagement/cache/ActorCache.java | package com.gepardec.hogarama.domain.unitmanagement.cache;
import com.gepardec.hogarama.domain.unitmanagement.dao.ActorDAO;
import com.gepardec.hogarama.domain.unitmanagement.entity.Actor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class ActorCache {
private static final Logger LOG = LoggerFactory.getLogger(ActorCache.class);
@Inject
private ActorDAO dao;
private Map<String, Actor> cache = new HashMap<>();
public void invalidateCache(@Observes Actor actor) {
LOG.info("Invalidate actor cache.");
cache = new HashMap<>();
}
public Optional<Actor> getByDeviceId(String deviceId) {
Optional<Actor> actor = getCachedActor(deviceId);
if ( actor.isPresent()) {
return actor;
}
return loadActor(deviceId);
}
private synchronized Optional<Actor> loadActor(String deviceId) {
Optional<Actor> optionalActor = getCachedActor(deviceId);
if (optionalActor.isPresent()) {
return optionalActor;
}
LOG.info("Actor not found in cache, read from database with deviceId: " + deviceId);
optionalActor = dao.getByDeviceId(deviceId);
if (optionalActor.isPresent()) {
Actor actor = optionalActor.get();
LOG.info("Actor {} found. UnitName: {}", actor.getName(), actor.getUnit().getName());
cache.put(deviceId, optionalActor.get());
}
return optionalActor;
}
private Optional<Actor> getCachedActor(String deviceId) {
return Optional.ofNullable(cache.get(deviceId));
}
}
| 1,757 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
SensorCache.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-domain/src/main/java/com/gepardec/hogarama/domain/unitmanagement/cache/SensorCache.java | package com.gepardec.hogarama.domain.unitmanagement.cache;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gepardec.hogarama.domain.unitmanagement.dao.SensorDAO;
import com.gepardec.hogarama.domain.unitmanagement.entity.Sensor;
import com.gepardec.hogarama.domain.unitmanagement.entity.SensorType;
@ApplicationScoped
public class SensorCache {
private static final Logger LOG = LoggerFactory.getLogger(SensorCache.class);
@Inject
private SensorDAO dao;
private Map<String, Sensor> cache = new HashMap<>();
public void invalidateCache(@Observes Sensor sensor) {
LOG.info("Invalidate sensor cache.");
cache = new HashMap<>();
}
public Optional<Sensor> getByDeviceId(String deviceId) {
Optional<Sensor> sensor = getCachedSensor(deviceId);
if ( sensor.isPresent()) {
return sensor;
}
return loadSensor(deviceId);
}
private synchronized Optional<Sensor> loadSensor(String deviceId) {
Optional<Sensor> sensor = getCachedSensor(deviceId);
if (sensor.isPresent()) {
return sensor;
}
LOG.info("Sensor not found in cache, read from database with deviceId: " + deviceId);
sensor = dao.getByDeviceId(deviceId);
if (sensor.isPresent()) {
touchSensorTypeAndUnit(sensor);
cache.put(deviceId, sensor.get());
}
return sensor;
}
private Optional<Sensor> getCachedSensor(String deviceId) {
return Optional.ofNullable(cache.get(deviceId));
}
private void touchSensorTypeAndUnit(Optional<Sensor> sensor) {
SensorType type = sensor.get().getSensorType();
String unitName = sensor.get().getUnit().getName();
LOG.info("Sensor {} found. SensorType: {}, UnitName: {}",
sensor.get().getName(), type.getName(), unitName);
}
}
| 2,105 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
TechnicalException.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-domain/src/main/java/com/gepardec/hogarama/domain/exception/TechnicalException.java | package com.gepardec.hogarama.domain.exception;
public class TechnicalException extends RuntimeException {
private static final long serialVersionUID = 1L;
public TechnicalException() {
}
public TechnicalException(String message) {
super(message);
}
public TechnicalException(String message, Throwable cause) {
super(message, cause);
}
public TechnicalException(Throwable cause) {
super(cause);
}
public TechnicalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| 662 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
PostgresDAO.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-domain/src/main/java/com/gepardec/hogarama/annotations/PostgresDAO.java | package com.gepardec.hogarama.annotations;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import jakarta.inject.Qualifier;
@Qualifier
@Inherited
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface PostgresDAO {
}
| 593 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
MongoDAO.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-domain/src/main/java/com/gepardec/hogarama/annotations/MongoDAO.java | package com.gepardec.hogarama.annotations;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import jakarta.inject.Qualifier;
@Qualifier
@Inherited
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface MongoDAO {
}
| 590 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
ScalingTestServlet.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-frontend/src/main/java/at/gepardec/hogarama/scaling/ScalingTestServlet.java | package at.gepardec.hogarama.scaling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
@WebServlet("/ScalingTest")
public class ScalingTestServlet extends HttpServlet {
private static final long serialVersionUID = -4257270508512265869L;
private static final Logger logger = LoggerFactory.getLogger(ScalingTestServlet.class);
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) {
try{
PrintWriter out = response.getWriter();
out.println("Session ID: " + request.getSession().getId());
if (request.getSession().getAttribute("test") == null) {
out.println("New session. Current session is empty.");
request.getSession().setAttribute("test", Integer.valueOf(1));
logger.info("Here we start with a new session");
} else {
Integer value = (Integer) request.getSession().getAttribute("test");
out.println("Existing session: Value is " + value);
request.getSession().setAttribute("test",
Integer.valueOf(value.intValue() + 1));
}
out.println("Active Sessions: " + getActiveSession());
out.println("End");
} catch(IOException e){
logger.error("Error handling http request", e);
}
}
private int getActiveSession() {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
int activeSessions = 0;
try {
for (ObjectInstance objectInstance : mBeanServer.queryMBeans(
new ObjectName("jboss.as:deployment=*,subsystem=undertow"), null)) {
activeSessions += (Integer) mBeanServer.getAttribute(objectInstance.getObjectName(), "activeSessions");
}
} catch (MalformedObjectNameException | AttributeNotFoundException | InstanceNotFoundException
| MBeanException | ReflectionException e) {
throw new RuntimeException(e);
}
return activeSessions;
}
}
| 2,155 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
RuleDtoTranslatorTest.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/test/java/com/gepardec/hogarama/rest/unitmanagement/translator/RuleDtoTranslatorTest.java | package com.gepardec.hogarama.rest.unitmanagement.translator;
import com.gepardec.hogarama.domain.unitmanagement.dao.ActorDAO;
import com.gepardec.hogarama.domain.unitmanagement.dao.SensorDAO;
import com.gepardec.hogarama.domain.unitmanagement.dao.UnitDAO;
import com.gepardec.hogarama.domain.unitmanagement.entity.Actor;
import com.gepardec.hogarama.domain.unitmanagement.entity.LowWaterWateringRule;
import com.gepardec.hogarama.domain.unitmanagement.entity.Sensor;
import com.gepardec.hogarama.domain.unitmanagement.entity.Unit;
import com.gepardec.hogarama.rest.unitmanagement.dto.RuleDto;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ExtendWith(MockitoExtension.class)
public class RuleDtoTranslatorTest {
private static final long RULE_ID = 1338L;
private static final String NAME = "MY_RULE";
private static final String DESCRIPTION = "MY_RULE_DESCRIPTION";
private static final long SENSOR_ID = 2L;
private static final long ACTOR_ID = 3L;
private static final long UNIT_ID = 4L;
private static final double LOW_WATER = 0.3;
private static final int WATER_DURATION = 15;
@Mock
private SensorDAO sensorDAO;
@Mock
private ActorDAO actorDAO;
@Mock
private UnitDAO unitDAO;
@InjectMocks
private RuleDtoTranslator translator;
@Test
public void toDto_NullInput_ExceptionExpected() {
assertThrows(NullPointerException.class, () -> {
translator.toDto(null);
});
}
@Test
public void toDto() {
LowWaterWateringRule rule = new LowWaterWateringRule();
rule.setId(RULE_ID);
rule.setName(NAME);
rule.setDescription(DESCRIPTION);
rule.setSensor(newSensor());
rule.setActor(newActor());
rule.setUnit(newUnit());
rule.setLowWater(LOW_WATER);
rule.setWaterDuration(WATER_DURATION);
RuleDto result = translator.toDto(rule);
assertThat(result).isNotNull();
assertThat(result.getId()).isEqualTo(RULE_ID);
assertThat(result.getName()).isEqualTo(NAME);
assertThat(result.getDescription()).isEqualTo(DESCRIPTION);
assertThat(result.getUnitId()).isEqualTo(UNIT_ID);
assertThat(result.getSensorId()).isEqualTo(SENSOR_ID);
assertThat(result.getActorId()).isEqualTo(ACTOR_ID);
assertThat(result.getWaterDuration()).isEqualTo(WATER_DURATION);
assertThat(result.getLowWater()).isEqualTo(LOW_WATER);
}
@Test
public void fromDto_NullInput_ExceptionExpected() {
assertThrows(NullPointerException.class, () -> {
translator.fromDto(null);
});
}
@Test
public void fromDto() {
Sensor sensor = newSensor();
Actor actor = newActor();
Unit unit = newUnit();
Mockito.when(sensorDAO.getByIdNonOpt(SENSOR_ID)).thenReturn(sensor);
Mockito.when(actorDAO.getByIdNonOpt(ACTOR_ID)).thenReturn(actor);
Mockito.when(unitDAO.getById(UNIT_ID)).thenReturn(Optional.of(unit));
RuleDto dto = new RuleDto();
dto.setId(RULE_ID);
dto.setName(NAME);
dto.setDescription(DESCRIPTION);
dto.setSensorId(SENSOR_ID);
dto.setActorId(ACTOR_ID);
dto.setUnitId(UNIT_ID);
dto.setWaterDuration(WATER_DURATION);
dto.setLowWater(LOW_WATER);
LowWaterWateringRule result = translator.fromDto(dto);
assertThat(result).isNotNull();
assertThat(result.getId()).isEqualTo(RULE_ID);
assertThat(result.getName()).isEqualTo(NAME);
assertThat(result.getDescription()).isEqualTo(DESCRIPTION);
assertThat(result.getSensor()).isEqualTo(sensor);
assertThat(result.getActor()).isEqualTo(actor);
assertThat(result.getUnit()).isEqualTo(unit);
assertThat(result.getLowWater()).isEqualTo(LOW_WATER);
assertThat(result.getWaterDuration()).isEqualTo(WATER_DURATION);
}
private Sensor newSensor() {
Sensor sensor = new Sensor();
sensor.setId(SENSOR_ID);
return sensor;
}
private Actor newActor() {
Actor actor = new Actor();
actor.setId(ACTOR_ID);
return actor;
}
private Unit newUnit() {
Unit unit = new Unit();
unit.setId(UNIT_ID);
return unit;
}
}
| 4,650 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
UnitDtoTranslatorTest.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/test/java/com/gepardec/hogarama/rest/unitmanagement/translator/UnitDtoTranslatorTest.java | package com.gepardec.hogarama.rest.unitmanagement.translator;
import static org.assertj.core.api.Assertions.assertThat;
import com.gepardec.hogarama.domain.unitmanagement.entity.User;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import com.gepardec.hogarama.domain.unitmanagement.context.UserContext;
import com.gepardec.hogarama.domain.unitmanagement.entity.Unit;
import com.gepardec.hogarama.rest.unitmanagement.dto.UnitDto;
@ExtendWith(MockitoExtension.class)
public class UnitDtoTranslatorTest {
private static final String EXAMPLE_UNIT = "ExampleUnit";
private static final long USER_ID = 5L;
private static final long UNIT_ID = 2L;
@Mock
private UserContext userContext;
@InjectMocks
private UnitDtoTranslator translator;
@Test
public void fromDto() {
UnitDto dto = new UnitDto();
dto.setDefaultUnit(false);
dto.setDescription("A Example Unit");
dto.setId(UNIT_ID);
dto.setName(EXAMPLE_UNIT);
Mockito.when(userContext.getUser()).thenReturn(currentUser());
Unit result = translator.fromDto(dto);
assertThat(result).isNotNull();
assertThat(result.getId()).isEqualTo(UNIT_ID);
assertThat(result.getUser().getId()).isEqualTo(USER_ID);
assertThat(result.getName()).isEqualTo(EXAMPLE_UNIT);
}
private User currentUser() {
User user = new User();
user.setId(USER_ID);
return user;
}
}
| 1,600 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
SensorDtoTranslatorTest.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/test/java/com/gepardec/hogarama/rest/unitmanagement/translator/SensorDtoTranslatorTest.java | package com.gepardec.hogarama.rest.unitmanagement.translator;
import com.gepardec.hogarama.domain.unitmanagement.cache.SensorTypeCache;
import com.gepardec.hogarama.domain.unitmanagement.dao.UnitDAO;
import com.gepardec.hogarama.domain.unitmanagement.entity.Sensor;
import com.gepardec.hogarama.domain.unitmanagement.entity.SensorType;
import com.gepardec.hogarama.domain.unitmanagement.entity.Unit;
import com.gepardec.hogarama.rest.unitmanagement.dto.SensorDto;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ExtendWith(MockitoExtension.class)
public class SensorDtoTranslatorTest {
private static final long SENSOR_ID = 1337L;
private static final String DEVICE_ID = "DEVICE_ID";
private static final String NAME = "MY_SENSOR";
private static final long SENSOR_TYPE_ID = 1L;
private static final long UNIT_ID = 2L;
@Mock
private UnitDAO unitDAO;
@Mock
private SensorTypeCache sensorTypeCache;
@InjectMocks
private SensorDtoTranslator translator;
@Test
public void toDto_NullInput_ExceptionExpected() {
assertThrows(NullPointerException.class, () -> {
translator.toDto(null);
});
}
@Test
public void toDto() {
Sensor sensor = new Sensor();
sensor.setId(SENSOR_ID);
sensor.setDeviceId(DEVICE_ID);
sensor.setName(NAME);
sensor.setSensorType(newSensorType());
sensor.setUnit(newUnit());
SensorDto result = translator.toDto(sensor);
assertThat(result).isNotNull();
assertThat(result.getId()).isEqualTo(SENSOR_ID);
assertThat(result.getDeviceId()).isEqualTo(DEVICE_ID);
assertThat(result.getName()).isEqualTo(NAME);
assertThat(result.getSensorTypeId()).isEqualTo(SENSOR_TYPE_ID);
assertThat(result.getUnitId()).isEqualTo(UNIT_ID);
}
@Test
public void fromDto_NullInput_ExceptionExpected() {
assertThrows(NullPointerException.class, () -> {
translator.fromDto(null);
});
}
@Test
public void fromDto() {
Unit unit = newUnit();
Mockito.when(unitDAO.getById(UNIT_ID)).thenReturn(Optional.of(unit));
SensorType sensorType = newSensorType();
Mockito.when(sensorTypeCache.byId(SENSOR_TYPE_ID)).thenReturn(Optional.of(sensorType));
SensorDto dto = new SensorDto();
dto.setId(SENSOR_ID);
dto.setDeviceId(DEVICE_ID);
dto.setName(NAME);
dto.setSensorTypeId(SENSOR_TYPE_ID);
dto.setUnitId(UNIT_ID);
Sensor result = translator.fromDto(dto);
assertThat(result).isNotNull();
assertThat(result.getId()).isEqualTo(SENSOR_ID);
assertThat(result.getDeviceId()).isEqualTo(DEVICE_ID);
assertThat(result.getName()).isEqualTo(NAME);
assertThat(result.getSensorType()).isEqualTo(sensorType);
assertThat(result.getUnit()).isEqualTo(unit);
}
private SensorType newSensorType() {
SensorType sensorType = new SensorType();
sensorType.setId(SENSOR_TYPE_ID);
return sensorType;
}
private Unit newUnit() {
Unit unit = new Unit();
unit.setId(UNIT_ID);
return unit;
}
}
| 3,526 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
ActorDtoTranslatorTest.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/test/java/com/gepardec/hogarama/rest/unitmanagement/translator/ActorDtoTranslatorTest.java | package com.gepardec.hogarama.rest.unitmanagement.translator;
import com.gepardec.hogarama.domain.unitmanagement.dao.UnitDAO;
import com.gepardec.hogarama.domain.unitmanagement.entity.Actor;
import com.gepardec.hogarama.domain.unitmanagement.entity.Unit;
import com.gepardec.hogarama.rest.unitmanagement.dto.ActorDto;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ExtendWith(MockitoExtension.class)
public class ActorDtoTranslatorTest {
private static final long ACTOR_ID = 1337L;
private static final String DEVICE_ID = "DEVICE_ID";
private static final String NAME = "MY_ACTOR";
private static final long UNIT_ID = 2L;
public static final String QNAME = "QNAME";
@Mock
private UnitDAO unitDAO;
@InjectMocks
private ActorDtoTranslator translator;
@Test
public void toDto_NullInput_ExceptionExpected() {
assertThrows(NullPointerException.class, () -> {
translator.toDto(null);
});
}
@Test
public void toDto() {
Actor actor = new Actor();
actor.setId(ACTOR_ID);
actor.setDeviceId(DEVICE_ID);
actor.setName(NAME);
actor.setUnit(newUnit());
actor.setQueueName(QNAME);
ActorDto result = translator.toDto(actor);
assertThat(result).isNotNull();
assertThat(result.getId()).isEqualTo(ACTOR_ID);
assertThat(result.getDeviceId()).isEqualTo(DEVICE_ID);
assertThat(result.getName()).isEqualTo(NAME);
assertThat(result.getUnitId()).isEqualTo(UNIT_ID);
assertThat(result.getQueueName()).isEqualTo(QNAME);
}
@Test
public void fromDto_NullInput_ExceptionExpected() {
assertThrows(NullPointerException.class, () -> {
translator.fromDto(null);
});
}
@Test
public void fromDto() {
Unit unit = newUnit();
Mockito.when(unitDAO.getById(UNIT_ID)).thenReturn(Optional.of(unit));
ActorDto dto = new ActorDto();
dto.setId(ACTOR_ID);
dto.setDeviceId(DEVICE_ID);
dto.setName(NAME);
dto.setUnitId(UNIT_ID);
dto.setQueueName(QNAME);
Actor result = translator.fromDto(dto);
assertThat(result).isNotNull();
assertThat(result.getId()).isEqualTo(ACTOR_ID);
assertThat(result.getDeviceId()).isEqualTo(DEVICE_ID);
assertThat(result.getName()).isEqualTo(NAME);
assertThat(result.getUnit()).isEqualTo(unit);
assertThat(result.getQueueName()).isEqualTo(QNAME);
}
private Unit newUnit() {
Unit unit = new Unit();
unit.setId(UNIT_ID);
return unit;
}
}
| 2,949 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
TestCaseDateUtil.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/test/java/com/gepardec/hogarama/rest/util/TestCaseDateUtil.java | package com.gepardec.hogarama.rest.util;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Calendar;
import java.util.Date;
import jakarta.ws.rs.WebApplicationException;
import org.junit.jupiter.api.Test;
public class TestCaseDateUtil {
@Test
public void testDateUtilNullInput() {
String input = null;
Date output = DateUtil.getDateTimeFromString(input);
assertTrue(output == null);
}
@Test
public void testDateUtilParseOK() {
String input = "2018-02-07T08:46:56.000Z";
Date date = DateUtil.getDateTimeFromString(input);
assertTrue(date != null);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
assertEquals(2018, cal.get(Calendar.YEAR));
assertEquals(1, cal.get(Calendar.MONTH));
assertEquals(7, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(8, cal.get(Calendar.HOUR));
assertEquals(46, cal.get(Calendar.MINUTE));
assertEquals(56, cal.get(Calendar.SECOND));
}
@Test
public void testDateUtilParseNOK() {
String input = "bad input";
try {
DateUtil.getDateTimeFromString(input);
assertFalse(false, "WebApplicationException was not thrown.");
} catch (WebApplicationException e) {
assertTrue(true);
}
}
@Test
public void testDateUtilTimeOK() {
Date date = DateUtil.getTime(11, 11, 11);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
assertEquals(11, cal.get(Calendar.HOUR));
assertEquals(11, cal.get(Calendar.MINUTE));
assertEquals(11, cal.get(Calendar.SECOND));
}
@Test
public void testDateUtilTimeNOKHour() {
try {
DateUtil.getTime(99, 0, 0);
assertTrue(false, "IllegalArgumentException was not thrown.");
} catch (IllegalArgumentException e) {
assertTrue(true);
}
}
@Test
public void testDateUtilTimeNOKMin() {
try {
DateUtil.getTime(0, 99, 0);
assertTrue(false, "IllegalArgumentException was not thrown.");
} catch (IllegalArgumentException e) {
assertTrue(true);
}
}
@Test
public void testDateUtilTimeNOKSec() {
try {
DateUtil.getTime(0, 0, 99);
assertTrue(false, "IllegalArgumentException was not thrown.");
} catch (IllegalArgumentException e) {
assertTrue(true);
}
}
}
| 2,228 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
HogaramaExceptionMapper.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/HogaramaExceptionMapper.java | package com.gepardec.hogarama.rest;
import com.gepardec.hogarama.rest.unitmanagement.BaseResponse;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
/**
* Map occurring exceptions to a standard response
*/
@Provider
public class HogaramaExceptionMapper implements ExceptionMapper<Exception> {
private static final Logger LOG = LoggerFactory.getLogger(HogaramaExceptionMapper.class);
@Override
public Response toResponse(Exception exception) {
String message = exception.getMessage();
LOG.error("Exception occured: {}", message, exception);
BaseResponse<Object> response = new BaseResponse<>(HttpStatus.SC_INTERNAL_SERVER_ERROR);
response.setMessage(message);
return response.createRestResponse();
}
}
| 922 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
DefaultOptionsMethodExceptionMapper.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/DefaultOptionsMethodExceptionMapper.java | package com.gepardec.hogarama.rest;
import com.google.common.net.HttpHeaders;
import org.jboss.resteasy.spi.DefaultOptionsMethodException;
import jakarta.ws.rs.HttpMethod;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
/**
* Exception mapper for returning a standardized response for all OPTIONS requests
*/
@Provider
public class DefaultOptionsMethodExceptionMapper implements ExceptionMapper<DefaultOptionsMethodException> {
@Override
public Response toResponse(DefaultOptionsMethodException exception) {
return Response.ok()
.header(HttpHeaders.ALLOW, HttpMethod.GET)
.header(HttpHeaders.ALLOW, HttpMethod.POST)
.header(HttpHeaders.ALLOW, HttpMethod.PUT)
.header(HttpHeaders.ALLOW, HttpMethod.DELETE)
.header(HttpHeaders.ALLOW, HttpMethod.OPTIONS)
.header(HttpHeaders.ALLOW, HttpMethod.HEAD)
.build();
}
}
| 1,013 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
PrometheusHandler.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/PrometheusHandler.java | package com.gepardec.hogarama.rest;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Response;
import org.jboss.resteasy.core.providerfactory.ResteasyProviderFactoryImpl;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gepardec.hogarama.domain.metrics.Metrics;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Summary;
import io.prometheus.client.exporter.common.TextFormat;
import io.prometheus.client.hotspot.DefaultExports;
import jakarta.annotation.PostConstruct;
@Path("/metrics")
//@GZIP
@ApplicationScoped
public class PrometheusHandler {
private static final Logger logger = LoggerFactory.getLogger(PrometheusHandler.class);
private CollectorRegistry prometheusRegistry;
@PostConstruct
public void init(){
prometheusRegistry = CollectorRegistry.defaultRegistry;
DefaultExports.initialize();
}
@GET
@Produces(TextFormat.CONTENT_TYPE_004)
public Response getMetrics() throws IOException{
Summary.Timer requestTimer = Metrics.requestLatency.labels("hogarama_monitoring", "get_metrics").startTimer();
Metrics.requestsTotal.labels("hogarama_monitoring", "get_metrics").inc();
ResteasyProviderFactory resteasyProviderFactory = ResteasyProviderFactoryImpl.getInstance();
HttpServletRequest request = resteasyProviderFactory.getContextData(HttpServletRequest.class);
StringWriter writer = new StringWriter();
TextFormat.write004(writer, prometheusRegistry.filteredMetricFamilySamples(parse(request)));
logger.info("GET Request {}", request);
writer.flush();
requestTimer.observeDuration();
return Response.ok(writer.toString()).build();
}
private Set<String> parse(HttpServletRequest req) {
String[] includedParam = req.getParameterValues("name[]");
if (includedParam == null) {
return Collections.emptySet();
} else {
return new HashSet<>(Arrays.asList(includedParam));
}
}
}
| 2,420 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
ClientConfigResource.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/ClientConfigResource.java | package com.gepardec.hogarama.rest;
import com.gepardec.hogarama.rest.unitmanagement.BaseResponse;
import com.gepardec.hogarama.rest.unitmanagement.dto.ClientConfig;
import org.apache.http.HttpStatus;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("clientconfig")
public class ClientConfigResource {
@GET
@Path("")
@Produces(MediaType.APPLICATION_JSON)
public Response getAuthServerUrl() {
ClientConfig clientConfig = new ClientConfig();
clientConfig.setAuthServerUrl(System.getenv("KEYCLOAK_AUTH_SERVER_URL"));
clientConfig.setRealm(System.getenv("KEYCLOAK_REALM"));
clientConfig.setClientIdFrontend(System.getenv("KEYCLOAK_CLIENT_ID_FRONTEND"));
return new BaseResponse<>(clientConfig, HttpStatus.SC_OK).createRestResponse();
}
}
| 867 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
ActorApiImpl.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/ActorApiImpl.java | package com.gepardec.hogarama.rest;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.SecurityContext;
import com.gepardec.hogarama.domain.watering.ActorControlService;
public class ActorApiImpl implements ActorApi {
@Inject
ActorControlService pumpService;
@Override
public Response sendActorMessage(String location, String actorName, Integer duration,
SecurityContext securityContext) {
pumpService.sendActorMessage(location, actorName, duration);
return Response.ok().build();
}
}
| 543 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
CorsFilter.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/CorsFilter.java | package com.gepardec.hogarama.rest;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import jakarta.ws.rs.ext.Provider;
/**
* CORS-Filter for local development
*/
@Provider
public class CorsFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) {
responseContext.getHeaders().add(
"Access-Control-Allow-Origin", "*");
responseContext.getHeaders().add(
"Access-Control-Allow-Credentials", "true");
responseContext.getHeaders().add(
"Access-Control-Allow-Headers",
"origin, content-type, accept, authorization");
responseContext.getHeaders().add(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD");
}
}
| 1,018 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
SensorApiImpl.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/SensorApiImpl.java | package com.gepardec.hogarama.rest;
import com.gepardec.hogarama.domain.sensor.SensorDataDAO;
import com.gepardec.hogarama.domain.sensor.SensorNamesCache;
import com.gepardec.hogarama.domain.watering.WateringDAO;
import com.gepardec.hogarama.domain.watering.WateringData;
import com.gepardec.hogarama.rest.mapper.SensorMapper;
import com.gepardec.hogarama.rest.util.DateUtil;
import jakarta.enterprise.context.SessionScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.SecurityContext;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Path("sensor")
@SessionScoped
public class SensorApiImpl implements SensorApi, Serializable {
private static final long serialVersionUID = 1L;
@Inject
private SensorDataDAO habaramaDAO;
@Inject
private WateringDAO wateringDAO;
@Inject
private SensorNamesCache sensorNamesCache;
@Override
public Response getAllSensors(SecurityContext securityContext) {
return Response.ok(sensorNamesCache.getSensorNames()).build();
}
@Override
public Response getAllDataMaxNumber(Boolean onlyDataFromToday, Integer maxNumber, String sensor, String from, String to,
SecurityContext securityContext) {
/*
* TODO: From and To as Date. See in swagger conf. @DateTimeParam refactor Date
* format swagger: 2018-02-19T13:46:01.149Z yyyy-MM-ddTHH:mm:ss.SSSZ
*/
Date fromDate = DateUtil.getDateTimeFromString(from);
Date toDate = DateUtil.getDateTimeFromString(to);
if (onlyDataFromToday) {
fromDate = getTodayStartTime();
toDate = getTodayEndTime();
}
List<SensorData> sensorData = SensorMapper.INSTANCE.mapSensors(habaramaDAO.getAllData(maxNumber, sensor, fromDate, toDate));
return Response.ok(sensorData).build();
}
@Override
public Response getAllWateringDataMaxNumber(Boolean onlyDataFromToday, Integer maxNumber, String sensor, String from, String to, SecurityContext securityContext) {
Date fromDate = DateUtil.getDateTimeFromString(from);
Date toDate = DateUtil.getDateTimeFromString(to);
if (onlyDataFromToday) {
fromDate = getTodayStartTime();
toDate = getTodayEndTime();
}
List<WateringData> wateringData = wateringDAO.getWateringData(maxNumber, sensor, fromDate, toDate);
return Response.ok(wateringData).build();
}
@Override
public Response getLocationBySensorName(String sensorName, SecurityContext securityContext) {
return Response.ok(habaramaDAO.getLocationBySensorName(sensorName)).build();
}
private Date getTodayStartTime() {
return DateUtil.getTime(0, 0, 0);
}
private Date getTodayEndTime() {
return DateUtil.getTime(23, 59, 59);
}
}
| 2,668 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
TeamResource.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/TeamResource.java | package com.gepardec.hogarama.rest;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import org.apache.commons.io.IOUtils;
@Path("team")
public class TeamResource {
private static final String TEAM_URL = "http://www.gepardec.com/team/";
@GET
@Produces("text/html")
public String getTeamMembers() throws IOException {
URL url = new URL(TEAM_URL);
URLConnection connection = url.openConnection();
try(InputStream is = connection.getInputStream()){
return IOUtils.toString(is, StandardCharsets.UTF_8.name());
}
}
}
| 719 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
OpenshiftEnvResource.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/OpenshiftEnvResource.java | package com.gepardec.hogarama.rest;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
@Path("openshift")
public class OpenshiftEnvResource {
@GET
@Path("stage")
@Produces("text/html")
public String getStage() {
return getReturnValue(System.getenv("STAGE"));
}
@GET
@Path("tinyurl")
@Produces("text/html")
public String getTinyUrl() {
return getReturnValue(System.getenv("TINYURL"));
}
@GET
@Path("hostname")
@Produces("text/html")
public String getHostname() {
String ret = System.getenv("HOSTNAME");
if (ret == null) {
return "Not found";
}
if (ret.split("-").length != 3) {
return ret;
} else {
return "" + ret.split("-")[2].hashCode();
}
}
private String getReturnValue(String ret) {
return ret != null ? ret : "Not found";
}
}
| 818 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
SensorMapper.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/mapper/SensorMapper.java | package com.gepardec.hogarama.rest.mapper;
import java.util.List;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import com.gepardec.hogarama.rest.SensorData;
@Mapper
public interface SensorMapper {
SensorMapper INSTANCE = Mappers.getMapper(SensorMapper.class);
SensorData mapSensor(com.gepardec.hogarama.domain.sensor.SensorData sensor);
List<SensorData> mapSensors(List<com.gepardec.hogarama.domain.sensor.SensorData> sensors);
}
| 462 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
UserApiImpl.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/UserApiImpl.java | package com.gepardec.hogarama.rest.unitmanagement;
import com.gepardec.hogarama.domain.unitmanagement.entity.UserProfile;
import com.gepardec.hogarama.domain.unitmanagement.service.UserProfileService;
import com.gepardec.hogarama.rest.unitmanagement.dto.UserDto;
import com.gepardec.hogarama.rest.unitmanagement.interceptor.DetermineUser;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.inject.Inject;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
@Path("/unitmanagement/user")
@DetermineUser
public class UserApiImpl implements UserApi {
private static final Logger LOG = LoggerFactory.getLogger(UserApiImpl.class);
@Inject
private UserProfileService userProfileService;
@Override
public Response getUser() {
LOG.info("Get user data. Currently dummy data.");
// provide temporary dummy response for frontend
UserDto userDto = new UserDto();
UserProfile userProfile = userProfileService.getUserProfile();
userDto.setName(userProfile.getName());
userDto.setGivenName(userProfile.getGivenName());
userDto.setFamilyName(userProfile.getFamilyName());
userDto.setEmail(userProfile.getEmail());
return new BaseResponse<>(userDto, HttpStatus.SC_OK).createRestResponse();
}
}
| 1,346 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
RuleApiImpl.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/RuleApiImpl.java | package com.gepardec.hogarama.rest.unitmanagement;
import com.gepardec.hogarama.domain.unitmanagement.entity.LowWaterWateringRule;
import com.gepardec.hogarama.domain.unitmanagement.service.RuleService;
import com.gepardec.hogarama.rest.unitmanagement.dto.RuleDto;
import com.gepardec.hogarama.rest.unitmanagement.interceptor.DetermineUser;
import com.gepardec.hogarama.rest.unitmanagement.translator.RuleDtoTranslator;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.SecurityContext;
import java.util.List;
@SuppressWarnings("unused")
@Path("/unitmanagement/rule")
@DetermineUser
public class RuleApiImpl implements RuleApi {
private static final Logger LOG = LoggerFactory.getLogger(RuleApiImpl.class);
@Inject
private RuleService service;
@Inject
private RuleDtoTranslator translator;
@Override
public Response getForUser() {
LOG.info("Get rules for current user.");
List<RuleDto> dtoList = translator.toDtoList(service.getAllRulesForUser());
return new BaseResponse<>(dtoList, HttpStatus.SC_OK).createRestResponse();
}
@Override
@Transactional
public Response create(RuleDto ruleDto) {
LOG.info("Create rule.");
LowWaterWateringRule rule = translator.fromDto(ruleDto);
service.createRule(rule);
return new BaseResponse<>(ruleDto, HttpStatus.SC_CREATED).createRestResponse();
}
@Override
@Transactional
public Response update(String id, RuleDto ruleDto) {
LOG.info("Updating rule with id {}.", id);
LowWaterWateringRule rule = translator.fromDto(ruleDto);
if (id == null) {
return new BaseResponse<>("Required parameter ID is not set!", HttpStatus.SC_BAD_REQUEST).createRestResponse();
} else if (!id.equals(ruleDto.getId().toString())) {
return new BaseResponse<>(String.format("ID %s has to match with ID %s", id, ruleDto.getId().toString()), HttpStatus.SC_BAD_REQUEST).createRestResponse();
} else {
service.updateRule(rule);
}
return new BaseResponse<>(ruleDto, HttpStatus.SC_OK).createRestResponse();
}
@Override
@Transactional
public Response delete(String id) {
LOG.info("Deleting rule with id {}.", id);
if (id == null) {
return new BaseResponse<>(HttpStatus.SC_BAD_REQUEST).createRestResponse();
} else {
Long idNum;
try {
idNum = Long.parseLong(id);
} catch (NumberFormatException e) {
return new BaseResponse<>(HttpStatus.SC_BAD_REQUEST).createRestResponse();
}
service.deleteRule(idNum);
}
return new BaseResponse<>(HttpStatus.SC_OK).createRestResponse();
}
}
| 2,966 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
ActorApiImpl.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/ActorApiImpl.java | package com.gepardec.hogarama.rest.unitmanagement;
import com.gepardec.hogarama.domain.unitmanagement.entity.Actor;
import com.gepardec.hogarama.domain.unitmanagement.service.ActorService;
import com.gepardec.hogarama.rest.unitmanagement.dto.ActorDto;
import com.gepardec.hogarama.rest.unitmanagement.interceptor.DetermineUser;
import com.gepardec.hogarama.rest.unitmanagement.translator.ActorDtoTranslator;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.SecurityContext;
import java.util.List;
@SuppressWarnings("unused")
@Path("/unitmanagement/actor")
@DetermineUser
public class ActorApiImpl implements ActorApi {
private static final Logger LOG = LoggerFactory.getLogger(ActorApiImpl.class);
@Inject
private ActorService service;
@Inject
private ActorDtoTranslator translator;
@Override
public Response getForUser() {
LOG.info("Get actors for current user.");
List<ActorDto> dtoList = translator.toDtoList(service.getAllActorsForUser());
return new BaseResponse<>(dtoList, HttpStatus.SC_OK).createRestResponse();
}
@Override
@Transactional
public Response create(ActorDto actorDto) {
LOG.info("Create actor.");
Actor actor = translator.fromDto(actorDto);
service.createActor(actor);
return new BaseResponse<>(actorDto, HttpStatus.SC_CREATED).createRestResponse();
}
@Override
@Transactional
public Response update(String id, ActorDto actorDto) {
LOG.info("Updating actor with id {}.", id);
Actor actor = translator.fromDto(actorDto);
if (id == null) {
return new BaseResponse<>("Required parameter ID is not set!", HttpStatus.SC_BAD_REQUEST).createRestResponse();
} else if (!id.equals(actorDto.getId().toString())) {
return new BaseResponse<>(String.format("ID %s has to match with ID %s", id, actorDto.getId().toString()), HttpStatus.SC_BAD_REQUEST).createRestResponse();
} else {
service.updateActor(actor);
}
return new BaseResponse<>(actorDto, HttpStatus.SC_OK).createRestResponse();
}
@Override
@Transactional
public Response delete(String id) {
LOG.info("Deleting actor with id {}.", id);
if (id == null) {
return new BaseResponse<>(HttpStatus.SC_BAD_REQUEST).createRestResponse();
} else {
Long idNum;
try {
idNum = Long.parseLong(id);
} catch (NumberFormatException e) {
return new BaseResponse<>(HttpStatus.SC_BAD_REQUEST).createRestResponse();
}
service.deleteActor(idNum);
}
return new BaseResponse<>(HttpStatus.SC_OK).createRestResponse();
}
}
| 2,953 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
SensorApiImpl.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/SensorApiImpl.java | package com.gepardec.hogarama.rest.unitmanagement;
import com.gepardec.hogarama.domain.unitmanagement.entity.Sensor;
import com.gepardec.hogarama.domain.unitmanagement.service.SensorService;
import com.gepardec.hogarama.rest.unitmanagement.dto.SensorDto;
import com.gepardec.hogarama.rest.unitmanagement.interceptor.DetermineUser;
import com.gepardec.hogarama.rest.unitmanagement.translator.SensorDtoTranslator;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.SecurityContext;
import java.util.List;
@SuppressWarnings("unused")
@Path("/unitmanagement/sensor")
@DetermineUser
public class SensorApiImpl implements SensorApi {
private static final Logger LOG = LoggerFactory.getLogger(SensorApiImpl.class);
@Inject
private SensorService service;
@Inject
private SensorDtoTranslator translator;
@Override
public Response getForUser() {
LOG.info("Get sensors for current user.");
List<SensorDto> dtoList = translator.toDtoList(service.getAllSensorsForUser());
return new BaseResponse<>(dtoList, HttpStatus.SC_OK).createRestResponse();
}
@Override
@Transactional
public Response create(SensorDto sensorDto) {
LOG.info("Create sensor.");
Sensor sensor = translator.fromDto(sensorDto);
service.createSensor(sensor);
return new BaseResponse<>(sensorDto, HttpStatus.SC_CREATED).createRestResponse();
}
@Override
@Transactional
public Response update(String id, SensorDto sensorDto) {
LOG.info("Updating sensor with id {}.", id);
Sensor sensor = translator.fromDto(sensorDto);
if (id == null) {
return new BaseResponse<>("Required parameter ID is not set!", HttpStatus.SC_BAD_REQUEST).createRestResponse();
} else if (!id.equals(sensorDto.getId().toString())) {
return new BaseResponse<>(String.format("ID %s has to match with ID %s", id, sensorDto.getId().toString()), HttpStatus.SC_BAD_REQUEST).createRestResponse();
} else {
service.updateSensor(sensor);
}
return new BaseResponse<>(sensorDto, HttpStatus.SC_OK).createRestResponse();
}
@Override
@Transactional
public Response delete(String id) {
LOG.info("Deleting sensor with id {}.", id);
if (id == null) {
return new BaseResponse<>(HttpStatus.SC_BAD_REQUEST).createRestResponse();
} else {
Long idNum;
try {
idNum = Long.parseLong(id);
} catch (NumberFormatException e) {
return new BaseResponse<>(HttpStatus.SC_BAD_REQUEST).createRestResponse();
}
service.deleteSensor(idNum);
}
return new BaseResponse<>(HttpStatus.SC_OK).createRestResponse();
}
}
| 2,988 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
UnitApiImpl.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/UnitApiImpl.java | package com.gepardec.hogarama.rest.unitmanagement;
import com.gepardec.hogarama.domain.unitmanagement.entity.Unit;
import com.gepardec.hogarama.domain.unitmanagement.service.UnitService;
import com.gepardec.hogarama.rest.unitmanagement.dto.UnitDto;
import com.gepardec.hogarama.rest.unitmanagement.interceptor.DetermineUser;
import com.gepardec.hogarama.rest.unitmanagement.translator.UnitDtoTranslator;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
import java.util.List;
@Path("/unitmanagement/unit")
@DetermineUser
public class UnitApiImpl implements UnitApi {
private static final Logger LOG = LoggerFactory.getLogger(UnitApiImpl.class);
@Inject
private UnitService service;
@Inject
private UnitDtoTranslator translator;
@Override
public Response getForUser() {
LOG.info("Get unit for current user.");
List<UnitDto> dtoList = translator.toDtoList(service.getUnitsForUser());
return new BaseResponse<>(dtoList, HttpStatus.SC_OK).createRestResponse();
}
@Override
@Transactional
public Response create(UnitDto unitDto) {
LOG.info("Create new unit {}", unitDto);
Unit unit = translator.fromDto(unitDto);
service.createUnit(unit);
return new BaseResponse<>(unitDto, HttpStatus.SC_CREATED).createRestResponse();
}
@Override
@Transactional
public Response update(String id, UnitDto unitDto) {
LOG.info("Updating unit {}.", unitDto);
Unit unit = translator.fromDto(unitDto);
if (id == null) {
return new BaseResponse<>("Required parameter ID is not set!", HttpStatus.SC_BAD_REQUEST).createRestResponse();
} else if (!id.equals(unitDto.getId().toString())) {
return new BaseResponse<>(String.format("ID %s has to match with ID %s", id, unitDto.getId().toString()), HttpStatus.SC_BAD_REQUEST).createRestResponse();
} else {
service.updateUnit(unit);
}
return new BaseResponse<>(unitDto, HttpStatus.SC_OK).createRestResponse();
}
@Override
@Transactional
public Response delete(String id) {
LOG.info("Deleting unit with id {}.", id);
if (id == null) {
return new BaseResponse<>(HttpStatus.SC_BAD_REQUEST).createRestResponse();
} else {
Long idNum;
try {
idNum = Long.parseLong(id);
} catch (NumberFormatException e) {
return new BaseResponse<>(HttpStatus.SC_BAD_REQUEST).createRestResponse();
}
service.deleteUnit(idNum);
}
return new BaseResponse<>(HttpStatus.SC_OK).createRestResponse();
}
}
| 2,855 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
SensorDtoTranslator.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/translator/SensorDtoTranslator.java | package com.gepardec.hogarama.rest.unitmanagement.translator;
import com.gepardec.hogarama.domain.exception.TechnicalException;
import com.gepardec.hogarama.domain.unitmanagement.cache.SensorTypeCache;
import com.gepardec.hogarama.domain.unitmanagement.dao.UnitDAO;
import com.gepardec.hogarama.domain.unitmanagement.entity.Sensor;
import com.gepardec.hogarama.domain.unitmanagement.entity.SensorType;
import com.gepardec.hogarama.domain.unitmanagement.entity.Unit;
import com.gepardec.hogarama.domain.unitmanagement.context.UserContext;
import com.gepardec.hogarama.rest.unitmanagement.dto.SensorDto;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.enterprise.context.Dependent;
import jakarta.inject.Inject;
import java.util.Optional;
@Dependent
public class SensorDtoTranslator implements Translator<SensorDto, Sensor> {
private static final Logger LOG = LoggerFactory.getLogger(SensorDtoTranslator.class);
@Inject
private UnitDAO unitDAO;
@Inject
private UserContext userContext;
@Inject
private SensorTypeCache sensorTypeCache;
@Override
public SensorDto toDto(Sensor sensor) {
Preconditions.checkNotNull(sensor, "Sensor must not be null");
return SensorDto.of(sensor.getId(),
sensor.getName(),
sensor.getDeviceId(),
sensor.getUnit().getId(),
sensor.getSensorType().getId());
}
@Override
public Sensor fromDto(SensorDto dto) {
Preconditions.checkNotNull(dto, "SensorDto must not be null");
Sensor sensor = new Sensor();
sensor.setId(dto.getId());
Unit unit = getUnitByUnitIdOrDefaultUnit(dto.getUnitId());
sensor.setUnit(unit);
sensor.setDeviceId(dto.getDeviceId());
sensor.setName(dto.getName());
Optional<SensorType> optionalSensorType = sensorTypeCache.byId(dto.getSensorTypeId());
if (optionalSensorType.isPresent()) {
sensor.setSensorType(optionalSensorType.get());
} else {
throw new TechnicalException("No sensorType with id " + dto.getSensorTypeId() + " found.");
}
return sensor;
}
private Unit getUnitByUnitIdOrDefaultUnit(Long unitId) {
if (unitId == null) {
LOG.debug("No unitId supplied - Use default unit.");
return userContext.getUser().getDefaultUnit();
}
return unitDAO.getById(unitId).orElseGet(() -> {
LOG.warn("No unit with id {} found.", unitId);
return userContext.getUser().getDefaultUnit();
});
}
}
| 2,649 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
ActorDtoTranslator.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/translator/ActorDtoTranslator.java | package com.gepardec.hogarama.rest.unitmanagement.translator;
import com.gepardec.hogarama.domain.unitmanagement.context.UserContext;
import com.gepardec.hogarama.domain.unitmanagement.dao.UnitDAO;
import com.gepardec.hogarama.domain.unitmanagement.entity.Actor;
import com.gepardec.hogarama.domain.unitmanagement.entity.Unit;
import com.gepardec.hogarama.rest.unitmanagement.dto.ActorDto;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.enterprise.context.Dependent;
import jakarta.inject.Inject;
@Dependent
public class ActorDtoTranslator implements Translator<ActorDto, Actor> {
private static final Logger LOG = LoggerFactory.getLogger(ActorDtoTranslator.class);
@Inject
private UnitDAO unitDAO;
@Inject
private UserContext userContext;
@Override
public ActorDto toDto(Actor actor) {
Preconditions.checkNotNull(actor, "Actor must not be null");
return ActorDto.of(actor.getId(),
actor.getName(),
actor.getDeviceId(),
actor.getUnit().getId(),
actor.getQueueName());
}
@Override
public Actor fromDto(ActorDto dto) {
Preconditions.checkNotNull(dto, "ActorDto must not be null");
Actor actor = new Actor();
actor.setId(dto.getId());
Unit unit = getUnitByUnitIdOrDefaultUnit(dto.getUnitId());
actor.setUnit(unit);
actor.setDeviceId(dto.getDeviceId());
actor.setName(dto.getName());
actor.setQueueName(dto.getQueueName());
return actor;
}
private Unit getUnitByUnitIdOrDefaultUnit(Long unitId) {
if (unitId == null) {
LOG.debug("No unitId supplied - Use default unit.");
return userContext.getUser().getDefaultUnit();
}
return unitDAO.getById(unitId).orElseGet(() -> {
LOG.warn("No unit with id {} found.", unitId);
return userContext.getUser().getDefaultUnit();
});
}
}
| 2,034 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
Translator.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/translator/Translator.java | package com.gepardec.hogarama.rest.unitmanagement.translator;
import com.gepardec.hogarama.rest.unitmanagement.dto.BaseDto;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public interface Translator<DTO extends BaseDto, BO> {
DTO toDto(BO bo);
BO fromDto(DTO dto);
default List<DTO> toDtoList(Collection<BO> boCollection) {
return boCollection.stream().map(this::toDto).collect(Collectors.toList());
}
default List<BO> fromDtoList(Collection<DTO> dtoCollection) {
return dtoCollection.stream().map(this::fromDto).collect(Collectors.toList());
}
}
| 635 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
RuleDtoTranslator.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/translator/RuleDtoTranslator.java | package com.gepardec.hogarama.rest.unitmanagement.translator;
import com.gepardec.hogarama.domain.unitmanagement.context.UserContext;
import com.gepardec.hogarama.domain.unitmanagement.dao.ActorDAO;
import com.gepardec.hogarama.domain.unitmanagement.dao.SensorDAO;
import com.gepardec.hogarama.domain.unitmanagement.dao.UnitDAO;
import com.gepardec.hogarama.domain.unitmanagement.entity.LowWaterWateringRule;
import com.gepardec.hogarama.domain.unitmanagement.entity.Sensor;
import com.gepardec.hogarama.domain.unitmanagement.entity.Unit;
import com.gepardec.hogarama.rest.unitmanagement.dto.RuleDto;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.enterprise.context.Dependent;
import jakarta.inject.Inject;
@Dependent
public class RuleDtoTranslator implements Translator<RuleDto, LowWaterWateringRule> {
private static final Logger LOG = LoggerFactory.getLogger(RuleDtoTranslator.class);
@Inject
private SensorDAO sensorDAO;
@Inject
private ActorDAO actorDAO;
@Inject
private UnitDAO unitDAO;
@Inject
private UserContext userContext;
@Override
public RuleDto toDto(LowWaterWateringRule rule) {
Preconditions.checkNotNull(rule, "Rule must not be null");
return RuleDto.of(rule.getId(),
rule.getName(),
rule.getDescription(),
rule.getSensor().getId(),
rule.getActor().getId(),
rule.getUnit().getId(),
rule.getWaterDuration(),
rule.getLowWater()
);
}
@Override
public LowWaterWateringRule fromDto(RuleDto dto) {
Preconditions.checkNotNull(dto, "RuleDto must not be null");
LowWaterWateringRule rule = new LowWaterWateringRule();
rule.setId(dto.getId());
Sensor sensor = sensorDAO.getByIdNonOpt(dto.getSensorId());
rule.setSensor(sensor);
rule.setActor(actorDAO.getByIdNonOpt(dto.getActorId()));
rule.setUnit(unitDAO.getById(dto.getUnitId()).orElse(sensor.getUnit()));
rule.setName(dto.getName());
rule.setDescription(dto.getDescription());
rule.setLowWater(dto.getLowWater());
rule.setWaterDuration(dto.getWaterDuration());
return rule;
}
private Unit getUnitByUnitIdOrDefaultUnit(Long unitId) {
if (unitId == null) {
LOG.debug("No unitId supplied - Use default unit.");
return userContext.getUser().getDefaultUnit();
}
return unitDAO.getById(unitId).orElseGet(() -> {
LOG.warn("No unit with id {} found.", unitId);
return userContext.getUser().getDefaultUnit();
});
}
}
| 2,754 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
UnitDtoTranslator.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/translator/UnitDtoTranslator.java | package com.gepardec.hogarama.rest.unitmanagement.translator;
import com.gepardec.hogarama.domain.unitmanagement.context.UserContext;
import com.gepardec.hogarama.domain.unitmanagement.entity.Unit;
import com.gepardec.hogarama.rest.unitmanagement.dto.UnitDto;
import jakarta.enterprise.context.Dependent;
import jakarta.inject.Inject;
@Dependent
public class UnitDtoTranslator implements Translator<UnitDto, Unit> {
@Inject
private UserContext userContext;
@Override
public UnitDto toDto(Unit unit) {
return UnitDto.of(unit.getId(),
unit.getDescription(),
unit.isDefaultUnit(),
unit.getName(),
unit.getUser().getId());
}
@Override
public Unit fromDto(UnitDto dto) {
Unit unit = new Unit();
unit.setDescription(dto.getDescription());
unit.setName(dto.getName());
unit.setId(dto.getId());
unit.setUser(userContext.getUser()); // We always use the current User? Should UserId be in Dto?
unit.setDefaultUnit(dto.isDefaultUnit());
return unit;
}
}
| 1,110 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
DetermineUserInterceptor.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/interceptor/DetermineUserInterceptor.java | package com.gepardec.hogarama.rest.unitmanagement.interceptor;
import com.gepardec.hogarama.domain.unitmanagement.context.UserContext;
import com.gepardec.hogarama.domain.unitmanagement.entity.User;
import com.gepardec.hogarama.domain.unitmanagement.entity.UserProfile;
import com.gepardec.hogarama.domain.unitmanagement.service.UserService;
import com.gepardec.hogarama.security.UserProfileResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.inject.Inject;
import jakarta.interceptor.AroundInvoke;
import jakarta.interceptor.Interceptor;
import jakarta.interceptor.InvocationContext;
/**
* Intercepts all requests annotated with {@link DetermineUser} and extracts logged in user
* by request's bearer token. <br />
* The extracted user will be stored in the {@link UserContext}.
*/
@DetermineUser
@Interceptor
public class DetermineUserInterceptor {
private static final Logger LOG = LoggerFactory.getLogger(DetermineUserInterceptor.class);
@Inject
private UserService service;
@Inject
private UserContext userContext;
@Inject
private UserProfileResolver userProfileResolver;
@AroundInvoke
public Object aroundInvoke(InvocationContext ctx) throws Exception {
UserProfile userProfile = userProfileResolver.resolveUserProfile();
userContext.setUserProfile(userProfile);
User user = service.getRegisteredUser(userProfile.getEmail())
.orElseGet(() -> synchronizedRegisterUser(userProfile.getEmail()));
userContext.setUser(user);
return ctx.proceed();
}
private User synchronizedRegisterUser(String userKey) {
synchronized (UserService.class) {
LOG.debug("In synchronizedRegisterUser");
try {
return service.getOrRegister(userKey);
} finally {
LOG.debug("Out of synchronizedRegisterUser");
}
}
}
}
| 1,939 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
DetermineUser.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/interceptor/DetermineUser.java | package com.gepardec.hogarama.rest.unitmanagement.interceptor;
import jakarta.interceptor.InterceptorBinding;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* JAX-RS endpoints annotated with {@link DetermineUser} are intercepted by {@link DetermineUserInterceptor}.
* @see DetermineUserInterceptor
*/
@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface DetermineUser {
}
| 658 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
DateUtil.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-rs/src/main/java/com/gepardec/hogarama/rest/util/DateUtil.java | package com.gepardec.hogarama.rest.util;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import org.apache.commons.lang3.StringUtils;
public class DateUtil {
private static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(PATTERN);
private DateUtil() {
//static
}
public static Date getDateTimeFromString(String date) {
if (StringUtils.isEmpty(date)) {
return null;
}
try {
LocalDateTime localDateTime = LocalDateTime.parse(date, dateTimeFormatter);
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
} catch (DateTimeParseException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST)
.entity("Couldn't parse date string: " + e.getMessage()).build());
}
}
public static Date getTime(int hour, int min, int sec) {
validateInput(hour, min, sec);
Calendar c = new GregorianCalendar();
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, min);
c.set(Calendar.SECOND, sec);
return c.getTime();
}
private static void validateInput(int hour, int min, int sec) {
if(hour < 0 || hour > 24) {
throw new IllegalArgumentException("Hour must be between 0-24");
}
if(min < 0 || min > 59) {
throw new IllegalArgumentException("Min must be between 0-59");
}
if(sec < 0 || sec > 59) {
throw new IllegalArgumentException("Sec must be between 0-59");
}
}
}
| 1,836 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
DaoTest.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-services/src/test/java/com/gepardec/hogarama/service/DaoTest.java | package com.gepardec.hogarama.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import com.gepardec.hogarama.domain.watering.WateringConfigData;
import com.gepardec.hogarama.domain.watering.WateringRule;
import com.gepardec.hogarama.service.dao.MongoWateringRuleDAO;
public class DaoTest {
private MongoWateringRuleDAO dao = new MongoWateringRuleDAO();
@BeforeEach
public void setUp() throws Exception {
dao.setUpForTest();
}
@Test @Disabled // Das ist eher ein Integrationstest. Man benötigt Mongo-Zugriff
public void test() {
WateringConfigData wconf = new WateringConfigData("sensor", "actor", 0.2, 5);
dao.save(wconf);
String id = "sensor";
WateringRule c1 = dao.getBySensorName(id);
assertEquals("sensor", c1.getSensorName());
assertEquals("actor", c1.getActorName());
assertNull(dao.getBySensorName("sensor1"));
}
}
| 1,055 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
ActorControlServiceImplTest.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-services/src/test/java/com/gepardec/hogarama/service/ActorControlServiceImplTest.java | package com.gepardec.hogarama.service;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class ActorControlServiceImplTest {
@InjectMocks
private ActorControlServiceImpl actorService;
@Test
public void testCheckParametersOrFailOk() {
String sensorName = "Palmlilie";
String location = "Vienna";
actorService.checkParametersOrFail(location, sensorName, 5);
}
@Test
public void testCheckParametersOrFailNoParameters() {
String sensorName = null;
String location = null;
try {
actorService.checkParametersOrFail(location, sensorName, 5);
fail("Expected exception due to missing parameters.");
} catch(IllegalArgumentException e) {
Assertions.assertEquals("Supplied parameters 'null', 'null', '5' must not be empty or null", e.getMessage());
}
}
@Test
public void testCheckParametersOrFailEmptyParameters() {
String sensorName = "";
String location = "";
try {
actorService.checkParametersOrFail(location, sensorName, 5);
fail("Expected exception due to missing parameters.");
} catch(IllegalArgumentException e) {
Assertions.assertEquals("Supplied parameters '', '', '5' must not be empty or null", e.getMessage());
}
}
}
| 1,495 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
ActorControlServiceImpl.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-services/src/main/java/com/gepardec/hogarama/service/ActorControlServiceImpl.java | package com.gepardec.hogarama.service;
import java.util.Date;
import java.util.Optional;
import jakarta.inject.Inject;
import org.json.JSONObject;
import org.mongodb.morphia.Datastore;
import org.slf4j.Logger;
import com.gepardec.hogarama.domain.metrics.Metrics;
import com.gepardec.hogarama.domain.watering.ActorControlService;
import com.gepardec.hogarama.domain.watering.WateringData;
import com.gepardec.hogarama.mocks.cli.MqttClient;
public class ActorControlServiceImpl implements ActorControlService {
@Inject
private Datastore db;
@Inject
private Logger log;
@Override
public void sendActorMessage(String location, String actorName, Integer duration) {
log.info("sendActorMessage: location: {}, actorName: {}, duration: {}", location, actorName, duration);
checkParametersOrFail(location, actorName, duration);
MqttClient mqttClient = new MqttClient().defaultConnection().
withTopic(Optional.ofNullable(System.getenv("AMQ_TOPICS")).orElse("actor." + location + "." + actorName)).
build();
WateringData data = new WateringData(new Date(), actorName, location, duration);
db.save(data);
JSONObject json = new JSONObject(data);
String message = json.toString();
mqttClient.connectAndPublish(message);
}
protected void checkParametersOrFail(String location, String actorName, Integer duration) {
if (location == null || location.isEmpty() || actorName == null || actorName.isEmpty() || duration == null) {
Metrics.exceptionsThrown.labels("hogarama_services", "IllegalArgumentException", "ActorServiceImpl.checkParametersOrFail").inc();
throw new IllegalArgumentException(String.format("Supplied parameters '%s', '%s', '%s' must not be empty or null", location, actorName, duration));
}
}
}
| 1,880 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
MongoDbProducer.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-services/src/main/java/com/gepardec/hogarama/service/MongoDbProducer.java | package com.gepardec.hogarama.service;
import java.util.Arrays;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Produces;
import org.bson.Document;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
@ApplicationScoped
public class MongoDbProducer {
private static final String HOGAJAMA_DB = "hogajamadb";
private static final String USER = "hogajama";
// You need to define Environment Variable BEFORE Eclipse Start / Login Computer.
// You should define it in .bashrc: export MONGODB_PASSWORD/MONGODB_HOST=xxx
private static final char[] PASSWORD = System.getenv("MONGODB_PASSWORD").toCharArray();
private static final String HOST = System.getenv("MONGODB_HOST");
private static final int PORT = 27017;
private static final String COLLECTION = "habarama";
private static MongoClient client;
@Produces
public Datastore getDatastore() {
Morphia morphia = new Morphia();
morphia.mapPackage("com.gepardec.hogarama.domain");
Datastore datastore = morphia.createDatastore(getClient(), MongoDbProducer.HOGAJAMA_DB);
datastore.ensureIndexes();
return datastore;
}
@Produces
public MongoCollection<Document> getCollection() {
MongoDatabase dataBase = getClient().getDatabase(HOGAJAMA_DB);
return dataBase.getCollection(COLLECTION);
}
private static MongoClient getClient() {
if (client == null) {
MongoCredential credential = MongoCredential.createCredential(USER, HOGAJAMA_DB, PASSWORD);
client = new MongoClient(new ServerAddress(HOST, PORT), Arrays.asList(credential));
}
return client;
}
} | 1,845 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
SensorDataDAOImpl.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-services/src/main/java/com/gepardec/hogarama/service/dao/SensorDataDAOImpl.java | package com.gepardec.hogarama.service.dao;
import com.gepardec.hogarama.domain.metrics.Metrics;
import com.gepardec.hogarama.domain.sensor.SensorDataDAO;
import com.gepardec.hogarama.domain.sensor.SensorData;
import com.gepardec.hogarama.domain.sensor.SensorNormalizer;
import com.mongodb.client.DistinctIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoIterable;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.FindOptions;
import org.mongodb.morphia.query.Query;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.persistence.NoResultException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@ApplicationScoped
public class SensorDataDAOImpl implements SensorDataDAO {
@Inject
private Datastore datastore;
@Inject
private MongoCollection<Document> collection;
@Inject
SensorNormalizer sensorNormalizer;
@Override
public List<String> getAllSensors() {
DistinctIterable<String> sensors = collection.distinct("sensorName", String.class);
Metrics.requestsTotal.labels("hogajama_services", "getAllSensors").inc();
return createResultList(sensors);
}
private <T> List<T> createResultList(MongoIterable<T> sourceIterable) {
List<T> result = new ArrayList<>();
sourceIterable.into(result);
return result;
}
@Override
public List<SensorData> getAllData(Integer maxNumber, String sensorName, Date from, Date to) {
Metrics.requestsTotal.labels("hogajama_services", "getAllData").inc();
Query<SensorData> query = datastore.createQuery(SensorData.class).order("-_id");
limitQueryBySensor(sensorName, query);
limitQueryByDate(from, to, query);
FindOptions numberLimitOption = getFindOptionsWithMaxNumber(maxNumber);
return sensorNormalizer.normalize(query.asList(numberLimitOption));
}
private void limitQueryBySensor(String sensorName, Query<SensorData> query) {
if (StringUtils.isNotEmpty(sensorName)) {
query.field("sensorName").equal(sensorName);
}
}
private void limitQueryByDate(Date from, Date to, Query<SensorData> query) {
if (from != null) {
if (to == null) {
to = new Date();
}
query.field("time").greaterThanOrEq(from);
query.field("time").lessThanOrEq(to);
}
}
private FindOptions getFindOptionsWithMaxNumber(Integer maxNumber) {
FindOptions findOptions = new FindOptions();
if (maxNumber != null && maxNumber >= 0) {
findOptions.limit(maxNumber);
}
return findOptions;
}
@Override
/**
* TODO: rewrite query and logic with single result
*/
public String getLocationBySensorName(String sensorName) {
Metrics.requestsTotal.labels("hogajama_services", "getLocationBySensorName").inc();
Query<SensorData> query = datastore.createQuery(SensorData.class).order("-_id");
limitQueryBySensor(sensorName, query);
FindOptions numberLimitOption = getFindOptionsWithMaxNumber(1);
List<SensorData> sensors = query.asList(numberLimitOption);
if (!sensors.isEmpty()) {
return sensors.get(0).getLocation();
} else {
Metrics.exceptionsThrown.labels("hogarama_services", "NoResultException", "SensorDAOImple.getLocationBySensorName").inc();
throw new NoResultException("Could not find location by sensorName");
}
}
public void save(SensorData data){
datastore.save(data);
}
}
| 3,752 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
WateringSetup.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-services/src/main/java/com/gepardec/hogarama/service/dao/WateringSetup.java | package com.gepardec.hogarama.service.dao;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gepardec.hogarama.annotations.MongoDAO;
import com.gepardec.hogarama.annotations.PostgresDAO;
import com.gepardec.hogarama.domain.unitmanagement.dao.PostgresWateringRuleDAO;
import com.gepardec.hogarama.domain.watering.WateringRuleDAO;
public class WateringSetup {
private static final Logger LOG = LoggerFactory.getLogger(WateringSetup.class);
@Inject @MongoDAO
private MongoWateringRuleDAO mongoDAO;
@Inject @PostgresDAO
private PostgresWateringRuleDAO postgresDAO;
@Produces
WateringRuleDAO createWateringRuleDao() {
switch (System.getProperty("hogarama.rules.storage", "postgres")) {
case "postgres":
LOG.debug("Produce PostgresWateringRuleDAO");
return postgresDAO;
case "mongo":
LOG.debug("Produce MongoWateringRuleDAO");
return mongoDAO;
default:
throw new RuntimeException(System.getProperty("hogarama.rules.storage", "postgres")
+ " is not valid for the System Property hogarama.rules.storage."
+ " Allowed values are 'postgres' or 'mongo'.");
}
}
}
| 1,323 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
WateringDAOImpl.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-services/src/main/java/com/gepardec/hogarama/service/dao/WateringDAOImpl.java | package com.gepardec.hogarama.service.dao;
import com.gepardec.hogarama.domain.metrics.Metrics;
import com.gepardec.hogarama.domain.watering.WateringDAO;
import com.gepardec.hogarama.domain.watering.WateringData;
import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.FindOptions;
import org.mongodb.morphia.query.Query;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import java.util.Date;
import java.util.List;
@RequestScoped
public class WateringDAOImpl implements WateringDAO {
@Inject
private Datastore dataStore;
@Override
public List<WateringData> getWateringData(Integer maxNumber, String actorName, Date from, Date to) {
Metrics.requestsTotal.labels("hogajama_services", "getWateringData");
Query<WateringData> query = dataStore.createQuery(WateringData.class).order("-_id");
limitQueryByActor(actorName, query);
limitQueryByDate(from, to, query);
FindOptions numberLimitOption = getFindOptionsWithMaxNumber(maxNumber);
return query.asList(numberLimitOption);
}
private void limitQueryByActor(String sensorName, Query<WateringData> query) {
if (StringUtils.isNotEmpty(sensorName)) {
query.field("name").equal(sensorName);
}
}
private void limitQueryByDate(Date from, Date to, Query<WateringData> query) {
if (from != null) {
if (to == null) {
to = new Date();
}
query.field("time").greaterThanOrEq(from);
query.field("time").lessThanOrEq(to);
}
}
private FindOptions getFindOptionsWithMaxNumber(Integer maxNumber) {
FindOptions findOptions = new FindOptions();
if (maxNumber != null && maxNumber >= 0) {
findOptions.limit(maxNumber);
}
return findOptions;
}
}
| 1,919 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
MongoWateringRuleDAO.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-services/src/main/java/com/gepardec/hogarama/service/dao/MongoWateringRuleDAO.java | package com.gepardec.hogarama.service.dao;
import java.util.List;
import jakarta.inject.Inject;
import org.mongodb.morphia.Datastore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gepardec.hogarama.domain.watering.WateringRuleDAO;
import com.gepardec.hogarama.annotations.MongoDAO;
import com.gepardec.hogarama.domain.watering.WateringConfigData;
import com.gepardec.hogarama.domain.watering.WateringRule;
import com.gepardec.hogarama.service.MongoDbProducer;
@MongoDAO
public class MongoWateringRuleDAO implements WateringRuleDAO{
private static final Logger LOG = LoggerFactory.getLogger(MongoWateringRuleDAO.class);
@Inject
public Datastore db;
public MongoWateringRuleDAO() {
}
@Override
public void save(WateringRule wconf) {
db.save(wconf);
}
@Override
public WateringRule getBySensorName(String sensorName) {
LOG.debug("getBySensorName " + sensorName);
List<WateringConfigData> configs = db.createQuery(WateringConfigData.class).field("sensorName").equal(sensorName).asList();
if (configs.isEmpty()){
return null;
}
return configs.get(0);
}
@Override
public WateringRule createWateringRule(String sensorName, String actorName, double lowWater, int waterDuration) {
return new WateringConfigData(sensorName, actorName, lowWater, waterDuration);
}
public void setUpForTest() {
MongoDbProducer producer = new MongoDbProducer();
db = producer.getDatastore();
}
} | 1,461 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
LoggerProducer.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-services/src/main/java/com/gepardec/hogarama/util/LoggerProducer.java | package com.gepardec.hogarama.util;
import jakarta.enterprise.inject.Produces;
import jakarta.enterprise.inject.spi.InjectionPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggerProducer {
@Produces
public Logger getLogger(InjectionPoint injectionPoint) {
return LoggerFactory.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
}
} | 388 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
HelloWorldEndpoint.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/raspberry-pi-mocks/raspberry-pi-mocks-gui/src/main/java/com/gepardec/hogajama/raspberrypimocks/rest/HelloWorldEndpoint.java | package com.gepardec.hogajama.raspberrypimocks.rest;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Produces;
@ApplicationScoped
@Path("/hello")
public class HelloWorldEndpoint {
@GET
@Produces("text/plain")
public Response doGet() {
return Response.ok("Hello from WildFly Swarm!").build();
}
} | 419 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
Endpoint.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/raspberry-pi-mocks/raspberry-pi-mocks-gui/src/main/java/com/gepardec/hogajama/raspberrypimocks/websocket/Endpoint.java | package com.gepardec.hogajama.raspberrypimocks.websocket;
import com.gepardec.hogarama.mocks.cli.MqttClient;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Optional;
@ServerEndpoint("/mock")
public class Endpoint {
private static final String TEST_MESSAGE = "{\"sensorName\" : \"$name\", \"type\" : \"$type\", \"value\" : $value, \"location\" : \"Wien\", \"version\" : 0}";
private static final Logger LOGGER = LoggerFactory.getLogger(Endpoint.class);
private MqttClient mqttClient;
@PostConstruct
public void init() {
mqttClient = new MqttClient().
defaultConnection().
withTopic(Optional.ofNullable(System.getenv("AMQ_TOPICS")).orElse("habarama")).
build();
}
@OnOpen
public void open(Session session) {
}
@OnClose
public void close(Session session, CloseReason c) {
}
@OnMessage
public void receiveMessage(String messageString, Session session) {
try {
if("ping".equals(messageString)) {
session.getBasicRemote().sendText("pong");
} else {
String[] values = messageString.split(",");
String messageToSend = TEST_MESSAGE.replace("$name", values[0]).replace("$type", values[1]).replace("$value", values[2]);
mqttClient.connectAndPublish(messageToSend);
session.getBasicRemote().sendText("ok");
}
} catch (IOException e) {
LOGGER.error("Exception occured while receiving messages", e);
}
}
}
| 1,551 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
MqttClientTest.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/raspberry-pi-mocks/raspberry-pi-mocks-cli/src/test/java/com/gepardec/hogarama/mocks/cli/MqttClientTest.java | package com.gepardec.hogarama.mocks.cli;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.fusesource.mqtt.client.BlockingConnection;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.QoS;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class MqttClientTest {
@Mock
private MQTT mockMQTT;
@Mock
private BlockingConnection mockBlockingConnection;
private MqttClient mqttClient;
@BeforeEach
public void setup() {
mqttClient = new MqttClient().
withURL("https://testhost:1234/").
withUser("testuser").
withPassword("testpwd").
withTopic("testtopic").
build();
final Field f = FieldUtils.getField(mqttClient.getClass(), "mqtt", true);
try {
f.set(mqttClient, mockMQTT);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Test
public void testBasicRun() throws Exception {
when(mockMQTT.blockingConnection()).thenReturn(mockBlockingConnection);
mqttClient.connectAndPublish("testmsg");
verify(mockBlockingConnection, times(1)).connect();
verify(mockBlockingConnection, times(1)).publish("testtopic", "testmsg".getBytes(), QoS.AT_LEAST_ONCE, false);
verify(mockBlockingConnection, times(1)).disconnect();
}
@Test
public void testMultipleMessages() throws Exception {
when(mockMQTT.blockingConnection()).thenReturn(mockBlockingConnection);
List<String> messages = new ArrayList<>();
messages.add("msg1");
messages.add("msg2");
mqttClient.connectAndPublish(messages, 0L);
verify(mockBlockingConnection, times(1)).connect();
verify(mockBlockingConnection, times(1)).publish("testtopic", "msg1".getBytes(), QoS.AT_LEAST_ONCE, false);
verify(mockBlockingConnection, times(1)).publish("testtopic", "msg2".getBytes(), QoS.AT_LEAST_ONCE, false);
verify(mockBlockingConnection, times(1)).disconnect();
}
@Test
public void testFixBrokerUrl() throws Exception {
check("ssl://myhost:443", "https://myhost");
check("ssl://myhost:443", "ssl://myhost");
check("ssl://myhost:8443", "https://myhost:8443");
check("tcp://myhost:80", "http://myhost");
check("tcp://myhost:8080", "http://myhost:8080");
}
private void check(String expected, String url) {
assertEquals(expected, MqttClient.fixUrl(url));
}
}
| 2,802 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
MockCliTest.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/raspberry-pi-mocks/raspberry-pi-mocks-cli/src/test/java/com/gepardec/hogarama/mocks/cli/MockCliTest.java | package com.gepardec.hogarama.mocks.cli;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class MockCliTest {
@Test
public void testCreateRunConfigurationFromArguments() throws Exception {
String properties = "brokerHost=url" + System.lineSeparator() +
"brokerUsername=user" + System.lineSeparator() +
"brokerPassword=pwd" + System.lineSeparator() +
"brokerTopic=topic";
String propsFile = writeToTempFile("props.props", properties);
String messagesFile = writeToTempFile("messages.json", "{1},{2}");
String [] args = new String[] {"-t", messagesFile, "-c", propsFile, "--delayMs", "3000"};
RunConfiguration runConfiguration = MockCli.createRunConfigurationFromArguments(args);
assertEquals("url", runConfiguration.getHost());
assertEquals("user", runConfiguration.getUser());
assertEquals("pwd", runConfiguration.getPassword());
assertEquals("topic", runConfiguration.getTopic());
assertEquals(3000L, runConfiguration.getDelayMs());
assertTrue(Arrays.equals(new String[]{"{1}", "{2}"}, runConfiguration.getMockMessages().toArray()));
assertEquals("amq", runConfiguration.getBroker());
}
@Test
public void testCreateRunConfigurationForKafka() throws Exception {
String properties = "brokerHost=url" + System.lineSeparator() +
"brokerUsername=user" + System.lineSeparator() +
"brokerPassword=pwd" + System.lineSeparator() +
"sslTruststoreLocation=/x/truststore.jks" + System.lineSeparator() +
"brokerTopic=topic";
String propsFile = writeToTempFile("props.props", properties);
String messagesFile = writeToTempFile("messages.json", "{1},{2}");
String[] args = new String[]{"-t", messagesFile, "-c", propsFile, "-b", "kafka", "--delayMs", "3000"};
RunConfiguration runConfiguration = MockCli.createRunConfigurationFromArguments(args);
assertEquals("url", runConfiguration.getHost());
assertEquals("/x/truststore.jks", runConfiguration.getSslTruststoreLocation());
assertEquals("kafka", runConfiguration.getBroker());
}
@Test
public void testCreateRunConfigurationForRest() throws Exception {
String properties = "dummyMessagingRestEndpointUrl=testUrl";
String propsFile = writeToTempFile("props.props", properties);
String messagesFile = writeToTempFile("messages.json", "{1},{2}");
String[] args = new String[]{"-t", messagesFile, "-c", propsFile, "-b", "rest", "--delayMs", "3000"};
RunConfiguration runConfiguration = MockCli.createRunConfigurationFromArguments(args);
assertEquals("testUrl", runConfiguration.getDummyMessagingRestEndpointUrl());
assertEquals("rest", runConfiguration.getBroker());
}
private static final String writeToTempFile(String filename, String content) throws IOException {
File tempFile = File.createTempFile(filename, "");
FileOutputStream tempFileOutputStream = new FileOutputStream(tempFile);
tempFileOutputStream.write(content.getBytes());
tempFileOutputStream.close();
return tempFile.getAbsolutePath();
}
}
| 3,521 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
RunConfiguration.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/raspberry-pi-mocks/raspberry-pi-mocks-cli/src/main/java/com/gepardec/hogarama/mocks/cli/RunConfiguration.java | package com.gepardec.hogarama.mocks.cli;
import org.apache.commons.cli.CommandLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RunConfiguration {
public static final Logger LOGGER = LoggerFactory.getLogger(RunConfiguration.class);
public static final String BROKER = "broker";
public static final String BROKER_HOST = "brokerHost";
public static final String BROKER_USERNAME = "brokerUsername";
public static final String BROKER_PASSWORD = "brokerPassword";
public static final String BROKER_TOPIC = "brokerTopic";
public static final String PATH_TO_TEST_DATA = "testData";
public static final String DELAY_MS = "delayMs";
public static final String PATH_TO_CONFIG = "configuration";
// Options for Kafka
public static final String SECURITY_PROTOCOL = "securityProtocol";
public static final String SSL_TRUSTSTORE_LOCATION = "sslTruststoreLocation";
public static final String SSL_TRUSTSTORE_PASSWORD = "sslTruststorePassword";
// Options for Rest-Endpoint-URL
public static final String DUMMY_MESSAGING_REST_ENDPOINT_URL = "dummyMessagingRestEndpointUrl";
private CommandLine cliArguments;
private Properties properties;
private String broker;
private String host;
private String user;
private String password;
private String topic;
private long delayMs;
private List<String> mockMessages;
// For Kafka
private String securityProtocol;
private String sslTruststoreLocation;
private String sslTruststorePassword;
// For Dummy Messaging REST Url
private String dummyMessagingRestEndpointUrl;
public RunConfiguration(CommandLine cliArguments, Properties properties) {
this.cliArguments = cliArguments;
this.properties = properties;
broker = configParam(BROKER, "amq");
host = configParam(BROKER_HOST, "https://broker-amq-mqtt-ssl-hogarama.10.0.75.2.nip.io");
user = configParam(BROKER_USERNAME, "mq_habarama");
password = configParam(BROKER_PASSWORD, "mq_habarama_pass");
topic = configParam(BROKER_TOPIC, "habarama");
delayMs = Long.parseLong(configParam(DELAY_MS, "3000"));
mockMessages = getTestMessages();
securityProtocol = configParam(SECURITY_PROTOCOL, "PLAINTEXT");
sslTruststoreLocation = configParam(SSL_TRUSTSTORE_LOCATION, "");
sslTruststorePassword = configParam(SSL_TRUSTSTORE_PASSWORD, "password");
dummyMessagingRestEndpointUrl = configParam(DUMMY_MESSAGING_REST_ENDPOINT_URL, "http://localhost:8080/hogajama-rs/rest/messaging/sensorData");
}
public String getBroker() {
return broker;
}
public String getHost() {
return host;
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
public String getTopic() {
return topic;
}
public long getDelayMs() {
return delayMs;
}
public List<String> getMockMessages() {
return mockMessages;
}
public String getSecurityProtocol() {
return securityProtocol;
}
public String getSslTruststoreLocation() {
return sslTruststoreLocation;
}
public String getSslTruststorePassword() {
return sslTruststorePassword;
}
public String getDummyMessagingRestEndpointUrl() {
return dummyMessagingRestEndpointUrl;
}
private List<String> getTestMessages() {
try {
String pathToTestData = cliArguments.getOptionValue(RunConfiguration.PATH_TO_TEST_DATA);
String content = new String(Files.readAllBytes(Paths.get(pathToTestData)));
List<String> messages = new ArrayList<>();
Matcher m = Pattern.compile("\\{[^\\{\\}]*\\}").matcher(content);
while (m.find()) {
messages.add(m.group());
}
return messages;
} catch (IOException e) {
MockCli.LOGGER.error("Exception occured while getting test messages", e);
System.exit(1);
return null;
}
}
private String configParam(String paramName, String defaultValue) {
if (cliArguments.hasOption(paramName)) {
return cliArguments.getOptionValue(paramName);
} else if (properties.containsKey(paramName)) {
return properties.getProperty(paramName);
} else {
return defaultValue;
}
}
public void print() {
LOGGER.info("=================== Hogarama Mock Cli Config =================");
print(BROKER, getBroker());
print(BROKER_HOST, getHost());
print(BROKER_USERNAME, getUser());
print(BROKER_PASSWORD, getPassword());
print(BROKER_TOPIC, getTopic());
print(DELAY_MS, getDelayMs());
LOGGER.info("For Kafka");
print(SECURITY_PROTOCOL, getSecurityProtocol());
print(SSL_TRUSTSTORE_LOCATION, getSslTruststoreLocation());
LOGGER.info(System.lineSeparator());
LOGGER.info("For Rest");
print(DUMMY_MESSAGING_REST_ENDPOINT_URL, getDummyMessagingRestEndpointUrl());
LOGGER.info(System.lineSeparator());
}
private void print(String key, Object value) {
LOGGER.info(key + "=" + value);
}
}
| 5,566 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
KafkaClient.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/raspberry-pi-mocks/raspberry-pi-mocks-cli/src/main/java/com/gepardec/hogarama/mocks/cli/KafkaClient.java | package com.gepardec.hogarama.mocks.cli;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.config.SslConfigs;
import org.apache.kafka.common.serialization.LongSerializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class KafkaClient {
public static final Logger LOGGER = LoggerFactory.getLogger(KafkaClient.class);
public static void execute(RunConfiguration runConfiguration) throws InterruptedException {
Producer<Long, String> customerProducer = createKafkaProducer(runConfiguration);
for(String valueToSend : runConfiguration.getMockMessages()) {
sendToKafka(customerProducer, valueToSend, runConfiguration.getTopic());
TimeUnit.MILLISECONDS.sleep(runConfiguration.getDelayMs());
}
LOGGER.info(System.lineSeparator() + "=================== Hogarama Mock Cli Kafka Finished =================");
}
private static Producer<Long, String> createKafkaProducer(RunConfiguration runConfiguration) {
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, runConfiguration.getHost());
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.RETRIES_CONFIG, 0);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName());
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, runConfiguration.getSecurityProtocol());
props.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, runConfiguration.getSslTruststoreLocation());
props.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, runConfiguration.getSslTruststorePassword());
return new KafkaProducer<>(props);
}
private static boolean sendToKafka(Producer<Long, String> producer, String valueToSend, String topic) {
boolean sendingSuccess = true;
ProducerRecord<Long, String> record = new ProducerRecord<>(topic, valueToSend);
try {
RecordMetadata metadata = producer.send(record).get();
System.out.println("Record \"" + valueToSend + "\" sent to partition " + metadata.partition()
+ " with offset " + metadata.offset());
} catch (InterruptedException | ExecutionException e) {
System.out.println("Error in sending record");
e.printStackTrace();
sendingSuccess = false;
}
return sendingSuccess;
}
}
| 2,640 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
MqttClient.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/raspberry-pi-mocks/raspberry-pi-mocks-cli/src/main/java/com/gepardec/hogarama/mocks/cli/MqttClient.java | package com.gepardec.hogarama.mocks.cli;
import org.fusesource.mqtt.client.BlockingConnection;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.QoS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class MqttClient {
private static final String TCP = "tcp";
private static final String SSL = "ssl";
private static final String HTTP = "http";
private static final String HTTPS = "https";
private static String PORT_PROVIDED_REGEX ="(.*)(:\\d+)";
private static final Logger LOGGER = LoggerFactory.getLogger(MqttClient.class);
private MQTT mqtt;
private String host;
private String user;
private String password;
private String topic;
public MqttClient defaultConnection() {
return withURL(Optional.ofNullable(System.getenv("AMQ_URL")).orElse("https://broker-amq-mqtt-ssl:8883")).
withUser(Optional.ofNullable(System.getenv("AMQ_USERNAME")).orElse("mq_habarama")).
withPassword(Optional.ofNullable(System.getenv("AMQ_PASSWORD")).orElse("mq_habarama_pass"));
}
public static void execute(RunConfiguration runConfiguration) {
MqttClient mqttClient = new MqttClient().
withURL(runConfiguration.getHost()).
withUser(runConfiguration.getUser()).
withPassword(runConfiguration.getPassword()).
withTopic(runConfiguration.getTopic()).
build();
mqttClient.connectAndPublish(runConfiguration.getMockMessages(), runConfiguration.getDelayMs());
}
/**
* Set the URL to connect to the message broker
* @param url
* @return
*/
public MqttClient withURL(String url) {
this.host = fixUrl(url);
return this;
}
protected static String fixUrl(String url) {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
throw new RuntimeException("Error creating URI from " + url, e);
}
int port = uri.getPort();
String scheme = uri.getScheme();
if ( HTTPS.equals(scheme) ) {
scheme = SSL;
}
if ( port == -1 && SSL.equals(scheme) ) {
port = 443;
}
if ( HTTP.equals(scheme) ) {
scheme = TCP;
}
if ( port == -1 && TCP.equals(scheme) ) {
port = 80;
}
String host;
try {
host = new URI(scheme,uri.getUserInfo(), uri.getHost(), port, uri.getPath(), uri.getQuery(), uri.getFragment()).toString();
} catch (URISyntaxException e) {
throw new RuntimeException("Error recreating URI from " + url, e);
}
return host;
}
/**
* Use {@link #withURL(String)} instead. This funktion contains obscure logic.
* @param host
* @return
*/
@Deprecated
public MqttClient withHost(String host) {
this.host = host.replaceAll(HTTPS, SSL);
this.host = this.host.replaceAll("http", "tcp");
if(!this.host.matches(PORT_PROVIDED_REGEX)) {
this.host += ":8883";
}
return this;
}
public MqttClient withUser(String user) {
this.user = user;
return this;
}
public MqttClient withPassword(String password) {
this.password = password;
return this;
}
public MqttClient withTopic(String topic) {
this.topic = topic;
return this;
}
public MqttClient build() {
try {
mqtt = new MQTT();
mqtt.setHost(host);
mqtt.setUserName(user);
mqtt.setPassword(password);
mqtt.setConnectAttemptsMax(2);
SSLContext sslContext = createSSLContext();
mqtt.setSslContext(sslContext);
return this;
} catch (Exception e) {
LOGGER.error("Error while configuring ", e);
return null;
}
}
public void connectAndPublish(List<String> messages, long delayMs) {
try {
LOGGER.info("Publising to " + this.host);
BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
int counter = 0;
for(String message : messages) {
counter++;
connection.publish(this.topic, message.getBytes(), QoS.AT_LEAST_ONCE, false);
LOGGER.info("Published " + counter + " of " + messages.size());
Thread.sleep(delayMs);
}
connection.disconnect();
} catch (Exception e) {
LOGGER.error("Error while publishing ", e);
}
}
public void connectAndPublish(String ... messages) {
connectAndPublish(Arrays.asList(messages), 1000L);
}
private SSLContext createSSLContext() throws NoSuchAlgorithmException, KeyStoreException,
CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(MockCli.class.getResourceAsStream("/broker.jks"), "L(o?cqGPtJ}7YiHu".toCharArray());
InputStream keystoreInputStream = MockCli.class.getResourceAsStream("/broker.jks");
byte[] keystoreBuffer = new byte[keystoreInputStream.available()];
keystoreInputStream.read(keystoreBuffer);
File keystoreTempFile = File.createTempFile("broker", ".jks");
try (FileOutputStream keystoreOutputStream = new FileOutputStream(keystoreTempFile)){
keystoreOutputStream.write(keystoreBuffer);
}
System.setProperty("javax.net.ssl.trustStore" , keystoreTempFile.getAbsolutePath());
factory.init(keyStore, "L(o?cqGPtJ}7YiHu".toCharArray());
sslContext.init(factory.getKeyManagers(), null, null);
return sslContext;
}
}
| 5,704 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
MockCli.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/raspberry-pi-mocks/raspberry-pi-mocks-cli/src/main/java/com/gepardec/hogarama/mocks/cli/MockCli.java | package com.gepardec.hogarama.mocks.cli;
import org.apache.commons.cli.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MockCli {
public static final Logger LOGGER = LoggerFactory.getLogger(MockCli.class);
public static void main(String[] args) throws InterruptedException {
RunConfiguration runConfiguration = createRunConfigurationFromArguments(args);
runConfiguration.print();
switch (runConfiguration.getBroker()) {
case "kafka":
KafkaClient.execute(runConfiguration);
break;
case "amq":
MqttClient.execute(runConfiguration);
break;
case "rest":
RestClient.execute(runConfiguration);
break;
default:
LOGGER.error("Broker {} not supported", runConfiguration.getBroker());
}
LOGGER.info(System.lineSeparator() + "=================== Hogarama Mock Cli Finished =================");
}
protected static RunConfiguration createRunConfigurationFromArguments(String[] args) {
CommandLine cliArguments = parseCliArguments(args);
Properties properties = loadProperties(cliArguments.getOptionValue(RunConfiguration.PATH_TO_CONFIG));
RunConfiguration configuration = new RunConfiguration(cliArguments, properties);
return configuration;
}
private static Options createOptions() {
Options options = new Options();
options.addOption(new Option("h", "help", false, "print this message"));
options.addRequiredOption("t", RunConfiguration.PATH_TO_TEST_DATA, true,
"Absolute path to file with test data");
options.addOption("c", RunConfiguration.PATH_TO_CONFIG, true,
"Absolute path to configuration file. Shoud contains key, value pairs in form key=value");
options.addOption(new Option("d", RunConfiguration.DELAY_MS, true,
"Delay between publishings in ms. It overrides the parameter delay in configuration file. Default value is 3000."));
options.addOption(new Option("host", RunConfiguration.BROKER_HOST, true,
"Url to AMQ Broker. Overrides the parameter in configuration file."));
options.addOption(new Option("u", RunConfiguration.BROKER_USERNAME, true,
"Username. Overrides the parameter in configuration file."));
options.addOption(new Option("p", RunConfiguration.BROKER_PASSWORD, true,
"Password. Overrides the parameter in configuration file."));
options.addOption(new Option("topic", RunConfiguration.BROKER_TOPIC, true,
"Topic name. Overrides the parameter in configuration file."));
options.addOption(new Option("b", RunConfiguration.BROKER, true,
"Broker to use: amq (default), kafka or rest"));
return options;
}
private static CommandLine parseCliArguments(String[] args) {
Options options = createOptions();
CommandLineParser parser = new DefaultParser();
try {
CommandLine cli = parser.parse(options, args);
if (cli.hasOption("help")) {
printHelp(options);
return null;
} else {
return cli;
}
} catch (ParseException exp) {
LOGGER.error(exp.getMessage());
printHelp(options);
return null;
}
}
private static Properties loadProperties(String filepath) {
Properties prop = new Properties();
InputStream input = null;
if (filepath == null) {
return prop;
}
try {
input = new FileInputStream(filepath);
prop.load(input);
return prop;
} catch (IOException ex) {
LOGGER.error("An exception occured while loading properties", ex);
System.exit(1);
return new Properties();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
LOGGER.error("Exception occured while closing inputstream", e);
System.exit(1);
}
}
}
}
private static void printHelp(Options options) {
HelpFormatter formater = new HelpFormatter();
formater.printHelp("java -jar hogarama-mock-cli.jar -c <arg> -t <arg>", options);
System.exit(0);
}
}
| 4,673 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
RestClient.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/raspberry-pi-mocks/raspberry-pi-mocks-cli/src/main/java/com/gepardec/hogarama/mocks/cli/RestClient.java | package com.gepardec.hogarama.mocks.cli;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;
public class RestClient {
public static final Logger LOGGER = LoggerFactory.getLogger(RestClient.class);
public static void execute(RunConfiguration runConfiguration) throws InterruptedException {
for (String valueToSend : runConfiguration.getMockMessages()) {
try {
sendPostRequest(runConfiguration.getDummyMessagingRestEndpointUrl(), valueToSend);
} catch (Exception e) {
LOGGER.error("Exception while sending {}. Execution will be interrupted", valueToSend, e);
throw new RuntimeException(e);
}
TimeUnit.MILLISECONDS.sleep(runConfiguration.getDelayMs());
}
LOGGER.info(System.lineSeparator() + "=================== Hogarama Mock Cli REST Client Finished =================");
}
private static void sendPostRequest(String url, String payload) throws Exception {
LOGGER.info("Send " + payload + " on " + url);
URL object = new URL(url);
HttpURLConnection connection = (HttpURLConnection) object.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("POST");
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(payload);
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
LOGGER.info("Response Code : " + responseCode);
String response;
if (responseCode != 200) {
response = getResponseString(connection.getErrorStream());
} else {
response = getResponseString(connection.getInputStream());
}
LOGGER.info("Response Body : " + response + System.lineSeparator());
}
private static String getResponseString(InputStream inputStream) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
return response.toString();
}
}
}
| 2,560 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
UnitApi.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/UnitApi.java | package com.gepardec.hogarama.rest.unitmanagement;
import com.gepardec.hogarama.rest.unitmanagement.dto.UnitDto;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public interface UnitApi {
@GET
Response getForUser();
@PUT
Response create(UnitDto unitDto);
@PATCH
@Path("/{id}")
Response update(@PathParam("id") String id, UnitDto unitDto);
@DELETE
@Path("/{id}")
Response delete(@PathParam("id") String id);
}
| 581 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
BaseResponse.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/BaseResponse.java | package com.gepardec.hogarama.rest.unitmanagement;
import jakarta.ws.rs.core.Response;
public class BaseResponse<T> {
private T response;
private int statusCode;
private String message;
public BaseResponse(T response, int statusCode) {
this.response = response;
this.statusCode = statusCode;
}
public BaseResponse(int statusCode) {
this.statusCode = statusCode;
}
public Response createRestResponse() {
return Response.status(statusCode).entity(this).build();
}
public T getResponse() {
return response;
}
public void setResponse(T response) {
this.response = response;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| 989 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
RuleApi.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/RuleApi.java | package com.gepardec.hogarama.rest.unitmanagement;
import com.gepardec.hogarama.rest.unitmanagement.dto.RuleDto;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public interface RuleApi {
@GET
Response getForUser();
@PUT
Response create(RuleDto actorDto);
@PATCH
@Path("/{id}")
Response update(@PathParam("id") String id, RuleDto actorDto);
@DELETE
@Path("/{id}")
Response delete(@PathParam("id") String id);
}
| 583 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
SensorApi.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/SensorApi.java | package com.gepardec.hogarama.rest.unitmanagement;
import com.gepardec.hogarama.rest.unitmanagement.dto.SensorDto;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public interface SensorApi {
@GET
Response getForUser();
@PUT
Response create(SensorDto sensorDto);
@PATCH
@Path("/{id}")
Response update(@PathParam("id") String id, SensorDto sensorDto);
@DELETE
@Path("/{id}")
Response delete(@PathParam("id") String id);
}
| 593 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
PATCH.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/PATCH.java | package com.gepardec.hogarama.rest.unitmanagement;
import jakarta.ws.rs.HttpMethod;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("PATCH")
public @interface PATCH {
}
| 362 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
UserApi.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/UserApi.java | package com.gepardec.hogarama.rest.unitmanagement;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public interface UserApi {
@GET
Response getUser();
}
| 381 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
ActorApi.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/ActorApi.java | package com.gepardec.hogarama.rest.unitmanagement;
import com.gepardec.hogarama.rest.unitmanagement.dto.ActorDto;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public interface ActorApi {
@GET
Response getForUser();
@PUT
Response create(ActorDto actorDto);
@PATCH
@Path("/{id}")
Response update(@PathParam("id") String id, ActorDto actorDto);
@DELETE
@Path("/{id}")
Response delete(@PathParam("id") String id);
}
| 587 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
ClientConfig.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/dto/ClientConfig.java | package com.gepardec.hogarama.rest.unitmanagement.dto;
public class ClientConfig {
private String authServerUrl;
private String realm;
private String clientIdFrontend;
public String getAuthServerUrl() {
return authServerUrl;
}
public void setAuthServerUrl(String authServerUrl) {
this.authServerUrl = authServerUrl;
}
public String getRealm() {
return realm;
}
public void setRealm(String realm) {
this.realm = realm;
}
public String getClientIdFrontend() {
return clientIdFrontend;
}
public void setClientIdFrontend(String clientIdFrontend) {
this.clientIdFrontend = clientIdFrontend;
}
}
| 706 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
UnitDto.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/dto/UnitDto.java | package com.gepardec.hogarama.rest.unitmanagement.dto;
public class UnitDto extends BaseDto {
private String description;
private Boolean defaultUnit;
private String name;
private Long userId;
public UnitDto() {
}
private UnitDto(Long id, String description, boolean defaultUnit, String name, Long userId) {
super(id);
this.description = description;
this.defaultUnit = defaultUnit;
this.name = name;
this.userId = userId;
}
public static UnitDto of(Long id, String description, boolean defaultUnit, String name, Long userId) {
return new UnitDto(id, description, defaultUnit, name, userId);
}
public String getDescription() {
return description;
}
public Boolean isDefaultUnit() {
return defaultUnit;
}
public String getName() {
return name;
}
public Long getUserId() {
return userId;
}
public void setDescription(String description) {
this.description = description;
}
public void setDefaultUnit(Boolean defaultUnit) {
this.defaultUnit = defaultUnit;
}
public void setName(String name) {
this.name = name;
}
public void setUserId(Long userId) {
this.userId = userId;
}
@Override
public String toString() {
return "UnitDto{" +
"id=" + id +
", description='" + description + '\'' +
", defaultUnit=" + defaultUnit +
", name='" + name + '\'' +
", userId=" + userId +
'}';
}
}
| 1,621 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
BaseDto.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/dto/BaseDto.java | package com.gepardec.hogarama.rest.unitmanagement.dto;
public abstract class BaseDto {
protected Long id;
public BaseDto() {
}
protected BaseDto(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
| 320 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
UserDto.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/dto/UserDto.java | package com.gepardec.hogarama.rest.unitmanagement.dto;
public class UserDto {
private String givenName;
private String familyName;
private String name;
private String email;
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
| 786 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
SensorDto.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/dto/SensorDto.java | package com.gepardec.hogarama.rest.unitmanagement.dto;
public class SensorDto extends BaseDto {
private String name;
private String deviceId;
private Long unitId;
private Long sensorTypeId;
public SensorDto() {
}
private SensorDto(Long id, String name, String deviceId, Long unitId, Long sensorTypeId) {
super(id);
this.name = name;
this.deviceId = deviceId;
this.unitId = unitId;
this.sensorTypeId = sensorTypeId;
}
public static SensorDto of(Long id, String name, String deviceId, Long unitId, Long sensorTypeId) {
return new SensorDto(id, name, deviceId, unitId, sensorTypeId);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public Long getUnitId() {
return unitId;
}
public void setUnitId(Long unitId) {
this.unitId = unitId;
}
public Long getSensorTypeId() {
return sensorTypeId;
}
public void setSensorTypeId(Long sensorTypeId) {
this.sensorTypeId = sensorTypeId;
}
}
| 1,276 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
ActorDto.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/dto/ActorDto.java | package com.gepardec.hogarama.rest.unitmanagement.dto;
public class ActorDto extends BaseDto {
private String name;
private String deviceId;
private Long unitId;
private String queueName;
public ActorDto() {
}
private ActorDto(Long id, String name, String deviceId, Long unitId, String queueName) {
super(id);
this.name = name;
this.deviceId = deviceId;
this.unitId = unitId;
this.queueName = queueName;
}
public static ActorDto of(Long id, String name, String deviceId, Long unitId, String queueName) {
return new ActorDto(id, name, deviceId, unitId, queueName);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public Long getUnitId() {
return unitId;
}
public void setUnitId(Long unitId) {
this.unitId = unitId;
}
public String getQueueName() { return queueName; }
public void setQueueName(String queueName) { this.queueName = queueName; }
}
| 1,219 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
RuleDto.java | /FileExtraction/Java_unseen/Gepardec_Hogarama/Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/dto/RuleDto.java | package com.gepardec.hogarama.rest.unitmanagement.dto;
public class RuleDto extends BaseDto {
private String name;
private String description;
private Long sensorId;
private Long actorId;
private Long unitId;
private int waterDuration;
private double lowWater;
public RuleDto() {
}
private RuleDto(Long id, String name, String description, Long sensorId, Long actorId, Long unitId, int waterDuration, double lowWater) {
super(id);
this.name = name;
this.description = description;
this.sensorId = sensorId;
this.actorId = actorId;
this.unitId = unitId;
this.waterDuration = waterDuration;
this.lowWater = lowWater;
}
public static RuleDto of(Long id, String name, String description, Long sensorId, Long actorId, Long unitId, int waterDuration, double lowWater) {
return new RuleDto( id, name, description, sensorId, actorId, unitId, waterDuration, lowWater);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getSensorId() {
return sensorId;
}
public void setSensorId(Long sensorId) {
this.sensorId = sensorId;
}
public Long getActorId() {
return actorId;
}
public void setActorId(Long actorId) {
this.actorId = actorId;
}
public int getWaterDuration() {
return waterDuration;
}
public void setWaterDuration(int waterDuration) {
this.waterDuration = waterDuration;
}
public double getLowWater() {
return lowWater;
}
public void setLowWater(double lowWater) {
this.lowWater = lowWater;
}
public Long getUnitId() {
return unitId;
}
public void setUnitId(Long unitId) {
this.unitId = unitId;
}
}
| 2,060 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
dashboard-java-system-metrics.yml | /FileExtraction/Java_unseen/Gepardec_Hogarama/OCP-Infrastructure/helm/grafana/templ_new/dashboard-java-system-metrics.yml | apiVersion: integreatly.org/v1alpha1
kind: GrafanaDashboard
metadata:
labels:
app: hogarama
dashboard: application
name: java-system-metrics
namespace: {{ .Release.Namespace }}
finalizers: []
spec:
json: |
{
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": {
"type": "datasource",
"uid": "grafana"
},
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"target": {
"limit": 100,
"matchAny": false,
"tags": [],
"type": "dashboard"
},
"type": "dashboard"
}
]
},
"description": "MicroProfile Metrics Endpoint Monitoring",
"editable": true,
"fiscalYearStartMonth": 0,
"gnetId": 12853,
"graphTooltip": 1,
"id": 39,
"links": [],
"liveNow": false,
"panels": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [
{
"options": {
"0": {
"text": "DOWN"
},
"1": {
"text": "UP"
}
},
"type": "value"
}
],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "#d44a3a",
"value": null
},
{
"color": "#37872D",
"value": 1
},
{
"color": "#FADE2A"
}
]
},
"unit": "none"
},
"overrides": []
},
"gridPos": {
"h": 2,
"w": 4,
"x": 0,
"y": 0
},
"id": 29,
"links": [],
"maxDataPoints": 100,
"options": {
"colorMode": "background",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"textMode": "auto"
},
"pluginVersion": "9.3.1",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"exemplar": false,
"expr": "up{job=\"$serviceID\", pod=~\"$pod\"}",
"instant": true,
"range": false,
"refId": "A"
}
],
"title": "Status",
"type": "stat"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": " base_jvm_uptime_seconds Displays the uptime of the JVM in milliseconds.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [
{
"options": {
"match": "null",
"result": {
"text": "N/A"
}
},
"type": "special"
}
],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
},
"unit": "s"
},
"overrides": []
},
"gridPos": {
"h": 2,
"w": 3,
"x": 4,
"y": 0
},
"id": 26,
"links": [],
"maxDataPoints": 100,
"options": {
"colorMode": "none",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"textMode": "auto"
},
"pluginVersion": "9.3.1",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_jvm_uptime_seconds{pod=~\"$pod\", job=\"$serviceID\"}",
"legendFormat": " ",
"range": true,
"refId": "A"
}
],
"title": "Uptime",
"type": "stat"
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "base_gc_total_total Displays the total number of collections that have occurred. This attribute lists -1 if the collection count is undefined for this collector.",
"fieldConfig": {
"defaults": {
"links": []
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 8,
"x": 7,
"y": 0
},
"hiddenSeries": false,
"id": 14,
"legend": {
"alignAsTable": true,
"avg": true,
"current": true,
"max": true,
"min": true,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "9.3.1",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "builder",
"expr": "rate(base_gc_total{job=~\"$serviceID\", pod=~\"$pod\"}[5m])",
"intervalFactor": 2,
"legendFormat": {{`"{{ name }}"`}},
"range": true,
"refId": "A"
}
],
"thresholds": [],
"timeRegions": [],
"title": "GC Copy & Mark Sweep Total",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": true
}
],
"yaxis": {
"align": false
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "base_gc_time_total Displays the approximate accumulated collection elapsed time in milliseconds. This attribute displays -1 if the collection elapsed time is undefined for this collector. The JVM implementation may use a high resolution timer to measure the elapsed time. This attribute may display the same value even if the collection count has been incremented if the collection elapsed time is very short.",
"fieldConfig": {
"defaults": {
"links": []
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 8,
"x": 15,
"y": 0
},
"hiddenSeries": false,
"id": 12,
"legend": {
"alignAsTable": true,
"avg": true,
"current": true,
"max": true,
"min": true,
"rightSide": false,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "9.3.1",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "rate(base_gc_time_total_seconds{pod=~\"$pod\", job=\"$serviceID\"}[5m])",
"legendFormat": {{`"{{ name }}"`}},
"range": true,
"refId": "A"
}
],
"thresholds": [],
"timeRegions": [],
"title": "GC Copy & Mark Sweep Time",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "ms",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": false
}
],
"yaxis": {
"align": false
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "",
"fieldConfig": {
"defaults": {
"links": []
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 6,
"w": 7,
"x": 0,
"y": 2
},
"hiddenSeries": false,
"id": 8,
"legend": {
"alignAsTable": true,
"avg": true,
"current": true,
"max": true,
"min": true,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "9.3.1",
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_cpu_systemLoadAverage{pod=~\"$pod\",job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "CPU load",
"range": true,
"refId": "A"
}
],
"thresholds": [],
"timeRegions": [],
"title": "CPU Load",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "percentunit",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": false
}
],
"yaxis": {
"align": false
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"links": []
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 9,
"w": 23,
"x": 0,
"y": 8
},
"hiddenSeries": false,
"hideTimeOverride": false,
"id": 10,
"interval": "",
"legend": {
"alignAsTable": true,
"avg": true,
"current": true,
"max": true,
"min": true,
"rightSide": false,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "9.3.1",
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_memory_usedHeap_bytes{pod=~\"$pod\",job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "Used Heap",
"range": true,
"refId": "A"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "base_memory_committedHeap_bytes{pod=~\"$pod\", job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "Commited Heap",
"refId": "C"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "base_memory_maxHeap_bytes{pod=~\"$pod\", job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "Max Heap",
"refId": "B"
}
],
"thresholds": [],
"timeRegions": [],
"title": "Heap Sizes",
"tooltip": {
"shared": true,
"sort": 2,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "decbytes",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": false
}
],
"yaxis": {
"align": false
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"links": []
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 6,
"w": 10,
"x": 0,
"y": 17
},
"hiddenSeries": false,
"id": 2,
"legend": {
"alignAsTable": true,
"avg": true,
"current": true,
"max": true,
"min": true,
"rightSide": false,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "9.3.1",
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_thread_count{pod=~\"$pod\",job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "Thread Count",
"range": true,
"refId": "A"
}
],
"thresholds": [],
"timeRegions": [],
"title": "Thread Count",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": false
}
],
"yaxis": {
"align": false
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"links": []
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 6,
"w": 10,
"x": 10,
"y": 17
},
"hiddenSeries": false,
"hideTimeOverride": false,
"id": 27,
"interval": "",
"legend": {
"alignAsTable": true,
"avg": true,
"current": true,
"max": true,
"min": true,
"rightSide": false,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "9.3.1",
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_memory_usedNonHeap_bytes{pod=~\"$pod\",job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "Used Non Heap",
"range": true,
"refId": "A"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "base_memory_committedNonHeap_bytes{pod=~\"$pod\",job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "Commited Non Heap",
"refId": "B"
}
],
"thresholds": [],
"timeRegions": [],
"title": "Non Heap Sizes",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "decbytes",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": true
}
],
"yaxis": {
"align": false
}
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "base_classloader_loadedClasses_count Displays the number of classes that are currently loaded in the JVM.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [
{
"options": {
"match": "null",
"result": {
"text": "N/A"
}
},
"type": "special"
}
],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
},
"unit": "none"
},
"overrides": []
},
"gridPos": {
"h": 2,
"w": 3,
"x": 20,
"y": 17
},
"id": 20,
"links": [],
"maxDataPoints": 100,
"options": {
"colorMode": "none",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"mean"
],
"fields": "",
"values": false
},
"textMode": "auto"
},
"pluginVersion": "9.3.1",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_classloader_loadedClasses_count{pod=~\"$pod\", job=\"$serviceID\"}",
"range": true,
"refId": "A"
}
],
"title": "Currently loaded Classes",
"type": "stat"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "base_classloader_loadedClasses_total_total Displays the total number of classes that have been loaded since the JVM has started execution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [
{
"options": {
"match": "null",
"result": {
"text": "N/A"
}
},
"type": "special"
}
],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
},
"unit": "none"
},
"overrides": []
},
"gridPos": {
"h": 2,
"w": 3,
"x": 20,
"y": 19
},
"id": 23,
"links": [],
"maxDataPoints": 100,
"options": {
"colorMode": "none",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"mean"
],
"fields": "",
"values": false
},
"textMode": "auto"
},
"pluginVersion": "9.3.1",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_classloader_loadedClasses_total{pod=~\"$pod\", job=\"$serviceID\"}",
"range": true,
"refId": "A"
}
],
"title": "Total loaded Classes",
"type": "stat"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "base_classloader_unloadedClasses_total_total Displays the total number of classes unloaded since the JVM has started execution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [
{
"options": {
"match": "null",
"result": {
"text": "N/A"
}
},
"type": "special"
}
],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
},
"unit": "none"
},
"overrides": []
},
"gridPos": {
"h": 2,
"w": 3,
"x": 20,
"y": 21
},
"id": 24,
"links": [],
"maxDataPoints": 100,
"options": {
"colorMode": "none",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"mean"
],
"fields": "",
"values": false
},
"textMode": "auto"
},
"pluginVersion": "9.3.1",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_classloader_unloadedClasses_total{pod=~\"$pod\", job=\"$serviceID\"}",
"range": true,
"refId": "A"
}
],
"title": "Total unloaded Classes",
"type": "stat"
}
],
"refresh": false,
"schemaVersion": 37,
"style": "dark",
"tags": [
"Ansprechperson: Erhard Siegl",
"Applikation: Hogarama",
"Themengebiet: Externe Applikation"
],
"templating": {
"list": [
{
"current": {
"selected": true,
"text": "hogarama",
"value": "hogarama"
},
"definition": "label_values(base_gc_total{namespace=~\"hogarama.*\"}, namespace)",
"hide": 0,
"includeAll": false,
"multi": false,
"name": "namespace",
"options": [],
"query": {
"query": "label_values(base_gc_total{namespace=~\"hogarama.*\"}, namespace)",
"refId": "StandardVariableQuery"
},
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 0,
"type": "query"
},
{
"current": {
"selected": true,
"text": "hogajama-admin",
"value": "hogajama-admin"
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"definition": "label_values(base_gc_total{namespace=\"$namespace\"}, job)",
"hide": 0,
"includeAll": false,
"label": "ServiceID",
"multi": false,
"name": "serviceID",
"options": [],
"query": {
"query": "label_values(base_gc_total{namespace=\"$namespace\"}, job)",
"refId": "StandardVariableQuery"
},
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 1,
"tagValuesQuery": "",
"tagsQuery": "",
"type": "query"
},
{
"allValue": ".+",
"current": {
"selected": true,
"text": [
"All"
],
"value": [
"$__all"
]
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"definition": "label_values(base_gc_total{job=\"$serviceID\"}, pod)",
"hide": 0,
"includeAll": true,
"multi": true,
"name": "pod",
"options": [],
"query": {
"query": "label_values(base_gc_total{job=\"$serviceID\"}, pod)",
"refId": "StandardVariableQuery"
},
"refresh": 2,
"regex": "",
"skipUrlSync": false,
"sort": 0,
"tagValuesQuery": "",
"tagsQuery": "",
"type": "query",
"useTags": false
}
]
},
"time": {
"from": "now-7d",
"to": "now"
},
"timepicker": {
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"time_options": [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
]
},
"timezone": "",
"title": "MicroProfile Java Metrics",
"uid": "java-system-metrics-{{ .Release.Namespace }}",
"version": 2,
"weekStart": ""
}
| 32,028 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
dashboard-java-system-metrics.yml | /FileExtraction/Java_unseen/Gepardec_Hogarama/OCP-Infrastructure/helm/grafana/templates/dashboard-java-system-metrics.yml | apiVersion: grafana.integreatly.org/v1beta1
kind: GrafanaDashboard
metadata:
labels:
app: hogarama
name: java-system-metrics
namespace: {{ .Release.Namespace }}
finalizers: []
spec:
folder: Hogarama
allowCrossNamespaceImport: true
instanceSelector:
matchLabels:
monitoring.gepardec.com/system: "true"
json: |
{
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": {
"type": "datasource",
"uid": "grafana"
},
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"target": {
"limit": 100,
"matchAny": false,
"tags": [],
"type": "dashboard"
},
"type": "dashboard"
}
]
},
"description": "MicroProfile Metrics Endpoint Monitoring",
"editable": true,
"fiscalYearStartMonth": 0,
"gnetId": 12853,
"graphTooltip": 1,
"id": 39,
"links": [],
"liveNow": false,
"panels": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [
{
"options": {
"0": {
"text": "DOWN"
},
"1": {
"text": "UP"
}
},
"type": "value"
}
],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "#d44a3a",
"value": null
},
{
"color": "#37872D",
"value": 1
},
{
"color": "#FADE2A"
}
]
},
"unit": "none"
},
"overrides": []
},
"gridPos": {
"h": 2,
"w": 4,
"x": 0,
"y": 0
},
"id": 29,
"links": [],
"maxDataPoints": 100,
"options": {
"colorMode": "background",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"textMode": "auto"
},
"pluginVersion": "9.3.1",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"exemplar": false,
"expr": "up{job=\"$serviceID\", pod=~\"$pod\"}",
"instant": true,
"range": false,
"refId": "A"
}
],
"title": "Status",
"type": "stat"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": " base_jvm_uptime_seconds Displays the uptime of the JVM in milliseconds.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [
{
"options": {
"match": "null",
"result": {
"text": "N/A"
}
},
"type": "special"
}
],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
},
"unit": "s"
},
"overrides": []
},
"gridPos": {
"h": 2,
"w": 3,
"x": 4,
"y": 0
},
"id": 26,
"links": [],
"maxDataPoints": 100,
"options": {
"colorMode": "none",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"textMode": "auto"
},
"pluginVersion": "9.3.1",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_jvm_uptime_seconds{pod=~\"$pod\", job=\"$serviceID\"}",
"legendFormat": " ",
"range": true,
"refId": "A"
}
],
"title": "Uptime",
"type": "stat"
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "base_gc_total_total Displays the total number of collections that have occurred. This attribute lists -1 if the collection count is undefined for this collector.",
"fieldConfig": {
"defaults": {
"links": []
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 8,
"x": 7,
"y": 0
},
"hiddenSeries": false,
"id": 14,
"legend": {
"alignAsTable": true,
"avg": true,
"current": true,
"max": true,
"min": true,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "9.3.1",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "builder",
"expr": "rate(base_gc_total{job=~\"$serviceID\", pod=~\"$pod\"}[5m])",
"intervalFactor": 2,
"legendFormat": {{`"{{ name }}"`}},
"range": true,
"refId": "A"
}
],
"thresholds": [],
"timeRegions": [],
"title": "GC Copy & Mark Sweep Total",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": true
}
],
"yaxis": {
"align": false
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "base_gc_time_total Displays the approximate accumulated collection elapsed time in milliseconds. This attribute displays -1 if the collection elapsed time is undefined for this collector. The JVM implementation may use a high resolution timer to measure the elapsed time. This attribute may display the same value even if the collection count has been incremented if the collection elapsed time is very short.",
"fieldConfig": {
"defaults": {
"links": []
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 8,
"x": 15,
"y": 0
},
"hiddenSeries": false,
"id": 12,
"legend": {
"alignAsTable": true,
"avg": true,
"current": true,
"max": true,
"min": true,
"rightSide": false,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "9.3.1",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "rate(base_gc_time_total_seconds{pod=~\"$pod\", job=\"$serviceID\"}[5m])",
"legendFormat": {{`"{{ name }}"`}},
"range": true,
"refId": "A"
}
],
"thresholds": [],
"timeRegions": [],
"title": "GC Copy & Mark Sweep Time",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "ms",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": false
}
],
"yaxis": {
"align": false
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "",
"fieldConfig": {
"defaults": {
"links": []
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 6,
"w": 7,
"x": 0,
"y": 2
},
"hiddenSeries": false,
"id": 8,
"legend": {
"alignAsTable": true,
"avg": true,
"current": true,
"max": true,
"min": true,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "9.3.1",
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_cpu_systemLoadAverage{pod=~\"$pod\",job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "CPU load",
"range": true,
"refId": "A"
}
],
"thresholds": [],
"timeRegions": [],
"title": "CPU Load",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "percentunit",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": false
}
],
"yaxis": {
"align": false
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"links": []
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 9,
"w": 23,
"x": 0,
"y": 8
},
"hiddenSeries": false,
"hideTimeOverride": false,
"id": 10,
"interval": "",
"legend": {
"alignAsTable": true,
"avg": true,
"current": true,
"max": true,
"min": true,
"rightSide": false,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "9.3.1",
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_memory_usedHeap_bytes{pod=~\"$pod\",job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "Used Heap",
"range": true,
"refId": "A"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "base_memory_committedHeap_bytes{pod=~\"$pod\", job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "Commited Heap",
"refId": "C"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "base_memory_maxHeap_bytes{pod=~\"$pod\", job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "Max Heap",
"refId": "B"
}
],
"thresholds": [],
"timeRegions": [],
"title": "Heap Sizes",
"tooltip": {
"shared": true,
"sort": 2,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "decbytes",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": false
}
],
"yaxis": {
"align": false
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"links": []
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 6,
"w": 10,
"x": 0,
"y": 17
},
"hiddenSeries": false,
"id": 2,
"legend": {
"alignAsTable": true,
"avg": true,
"current": true,
"max": true,
"min": true,
"rightSide": false,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "9.3.1",
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_thread_count{pod=~\"$pod\",job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "Thread Count",
"range": true,
"refId": "A"
}
],
"thresholds": [],
"timeRegions": [],
"title": "Thread Count",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": false
}
],
"yaxis": {
"align": false
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"links": []
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 6,
"w": 10,
"x": 10,
"y": 17
},
"hiddenSeries": false,
"hideTimeOverride": false,
"id": 27,
"interval": "",
"legend": {
"alignAsTable": true,
"avg": true,
"current": true,
"max": true,
"min": true,
"rightSide": false,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "9.3.1",
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_memory_usedNonHeap_bytes{pod=~\"$pod\",job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "Used Non Heap",
"range": true,
"refId": "A"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "base_memory_committedNonHeap_bytes{pod=~\"$pod\",job=\"$serviceID\"}",
"intervalFactor": 2,
"legendFormat": "Commited Non Heap",
"refId": "B"
}
],
"thresholds": [],
"timeRegions": [],
"title": "Non Heap Sizes",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "decbytes",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": true
}
],
"yaxis": {
"align": false
}
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "base_classloader_loadedClasses_count Displays the number of classes that are currently loaded in the JVM.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [
{
"options": {
"match": "null",
"result": {
"text": "N/A"
}
},
"type": "special"
}
],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
},
"unit": "none"
},
"overrides": []
},
"gridPos": {
"h": 2,
"w": 3,
"x": 20,
"y": 17
},
"id": 20,
"links": [],
"maxDataPoints": 100,
"options": {
"colorMode": "none",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"mean"
],
"fields": "",
"values": false
},
"textMode": "auto"
},
"pluginVersion": "9.3.1",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_classloader_loadedClasses_count{pod=~\"$pod\", job=\"$serviceID\"}",
"range": true,
"refId": "A"
}
],
"title": "Currently loaded Classes",
"type": "stat"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "base_classloader_loadedClasses_total_total Displays the total number of classes that have been loaded since the JVM has started execution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [
{
"options": {
"match": "null",
"result": {
"text": "N/A"
}
},
"type": "special"
}
],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
},
"unit": "none"
},
"overrides": []
},
"gridPos": {
"h": 2,
"w": 3,
"x": 20,
"y": 19
},
"id": 23,
"links": [],
"maxDataPoints": 100,
"options": {
"colorMode": "none",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"mean"
],
"fields": "",
"values": false
},
"textMode": "auto"
},
"pluginVersion": "9.3.1",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_classloader_loadedClasses_total{pod=~\"$pod\", job=\"$serviceID\"}",
"range": true,
"refId": "A"
}
],
"title": "Total loaded Classes",
"type": "stat"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "base_classloader_unloadedClasses_total_total Displays the total number of classes unloaded since the JVM has started execution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [
{
"options": {
"match": "null",
"result": {
"text": "N/A"
}
},
"type": "special"
}
],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
},
"unit": "none"
},
"overrides": []
},
"gridPos": {
"h": 2,
"w": 3,
"x": 20,
"y": 21
},
"id": 24,
"links": [],
"maxDataPoints": 100,
"options": {
"colorMode": "none",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"mean"
],
"fields": "",
"values": false
},
"textMode": "auto"
},
"pluginVersion": "9.3.1",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"editorMode": "code",
"expr": "base_classloader_unloadedClasses_total{pod=~\"$pod\", job=\"$serviceID\"}",
"range": true,
"refId": "A"
}
],
"title": "Total unloaded Classes",
"type": "stat"
}
],
"refresh": false,
"schemaVersion": 37,
"style": "dark",
"tags": [
"Ansprechperson: Erhard Siegl",
"Applikation: Hogarama",
"Themengebiet: Externe Applikation"
],
"templating": {
"list": [
{
"current": {
"selected": true,
"text": "hogarama",
"value": "hogarama"
},
"definition": "label_values(base_gc_total{namespace=~\"hogarama.*\"}, namespace)",
"hide": 0,
"includeAll": false,
"multi": false,
"name": "namespace",
"options": [],
"query": {
"query": "label_values(base_gc_total{namespace=~\"hogarama.*\"}, namespace)",
"refId": "StandardVariableQuery"
},
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 0,
"type": "query"
},
{
"current": {
"selected": true,
"text": "hogajama-admin",
"value": "hogajama-admin"
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"definition": "label_values(base_gc_total{namespace=\"$namespace\"}, job)",
"hide": 0,
"includeAll": false,
"label": "ServiceID",
"multi": false,
"name": "serviceID",
"options": [],
"query": {
"query": "label_values(base_gc_total{namespace=\"$namespace\"}, job)",
"refId": "StandardVariableQuery"
},
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 1,
"tagValuesQuery": "",
"tagsQuery": "",
"type": "query"
},
{
"allValue": ".+",
"current": {
"selected": true,
"text": [
"All"
],
"value": [
"$__all"
]
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"definition": "label_values(base_gc_total{job=\"$serviceID\"}, pod)",
"hide": 0,
"includeAll": true,
"multi": true,
"name": "pod",
"options": [],
"query": {
"query": "label_values(base_gc_total{job=\"$serviceID\"}, pod)",
"refId": "StandardVariableQuery"
},
"refresh": 2,
"regex": "",
"skipUrlSync": false,
"sort": 0,
"tagValuesQuery": "",
"tagsQuery": "",
"type": "query",
"useTags": false
}
]
},
"time": {
"from": "now-7d",
"to": "now"
},
"timepicker": {
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"time_options": [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
]
},
"timezone": "",
"title": "MicroProfile Java Metrics",
"uid": "java-system-metrics-{{ .Release.Namespace }}",
"weekStart": ""
}
| 32,123 | Java | .java | Gepardec/Hogarama | 16 | 8 | 9 | 2016-09-11T08:42:43Z | 2024-05-01T15:08:12Z |
Display.java | /FileExtraction/Java_unseen/TarballCoLtd_iOS-Restrictions-Recovery/src/com/alyxferrari/iosrr/Display.java | package com.alyxferrari.iosrr;
import javax.swing.*;
import java.net.*;
import java.awt.event.*;
import java.io.*;
import net.schmizz.sshj.*;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.transport.verification.*;
import net.schmizz.sshj.connection.channel.direct.*;
import org.apache.commons.io.*;
public class Display {
private Display() {}
private static final Display CLASS_OBJ = new Display();
private static JFrame FRAME = new JFrame(RRConst.FULL_NAME);
private static JLabel AUTHOR = new JLabel("by " + RRConst.AUTHOR);
private static JLabel TITLE = new JLabel(RRConst.TITLE);
private static JLabel DESC = new JLabel(RRConst.DESC);
private static JButton KEY_SALT_BUTTON = new JButton(RRConst.KEY_SALT_BUTTON);
private static JButton FILE_BUTTON = new JButton(RRConst.FILE_BUTTON);
private static JButton SSH_BUTTON = new JButton(RRConst.SSH_BUTTON);
private static JButton IPROXY_BUTTON = new JButton(RRConst.IPROXY_BUTTON);
private static JButton ITUNES_BACKUP = new JButton(RRConst.ITUNES_BACKUP);
private static JButton KEYCHAIN_DUMPER = new JButton(RRConst.KEYCHAIN_DUMPER);
private static JButton ABOUT = new JButton(RRConst.ABOUT);
private static JLabel iOS_13 = new JLabel(RRConst.iOS_13);
private static JLabel iOS_11 = new JLabel(RRConst.iOS_11);
private static InfoPlist[] plists = null;
private static boolean initialized = false;
public static void createDisplay() {
if (!initialized) {
Display.FRAME.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Display.FRAME.setSize(550, 400);
Display.FRAME.getContentPane().setLayout(new BoxLayout(FRAME.getContentPane(), BoxLayout.Y_AXIS));
Display.KEY_SALT_BUTTON.addActionListener(Display.CLASS_OBJ.new KeySaltButtonListener());
Display.FILE_BUTTON.addActionListener(Display.CLASS_OBJ.new FileButtonListener());
Display.SSH_BUTTON.addActionListener(Display.CLASS_OBJ.new SSHButtonListener());
Display.KEYCHAIN_DUMPER.addActionListener(Display.CLASS_OBJ.new KeychainDumperListener());
Display.IPROXY_BUTTON.addActionListener(Display.CLASS_OBJ.new IproxyButtonListener());
Display.IPROXY_BUTTON.setEnabled(false);
Display.ITUNES_BACKUP.addActionListener(Display.CLASS_OBJ.new ItunesBackupListener());
Display.ABOUT.addActionListener(Display.CLASS_OBJ.new AboutListener());
initialized = true;
}
Display.FRAME.getContentPane().add(Display.TITLE);
Display.FRAME.getContentPane().add(Display.AUTHOR);
Display.FRAME.getContentPane().add(Display.DESC);
Display.FRAME.getContentPane().add(Display.ABOUT);
Display.FRAME.getContentPane().add(Display.iOS_11);
Display.FRAME.getContentPane().add(Display.KEY_SALT_BUTTON);
Display.FRAME.getContentPane().add(Display.FILE_BUTTON);
Display.FRAME.getContentPane().add(Display.SSH_BUTTON);
Display.FRAME.getContentPane().add(Display.ITUNES_BACKUP);
Display.FRAME.getContentPane().add(Display.iOS_13);
Display.FRAME.getContentPane().add(Display.KEYCHAIN_DUMPER);
Display.FRAME.setVisible(true);
}
public class AboutListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
Display.FRAME.getContentPane().removeAll();
JLabel title = new JLabel(RRConst.FULL_NAME);
JLabel author = new JLabel("by " + RRConst.AUTHOR);
JLabel slf4j = new JLabel("<html><body><br/>slf4j Copyright (c) 2004-2017 QOS.ch</body></html>");
JLabel bcJava = new JLabel("bc-java Copyright (c) 2000-2019 The Legion of the Bouncy Castle Inc.");
JLabel sshj = new JLabel("sshj Copyright (c) 2010-2012 sshj contributors");
JLabel keychainDumper = new JLabel("keychain_dumper was written by ptoomey3 on GitHub");
JLabel backup = new JLabel("The iTunes backup idea was given to me by Reddit users u/Starwarsfan2099 and u/KuroAMK");
JLabel help = new JLabel("<html><body><br/>Testers:<br/>Jacob Ward (u/jacobward328)</body></html>");
JLabel paypal = new JLabel("<html><body><br/>Special thanks to my PayPal backers:<br/>Jacob Ward<br/>paypal.me/alyxferrari</body></html>");
OperatingSystemType ops = RestrictionsRecovery.identifyHostOS();
JLabel os = new JLabel();
String version = System.getProperty("os.version");
if (ops == OperatingSystemType.WINDOWS) {
os = new JLabel("<html><body><br/>Host OS: Windows " + version);
} else if (ops == OperatingSystemType.MACOSMOJAVE_OR_OLDER || ops == OperatingSystemType.MACOSCATALINA_OR_NEWER) {
os = new JLabel("<html><body><br/>Host OS: macOS " + version);
} else if (ops == OperatingSystemType.UNIX_BASED) {
os = new JLabel("<html><body><br/>Host OS: " + System.getProperty("os.name") + " " + version);
} else {
os = new JLabel("<html><body><br/>Host OS: Unknown");
}
JButton back = new JButton("Back");
back.addActionListener(new BackListener());
Display.FRAME.getContentPane().add(title);
Display.FRAME.getContentPane().add(author);
Display.FRAME.getContentPane().add(slf4j);
Display.FRAME.getContentPane().add(bcJava);
Display.FRAME.getContentPane().add(sshj);
Display.FRAME.getContentPane().add(keychainDumper);
Display.FRAME.getContentPane().add(backup);
Display.FRAME.getContentPane().add(help);
Display.FRAME.getContentPane().add(paypal);
Display.FRAME.getContentPane().add(os);
Display.FRAME.getContentPane().add(back);
Display.refresh();
}
}
public class KeychainDumperListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
new Thread() {
@Override
public void run() {
Display.FRAME.getContentPane().removeAll();
String keychain = null;
try {
JOptionPane.showMessageDialog(null, "Make sure your device meets the following conditions before proceeding:\nYour device must be jailbroken\nYour device must have an SSH server running\nYour device must have the \"SQLite 3.x\" package installed from Sam Bingner's repo\nYour device is highly recommended to have a passcode (it may work without, but having one fixes a lot of issues)\nMake sure your device is unlocked and on the home screen throughout the whole process");
String ip = JOptionPane.showInputDialog("Device IP address?");
String portStr = JOptionPane.showInputDialog("Device SSH server port? (press enter to default to 22)");
int port = 22;
if (!portStr.equals("")) {
port = Integer.parseInt(portStr);
}
String rootPass = JOptionPane.showInputDialog("What is your device's root password? (press enter to default to 'alpine')");
if (rootPass.equals("")) {
rootPass = "alpine";
}
File keychain_dumper = new File("keychain_dumper");
URL keychain_dumperURL = new URL("https://alyxferrari.github.io/iosrr/keychain_dumper");
File updateEntitlements = new File("updateEntitlements.sh");
URL updateEntitlementsURL = new URL("https://raw.githubusercontent.com/ptoomey3/Keychain-Dumper/master/updateEntitlements.sh");
File entitlements = new File("entitlements.xml");
URL entitlementsURL = new URL("https://raw.githubusercontent.com/ptoomey3/Keychain-Dumper/master/entitlements.xml");
if (!keychain_dumper.exists()) {
Display.FRAME.getContentPane().add(new JLabel("Couldn't find keychain_dumper!"));
Display.FRAME.getContentPane().add(new JLabel("Downloading keychain_dumper from alyxferrari.github.io..."));
System.out.println("Couldn't find keychain_dumper!");
System.out.println("Downloading keychain_dumper from alyxferrari.github.io...");
Display.refresh();
FileUtils.copyURLToFile(keychain_dumperURL, keychain_dumper);
}
if (!updateEntitlements.exists()) {
Display.FRAME.getContentPane().add(new JLabel("Couldn't find updateEntitlements.sh!"));
Display.FRAME.getContentPane().add(new JLabel("Downloading updateEntitlements.sh from Keychain-Dumper's GitHub repo..."));
System.out.println("Couldn't find updateEntitlements.sh!");
System.out.println("Downloading updateEntitlements.sh from Keychain-Dumper's GitHub repo...");
Display.refresh();
FileUtils.copyURLToFile(updateEntitlementsURL, updateEntitlements);
}
if (!entitlements.exists()) {
Display.FRAME.getContentPane().add(new JLabel("Couldn't find entitlements.xml!"));
Display.FRAME.getContentPane().add(new JLabel("Downloading entitlements.xml from Keychain-Dumper's GitHub repo..."));
System.out.println("Couldn't find entitlements.xml!");
System.out.println("Downloading entitlements.xml from Keychain-Dumper's GitHub repo...");
Display.refresh();
FileUtils.copyURLToFile(entitlementsURL, entitlements);
}
Display.FRAME.getContentPane().add(new JLabel("Connecting to " + ip + ":" + port + " over SSH..."));
Display.refresh();
System.out.println("Connecting to " + ip + ":" + port + " over SSH...");
SSHClient ssh = new SSHClient();
ssh.addHostKeyVerifier(new PromiscuousVerifier());
ssh.connect(ip, port);
Display.FRAME.getContentPane().add(new JLabel("Logging in as user 'root'..."));
System.out.println("Logging in as user 'root'...");
Display.refresh();
ssh.authPassword("root", rootPass);
Display.FRAME.getContentPane().add(new JLabel("Uploading keychain_dumper to device..."));
Display.refresh();
System.out.println("Uploading keychain_dumper to device...");
ssh.newSCPFileTransfer().upload("keychain_dumper", "/User/Documents/keychain_dumper");
Display.FRAME.getContentPane().add(new JLabel("Uploading updateEntitlements.sh to device..."));
Display.refresh();
System.out.println("Uploading updateEntitlements.sh to device...");
ssh.newSCPFileTransfer().upload("updateEntitlements.sh", "/User/Documents/updateEntitlements.sh");
Display.FRAME.getContentPane().add(new JLabel("Uploading entitlements.xml to device..."));
Display.refresh();
System.out.println("Uploading entitlements.xml to device...");
ssh.newSCPFileTransfer().upload("entitlements.xml", "/User/Documents/entitlements.xml");
Session session = ssh.startSession();
Display.FRAME.getContentPane().add(new JLabel("Giving keychain_dumper '+x' permissions..."));
System.out.println("Giving keychain_dumper '+x' permissions...");
Display.refresh();
session.exec("chmod +x /User/Documents/keychain_dumper");
session = ssh.startSession();
Display.FRAME.getContentPane().add(new JLabel("Giving updateEntitlements.sh '+x' permissions..."));
Display.refresh();
System.out.println("Giving updateEntitlements.sh '+x' permissions...");
session.exec("chmod +x /User/Documents/updateEntitlements.sh");
session = ssh.startSession();
Display.FRAME.getContentPane().add(new JLabel("Running updateEntitlements.sh..."));
Display.refresh();
System.out.println("Running updateEntitlements.sh...");
session.exec("./../mobile/Documents/updateEntitlements.sh");
session = ssh.startSession();
Display.FRAME.getContentPane().add(new JLabel("Assigning entitlements to keychain_dumper..."));
Display.refresh();
System.out.println("Assigning entitlements to keychain_dumper...");
session.exec("ldid -S/User/Documents/entitlements.xml /User/Documents/keychain_dumper");
Display.FRAME.getContentPane().add(new JLabel("Disconnecting..."));
System.out.println("Disconnecting...");
Display.refresh();
ssh.disconnect();
ssh.close();
SSHClient ssh2 = new SSHClient();
ssh2.addHostKeyVerifier(new PromiscuousVerifier());
Display.FRAME.getContentPane().add(new JLabel("Reconnecting to " + ip + ":" + port + "..."));
System.out.println("Reconnecting to " + ip + ":" + port + "...");
Display.refresh();
ssh2.connect(ip, port);
Display.FRAME.getContentPane().add(new JLabel("Logging in as user 'root'..."));
System.out.println("Logging in as user 'root'...");
Display.refresh();
ssh2.authPassword("root", rootPass);
Session session2 = ssh2.startSession();
JOptionPane.showMessageDialog(null, "Please make sure your device is unlocked and on the home screen.");
Display.FRAME.getContentPane().add(new JLabel("Dumping your device's Keychain... (authenticate with Touch ID/Face ID if asked)"));
System.out.println("Dumping your device's Keychain... (if this blocks, make sure your device is unlocked)");
Display.refresh();
Session.Command cmd = session2.exec("./../mobile/Documents/keychain_dumper");
keychain = IOUtils.readFully(cmd.getInputStream()).toString();
session2 = ssh2.startSession();
Display.FRAME.getContentPane().add(new JLabel("Removing keychain_dumper from device..."));
System.out.println("Removing keychain_dumper from device...");
Display.refresh();
session2.exec("rm /User/Documents/keychain_dumper");
session2 = ssh2.startSession();
Display.FRAME.getContentPane().add(new JLabel("Removing updateEntitlements.sh from device..."));
System.out.println("Removing updateEntitlements.sh from device...");
Display.refresh();
session2.exec("rm /User/Documents/updateEntitlements.sh");
session2 = ssh2.startSession();
Display.FRAME.getContentPane().add(new JLabel("Removing entitlements.xml from device..."));
System.out.println("Removing entitlements.xml from device...");
Display.refresh();
session2.exec("rm /User/Documents/entitlements.xml");
Display.FRAME.getContentPane().add(new JLabel("Disconnecting..."));
System.out.println("Disconnecting...");
Display.refresh();
ssh2.disconnect();
ssh2.close();
Display.FRAME.getContentPane().add(new JLabel("Parsing Keychain dump..."));
System.out.println("Parsing Keychain dump...");
Display.refresh();
String[] list = keychain.split("ParentalControls")[1].split("\n");
String password = null;
for (int i = 0; i < (list.length > 1000 ? 1000 : list.length); i++) {
if (list[i].contains("Keychain Data: ")) {
password = list[i].split("Keychain Data: ")[1];
break;
}
}
Display.FRAME.getContentPane().add(new JLabel("Found Screen Time passcode! Passcode: " + password));
System.out.println("Found Screen Time passcode! Passcode: " + password);
Display.refresh();
JButton keychainOutput = new JButton("View Keychain dump");
keychainOutput.addActionListener(new KeychainOutputListener(keychain));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(keychainOutput);
JButton button = new JButton("Back");
button.addActionListener(new BackListener());
panel.add(button);
Display.FRAME.getContentPane().add(panel);
Display.refresh();
JOptionPane.showMessageDialog(null, "Found Screen Time passcode! Passcode: " + password);
} catch (Exception ex) {
Display.FRAME.getContentPane().removeAll();
Display.FRAME.getContentPane().add(new JLabel("Failed to retrieve Screen Time passcode!"));
Display.FRAME.getContentPane().add(new JLabel("If you're sure you've done everything correctly, create an issue on GitHub."));
Display.FRAME.getContentPane().add(new JLabel(ex.getClass().toString().split(" ")[1]+ ": " + ex.getMessage()));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
JButton button = new JButton("Back");
button.addActionListener(new BackListener());
if (!(keychain == null)) {
JButton keychainView = new JButton("View failed Keychain dump");
keychainView.addActionListener(new KeychainOutputListener(keychain));
panel.add(keychainView);
}
panel.add(button);
Display.FRAME.getContentPane().add(panel);
Display.refresh();
Display.handleException(ex, true);
}
}
}.start();
}
}
public class KeychainOutputListener implements ActionListener {
private String dump;
public KeychainOutputListener(String dump) {
this.dump = dump;
}
public void actionPerformed(ActionEvent ev) {
Display.FRAME.getContentPane().removeAll();
dump = "<html><body>" + dump + "</body></html>";
String[] dumpArr = dump.split("\n");
dump = "";
for (int i = 0; i < dumpArr.length; i++) {
dump += dumpArr[i] + "<br/>";
}
Display.FRAME.getContentPane().add(new JLabel("<html><body>Keychain dump:<br/></body></html>"));
Display.FRAME.getContentPane().add(new JLabel(dump));
JButton back = new JButton("Back to main menu");
back.addActionListener(new BackListener());
Display.FRAME.getContentPane().add(back);
Display.refresh();
}
}
public class ItunesBackupListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
try {
OperatingSystemType currentOS = RestrictionsRecovery.identifyHostOS();
String backupPath = System.getProperty("user.home") + "\\";
if (currentOS == OperatingSystemType.WINDOWS) {
String y = "n";
File uwpiTunes = new File(backupPath + "AppData\\Local\\Microsoft\\WindowsApps\\AppleInc.iTunes_nzyj5cx40ttqa");
if (uwpiTunes.exists()) {
y = "y";
}
if (y.equalsIgnoreCase("y") || y.equalsIgnoreCase("yes")) {
backupPath += "Apple\\MobileSync\\Backup\\";
} else {
backupPath += "AppData\\Roaming\\Apple Computer\\MobileSync\\Backup\\";
}
} else if (currentOS == OperatingSystemType.MACOSMOJAVE_OR_OLDER || currentOS == OperatingSystemType.MACOSCATALINA_OR_NEWER) {
throw new Exception("macOS is not currently supported. Support will come in a future update.");
} else {
throw new Exception("Your OS is not supported because it is not possible to install iTunes on your OS.");
}
File backupLocation = new File(backupPath);
String[] backups = backupLocation.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
Display.FRAME.getContentPane().removeAll();
Display.FRAME.getContentPane().add(new JLabel(RRConst.ITUNES_BACKUPS));
plists = new InfoPlist[backups.length];
for (int i = 0; i < backups.length; i++) {
InfoPlist plist = InfoPlist.getInstance(backupPath + backups[i] + "\\");
plists[i] = plist;
if (plist != null) {
JButton button = new JButton(plist.getModelName() + " / " + plist.getiOSVersion() + " / " + plist.getBackupDate() + " / " + plist.getDisplayName() + " / " + plist.getDeviceName());
if (plist.getiOSRelease() < 7 || plist.getiOSRelease() > 11) {
button.setEnabled(false);
} else if (!new File(plist.getFile() + "398bc9c2aeeab4cb0c12ada0f52eea12cf14f40b").exists()) {
button.setEnabled(false);
}
button.addActionListener(Display.CLASS_OBJ.new BackupListener(i));
Display.FRAME.getContentPane().add(button);
}
}
JButton back = new JButton("Back");
back.addActionListener(new BackListener());
Display.FRAME.getContentPane().add(back);
Display.refresh();
} catch (Exception ex) {
if (ex.getClass().toString().split(" ")[1].equals("java.lang.IndexOutOfBoundsException")) {
Display.handleException(new Exception("Screen Time passcode could not be found in dump. Create an issue on GitHub that includes a summary of what you see in your Keychain dump if you're sure you've done everything correctly."), true);
Display.handleException(new Exception(""), true);
}
Display.handleException(ex, true);
}
}
}
public class BackupListener implements ActionListener {
private int index;
public BackupListener(int index) {
this.index = index;
}
public void actionPerformed(ActionEvent ev) {
try {
KeySaltPair pair = PropertyListReader.getKeyAndSaltFromPlist(plists[index].getFile() + "398bc9c2aeeab4cb0c12ada0f52eea12cf14f40b");
JLabel label = new JLabel("<html><body><strong>Calculating passcode...</strong></body></html>");
Display.FRAME.getContentPane().add(label);
Display.refresh();
Thread thread = new Thread() {
@Override
public void run() {
try {
String passcode = RestrictionsRecovery.calculate(pair.getKey(), pair.getSalt(), false);
if (passcode == null) {
throw new Exception("Passcode could not be found. Key and salt does not correspond to any passcode between 0000 and 9999.");
} else {
JOptionPane.showMessageDialog(null, "Passcode: " + passcode, "Passcode found!", 1);
}
Display.FRAME.getContentPane().remove(label);
Display.refresh();
} catch (Exception ex) {
Display.handleException(ex, true);
}
}
};
thread.start();
} catch (Exception ex) {
Display.handleException(ex, true);
}
}
}
public static void refresh() {
Display.FRAME.revalidate();
Display.FRAME.repaint();
}
public static void refreshThread() {
new Thread() {
@Override
public void run() {
Display.refresh();
}
}.start();
}
public static class BackListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
Display.FRAME.getContentPane().removeAll();
Display.createDisplay();
Display.refresh();
}
}
public class KeySaltButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
try {
String key = JOptionPane.showInputDialog("Key?");
String salt = JOptionPane.showInputDialog("Salt?");
Display.DESC.setText("<html><b>Calculating passcode...</b></html>");
Display.refresh();
Thread thread = new Thread() {
@Override
public void run() {
try {
String passcode = RestrictionsRecovery.calculate(key, salt, false);
if (passcode == null) {
throw new Exception("Passcode could not be found. Key and salt does not correspond to any passcode between 0000 and 9999.");
} else {
JOptionPane.showMessageDialog(null, "Passcode: " + passcode, "Passcode found!", 1);
}
} catch (Exception ex) {
Display.handleException(ex, true);
}
}
};
thread.start();
} catch (Exception ex) {
Display.handleException(ex, true);
}
Display.DESC.setText(RRConst.DESC);
Display.refresh();
}
}
public class FileButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
try {
String file = JOptionPane.showInputDialog("Property list path? (Do not include quotes)");
KeySaltPair pair = PropertyListReader.getKeyAndSaltFromPlist(file);
Display.DESC.setText("<html><b>Calculating passcode...</b></html>");
Display.refresh();
Thread thread = new Thread() {
@Override
public void run() {
try {
String passcode = RestrictionsRecovery.calculate(pair.getKey(), pair.getSalt(), false);
if (passcode == null) {
throw new Exception("Passcode could not be found. Key and salt does not correspond to any passcode between 0000 and 9999.");
} else {
JOptionPane.showMessageDialog(null, "Passcode: " + passcode, "Passcode found!", 1);
}
} catch (Exception ex) {
Display.handleException(ex, true);
}
}
};
thread.start();
} catch (Exception ex) {
Display.handleException(ex, true);
}
Display.DESC.setText(RRConst.DESC);
Display.refresh();
}
}
public class SSHButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
try {
String ip = JOptionPane.showInputDialog("Device IP address?");
String password = JOptionPane.showInputDialog("Device root password?");
String port = JOptionPane.showInputDialog("Device SSH port?");
Display.DESC.setText("<html><b>Calculating passcode...</b></html>");
Display.refresh();
Thread thread = new Thread() {
@Override
public void run() {
try {
Display.DESC.setText("Downloading passcode from device...");
RestrictionsRecovery.downloadViaSSH(ip, Integer.parseInt(port), password, false);
Display.DESC.setText("Bruteforcing passcode...");
KeySaltPair pair = PropertyListReader.getKeyAndSaltFromPlist("password.plist");
String passcode = RestrictionsRecovery.calculate(pair.getKey(), pair.getSalt(), false);
if (passcode == null) {
throw new Exception("Passcode could not be found. Specified key and salt do not correspond to any passcode between 0000 and 9999.");
} else {
JOptionPane.showMessageDialog(null, "Passcode: " + passcode, "Passcode found!", 1);
}
} catch (Exception ex) {
Display.handleException(ex, true);
}
}
};
thread.start();
} catch (Exception ex) {
Display.handleException(ex, true);
}
Display.DESC.setText(RRConst.DESC);
Display.refresh();
}
}
public class IproxyButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
// not implemented yet
}
}
private static void handleException(Exception ex, boolean message) {
ex.printStackTrace();
if (message) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getClass().toString().split(" ")[1] + ": " + ex.getMessage(), "An exception has occurred", 0);
}
}
} | 25,230 | Java | .java | TarballCoLtd/iOS-Restrictions-Recovery | 53 | 10 | 6 | 2020-02-19T04:41:52Z | 2022-12-07T01:18:36Z |
PasscodeChecker.java | /FileExtraction/Java_unseen/TarballCoLtd_iOS-Restrictions-Recovery/src/com/alyxferrari/iosrr/PasscodeChecker.java | package com.alyxferrari.iosrr;
import java.util.*;
import javax.crypto.spec.*;
import javax.crypto.*;
import java.security.*;
import java.security.spec.*;
import java.io.*;
public class PasscodeChecker {
private PasscodeChecker() {}
public static String calculateHash(String passcode, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
char[] passwordChar = passcode.toCharArray();
byte[] saltByte = Base64.getDecoder().decode(salt.getBytes("UTF-8"));
PBEKeySpec spec = new PBEKeySpec(passwordChar, saltByte, 1000, 160);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] result = factory.generateSecret(spec).getEncoded();
return new String(new String(Base64.getEncoder().encode(result)));
}
public static String getPasscode(String key, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
for (int i = 0; i < 10000; i++) {
String passcode = "" + i;
int length = Integer.toString(i).length();
if (length == 1) {
passcode = "000" + i;
} else if (length == 2) {
passcode = "00" + i;
} else if (length == 3) {
passcode = "0" + i;
}
String result = PasscodeChecker.calculateHash(passcode, salt);
if (result.contentEquals(key)) {
return passcode;
}
}
return "";
}
} | 1,362 | Java | .java | TarballCoLtd/iOS-Restrictions-Recovery | 53 | 10 | 6 | 2020-02-19T04:41:52Z | 2022-12-07T01:18:36Z |
RRArguments.java | /FileExtraction/Java_unseen/TarballCoLtd_iOS-Restrictions-Recovery/src/com/alyxferrari/iosrr/RRArguments.java | package com.alyxferrari.iosrr;
public class RRArguments {
private final RequestType type;
private boolean iproxy;
private String ssh;
String password;
String port;
String file;
String key;
String salt;
boolean version;
public RRArguments(boolean iproxy, String ssh, String password, String port, String file, String key, String salt, boolean version) {
this.iproxy = false;
this.ssh = null;
this.password = null;
this.port = null;
this.file = null;
this.key = null;
this.salt = null;
this.version = false;
if (iproxy && ssh == null && file == null && key == null && salt == null && !version) {
this.iproxy = true;
if (password != null) {
this.password = password;
}
if (port != null) {
this.port = port;
}
type = RequestType.IPROXY;
} else if (!iproxy && ssh != null && file == null && key == null && salt == null && !version) {
this.ssh = ssh;
if (password != null) {
this.password = password;
}
if (port != null) {
this.port = port;
}
type = RequestType.SSH;
} else if (!iproxy && ssh == null && file != null && key == null && salt == null && !version) {
this.file = file;
type = RequestType.FILE;
} else if (!iproxy && ssh == null && file == null && key != null && salt != null && !version) {
this.key = key;
this.salt = salt;
type = RequestType.KEYSALT;
} else if (!iproxy && ssh == null && file == null && key == null && salt == null && version) {
type = RequestType.VERSION;
} else {
type = RequestType.NONSENSICAL;
}
}
public RequestType getRequestType() {
return type;
}
public boolean getIproxy() {
return iproxy;
}
public String getSsh() {
return ssh;
}
public String getPassword() {
return password;
}
public String getPort() {
return port;
}
public String getFile() {
return file;
}
public String getKey() {
return key;
}
public String getSalt() {
return salt;
}
public boolean getVersion() {
return version;
}
} | 1,974 | Java | .java | TarballCoLtd/iOS-Restrictions-Recovery | 53 | 10 | 6 | 2020-02-19T04:41:52Z | 2022-12-07T01:18:36Z |
OperatingSystemType.java | /FileExtraction/Java_unseen/TarballCoLtd_iOS-Restrictions-Recovery/src/com/alyxferrari/iosrr/OperatingSystemType.java | package com.alyxferrari.iosrr;
public enum OperatingSystemType {
WINDOWS, MACOSMOJAVE_OR_OLDER, MACOSCATALINA_OR_NEWER, UNIX_BASED, OTHER;
} | 141 | Java | .java | TarballCoLtd/iOS-Restrictions-Recovery | 53 | 10 | 6 | 2020-02-19T04:41:52Z | 2022-12-07T01:18:36Z |
RRConst.java | /FileExtraction/Java_unseen/TarballCoLtd_iOS-Restrictions-Recovery/src/com/alyxferrari/iosrr/RRConst.java | package com.alyxferrari.iosrr;
public class RRConst {
private RRConst() {}
public static final String NAME = "iOS-Restrictions-Recovery";
public static final String VERSION = "v1.0 beta 4";
public static final String AUTHOR = "Alyx Ferrari";
public static final String FULL_NAME = NAME + " " + VERSION;
public static final String TITLE = "<html><body><font size=\"5\">" + FULL_NAME + "</font></body></html>";
public static final String DESC = "<html><body>Compatible with iOS 7.0 through iOS 13.x<br/><br/></body></html>";
public static final String KEY_SALT_BUTTON = "From key and salt";
public static final String FILE_BUTTON = "From property list (plist) file";
public static final String SSH_BUTTON = "From device via SSH";
public static final String IPROXY_BUTTON = "From device via iproxy over USB";
public static final String ITUNES_BACKUP = "From unencrypted iTunes backup";
public static final String ITUNES_BACKUPS = "iTunes Backups:";
public static final String ITUNES_BACKUP_12 = "From encrypted iTunes backup (iOS 12 only)";
public static final String KEYCHAIN_DUMPER = "From device via SSH";
public static final String ABOUT = "About/Credits";
public static final String iOS_13 = "<html><body><br/>iOS 12.0 through iOS 13.4.5:</body></html>";
public static final String iOS_11 = "<html><body><br/>iOS 7 through iOS 11:</body></html>";
} | 1,368 | Java | .java | TarballCoLtd/iOS-Restrictions-Recovery | 53 | 10 | 6 | 2020-02-19T04:41:52Z | 2022-12-07T01:18:36Z |
RequestType.java | /FileExtraction/Java_unseen/TarballCoLtd_iOS-Restrictions-Recovery/src/com/alyxferrari/iosrr/RequestType.java | package com.alyxferrari.iosrr;
public enum RequestType {
IPROXY, SSH, FILE, KEYSALT, VERSION, NONSENSICAL;
} | 109 | Java | .java | TarballCoLtd/iOS-Restrictions-Recovery | 53 | 10 | 6 | 2020-02-19T04:41:52Z | 2022-12-07T01:18:36Z |
RestrictionsRecovery.java | /FileExtraction/Java_unseen/TarballCoLtd_iOS-Restrictions-Recovery/src/com/alyxferrari/iosrr/RestrictionsRecovery.java | package com.alyxferrari.iosrr;
import java.security.*;
import java.security.spec.*;
import java.io.*;
import net.schmizz.sshj.*;
import net.schmizz.sshj.transport.verification.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
public class RestrictionsRecovery {
private RestrictionsRecovery() {}
public static void main(String[] args) throws Exception {
System.setErr(System.out);
if (args.length == 0) {
Display.createDisplay();
} else {
RRArguments arguments = ArgumentParser.parseArguments(args);
if (arguments.getRequestType() == RequestType.IPROXY) {
int port = 22;
String password = "alpine";
if (arguments.getPort() != null) {
port = Integer.parseInt(arguments.getPort());
}
if (arguments.getPassword() != null) {
password = arguments.getPassword();
}
RestrictionsRecovery.launchIproxy(port, password, true);
} else if (arguments.getRequestType() == RequestType.SSH) {
int port = 22;
String password = "alpine";
if (arguments.getPort() != null) {
port = Integer.parseInt(arguments.getPort());
}
if (arguments.getPassword() != null) {
password = arguments.getPassword();
}
RestrictionsRecovery.downloadViaSSH(arguments.getSsh(), port, password, true);
KeySaltPair pair = PropertyListReader.getKeyAndSaltFromPlist("password.plist");
RestrictionsRecovery.calculate(pair.getKey(), pair.getSalt(), true);
} else if (arguments.getRequestType() == RequestType.FILE) {
KeySaltPair pair = PropertyListReader.getKeyAndSaltFromPlist(arguments.getFile());
RestrictionsRecovery.calculate(pair.getKey(), pair.getSalt(), true);
} else if (arguments.getRequestType() == RequestType.KEYSALT) {
RestrictionsRecovery.calculate(arguments.getKey(), arguments.getSalt(), true);
} else if (arguments.getRequestType() == RequestType.VERSION) {
CommandLineOutput.printVersion();
} else {
CommandLineOutput.printUsage();
}
}
}
public static String calculate(String key, String salt, boolean exit) throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
System.out.println("Bruteforcing restrictions passcode...");
String passcode = PasscodeChecker.getPasscode(key, salt);
if (passcode.length() == 4) {
System.out.println("Found passcode!");
System.out.println("Restrictions passcode: " + passcode);
if (exit) {
System.exit(0);
}
return passcode;
} else {
System.out.println("The key " + key + " with the salt " + salt + " does not appear to be a valid combination for any iOS restrictions passcode. Please ensure you have entered the key and salt correctly.");
if (exit) {
System.exit(0);
}
return null;
}
}
public static void downloadViaSSH(String ip, int port, String password, boolean exit) throws IOException {
if (RestrictionsRecovery.identifyHostOS() != OperatingSystemType.OTHER) {
SSHClient ssh = new SSHClient();
ssh.addHostKeyVerifier(new PromiscuousVerifier());
ssh.connect(ip, port);
ssh.authPassword("root", password);
ssh.newSCPFileTransfer().download("/private/var/mobile/Library/Preferences/com.apple.restrictionspassword.plist", "password.plist");
ssh.disconnect();
ssh.close();
if (exit) {
System.exit(0);
}
} else {
CommandLineOutput.printUnsupportedOS();
}
}
public static OperatingSystemType identifyHostOS() {
String os = System.getProperty("os.name").toLowerCase();
if (os.indexOf("win") >= 0) {
return OperatingSystemType.WINDOWS;
} else if (os.indexOf("mac") >= 0) {
if (System.getProperty("os.version").indexOf("10.15") >= 0) {
return OperatingSystemType.MACOSCATALINA_OR_NEWER;
} else if (System.getProperty("os.version").indexOf("11.") >= 0) {
return OperatingSystemType.MACOSCATALINA_OR_NEWER;
} else {
return OperatingSystemType.MACOSMOJAVE_OR_OLDER;
}
} else if (os.indexOf("nix") >= 0) {
return OperatingSystemType.UNIX_BASED;
} else if (os.indexOf("nux") >= 0) {
return OperatingSystemType.UNIX_BASED;
} else if (os.indexOf("aix") >= 0) {
return OperatingSystemType.UNIX_BASED;
} else {
return OperatingSystemType.OTHER;
}
}
public static void launchIproxy(int port, String password, boolean exit) throws IOException, SAXException, ParserConfigurationException, InvalidKeySpecException, NoSuchAlgorithmException {
ProcessBuilder builder = null;
if (RestrictionsRecovery.identifyHostOS() == OperatingSystemType.MACOSMOJAVE_OR_OLDER || RestrictionsRecovery.identifyHostOS() == OperatingSystemType.UNIX_BASED) {
builder = new ProcessBuilder("/bin/bash", "-c", "iproxy", "23", ""+port);
} else if (RestrictionsRecovery.identifyHostOS() == OperatingSystemType.MACOSCATALINA_OR_NEWER) {
builder = new ProcessBuilder("/bin/zsh", "-c", "iproxy", "23", ""+port);
} else if (RestrictionsRecovery.identifyHostOS() == OperatingSystemType.WINDOWS) {
builder = new ProcessBuilder("cmd.exe", "/c", "iproxy", "23", ""+port); // MAKE SURE YOU HAVE IPROXY IN YOUR PATH ENVIRONMENT VARIABLE
} else {
CommandLineOutput.printUnsupportedOS();
}
builder.redirectErrorStream(true);
Process process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
if (line.equals("waiting for connection")) {
RestrictionsRecovery.downloadViaSSH("127.0.0.1", 23, password, exit);
KeySaltPair pair = PropertyListReader.getKeyAndSaltFromPlist("password.plist");
RestrictionsRecovery.calculate(pair.getKey(), pair.getSalt(), exit);
} else {
CommandLineOutput.printIproxyError();
}
}
} | 5,625 | Java | .java | TarballCoLtd/iOS-Restrictions-Recovery | 53 | 10 | 6 | 2020-02-19T04:41:52Z | 2022-12-07T01:18:36Z |
PropertyListReader.java | /FileExtraction/Java_unseen/TarballCoLtd_iOS-Restrictions-Recovery/src/com/alyxferrari/iosrr/PropertyListReader.java | package com.alyxferrari.iosrr;
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class PropertyListReader {
private PropertyListReader() {}
public static KeySaltPair getKeyAndSaltFromPlist(String plist) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(plist);
document.getDocumentElement().normalize();
String key = document.getElementsByTagName("data").item(0).getTextContent().split(" ")[1].split("\n")[0];
String salt = document.getElementsByTagName("data").item(1).getTextContent().split(" ")[1].split("\n")[0];
return new KeySaltPair(key, salt);
}
} | 795 | Java | .java | TarballCoLtd/iOS-Restrictions-Recovery | 53 | 10 | 6 | 2020-02-19T04:41:52Z | 2022-12-07T01:18:36Z |
ArgumentParser.java | /FileExtraction/Java_unseen/TarballCoLtd_iOS-Restrictions-Recovery/src/com/alyxferrari/iosrr/ArgumentParser.java | package com.alyxferrari.iosrr;
public class ArgumentParser {
private ArgumentParser() {}
public static RRArguments parseArguments(String[] args) {
boolean iproxy = false;
String ssh = null;
String password = null;
String port = null;
String file = null;
String key = null;
String salt = null;
boolean version = false;
for (int i = 0; i < args.length; i++) {
try {
if (args[i].equals("-iproxy")) {
iproxy = true;
} else if (args[i].equals("-ssh")) {
i++;
ssh = args[i];
} else if (args[i].equals("--secure-shell")) {
i++;
ssh = args[i];
} else if (args[i].equals("-password")) {
i++;
password = args[i];
} else if (args[i].equals("-port")) {
i++;
port = args[i];
} else if (args[i].equals("-f")) {
i++;
file = args[i];
} else if (args[i].equals("-file")) {
i++;
file = args[i];
} else if (args[i].equals("-k")) {
i++;
key = args[i];
} else if (args[i].equals("-key")) {
i++;
key = args[i];
} else if (args[i].equals("-s")) {
i++;
salt = args[i];
} else if (args[i].equals("-salt")) {
i++;
salt = args[i];
} else if (args[i].equals("-v")) {
version = true;
} else if (args[i].equals("-version")) {
version = true;
}
} catch (IndexOutOfBoundsException ex) {
return new RRArguments(false, null, null, null, null, null, null, false);
}
}
return new RRArguments(iproxy, ssh, password, port, file, key, salt, version);
}
} | 1,524 | Java | .java | TarballCoLtd/iOS-Restrictions-Recovery | 53 | 10 | 6 | 2020-02-19T04:41:52Z | 2022-12-07T01:18:36Z |
CommandLineOutput.java | /FileExtraction/Java_unseen/TarballCoLtd_iOS-Restrictions-Recovery/src/com/alyxferrari/iosrr/CommandLineOutput.java | package com.alyxferrari.iosrr;
public class CommandLineOutput {
private CommandLineOutput() {}
public static void printUsage() {
System.out.println("Usage: java RestrictionsRecovery [options]");
System.out.println(" Options:");
System.out.println(" -iproxy [port]: recover the restrictions passcode directly from a connected jailbroken device with OpenSSH installed, with the port specified in the optional port argument; if no port is specified, 22 will be used\n");
System.out.println(" -ssh ip_address, --secure-shell ip_address: connects to a jailbroken device and recovers the restrictions passcode directly from it; must have OpenSSH installed on the target device");
System.out.println(" -password password: (optional) specifies SSH password when connecting to device via SSH, if no password is specified, 'alpine' will be used; can also be used with the -iproxy option");
System.out.println(" -port port: (optional) specifies SSH port when connecting to device via SSH, if no port is specified, 22 will be used; can also be used with the -iproxy option\n");
System.out.println(" -f file, -file file: reads the key and salt directly from the passcode property list file\n");
System.out.println(" -k key, -key key: specifies key to use to brute force passcode");
System.out.println(" -s salt, -salt salt: specifies salt used to produce key");
System.out.println(" -v, -version: displays the version of RestrictionsRecovery installed");
System.out.println(" -h, -help: displays this menu");
System.out.println("\nOn iOS 7.0 to iOS 11.4.1, the key and salt are found in the com.apple.restrictionspassword.plist file located in /private/var/mobile/Library/Preferences.");
System.exit(0);
}
public static void printVersion() {
System.out.println("RestrictionsRecovery version: v" + RRConst.VERSION);
System.exit(0);
}
public static void printUnsupportedOS() {
System.out.println("Host operating system is unsupported by iOS Restrictions Recovery.");
System.exit(0);
}
public static void printIproxyError() {
System.out.println("iproxy encountered a fatal error. Please ensure you have the dependencies listed in the README installed.");
System.exit(0);
}
} | 2,233 | Java | .java | TarballCoLtd/iOS-Restrictions-Recovery | 53 | 10 | 6 | 2020-02-19T04:41:52Z | 2022-12-07T01:18:36Z |
InfoPlist.java | /FileExtraction/Java_unseen/TarballCoLtd_iOS-Restrictions-Recovery/src/com/alyxferrari/iosrr/InfoPlist.java | package com.alyxferrari.iosrr;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
public class InfoPlist {
private final String deviceName;
private final String displayName;
private final String backupDate;
private final String iOSVersion;
private final String file;
private InfoPlist(String deviceName, String displayName, String backupDate, String iOSVersion, String file) {
this.deviceName = deviceName;
this.displayName = displayName;
this.backupDate = backupDate;
this.iOSVersion = iOSVersion;
this.file = file;
}
public String getModelName() {
return identifierToName(deviceName);
}
public String getDeviceName() {
return deviceName;
}
public String getDisplayName() {
return displayName;
}
public String getBackupDate() {
return backupDate;
}
public String getiOSVersion() {
if (getiOSRelease() == -1) {
return "iOS version couldn't be read";
} else {
return iOSVersion;
}
}
public String getFile() {
return file;
}
public int getiOSRelease() {
try {
String version = iOSVersion.split(" ")[1].substring(0, 2);
if (version.endsWith(".")) {
return Integer.parseInt(version.substring(0, 1));
}
return Integer.parseInt(version);
} catch (NumberFormatException ex) {
return -1;
}
}
public static InfoPlist getInstance(String file) {
try {
String fileTemp = file + "Info.plist";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(fileTemp);
document.getDocumentElement().normalize();
NodeList nodes = document.getElementsByTagName("string");
String displayName = nodes.item(1).getTextContent();
boolean stop = false;
String deviceName = null;
String iOSVersion = null;
for (int i = 3; !stop; i++) {
if (nodes.item(i).getTextContent().startsWith("iP")) {
FileInputStream fis = new FileInputStream(fileTemp);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String result = "";
String line = "";
while ((line = reader.readLine()) != null) {
result += line;
}
reader.close();
if (result.contains("Product Name")) {
deviceName = nodes.item(i+1).getTextContent();
iOSVersion = "iOS " + nodes.item(i+2).getTextContent();
} else {
deviceName = nodes.item(i).getTextContent();
iOSVersion = "iOS " + nodes.item(i+1).getTextContent();
}
stop = true;
}
}
String backupDate = document.getElementsByTagName("date").item(0).getTextContent();
String backupDate1 = backupDate.substring(0, 10);
String backupDate2 = backupDate.substring(14, 19);
backupDate = backupDate1 + "@" + backupDate2;
return new InfoPlist(deviceName, displayName, backupDate, iOSVersion, file);
} catch (Exception ex) {}
return null;
}
public static String identifierToName(String identifier) {
if (identifier.equals("iPhone1,1")) {
return "iPhone 2G";
} else if (identifier.equals("iPhone1,2")) {
return "iPhone 3G";
} else if (identifier.equals("iPhone2,1")) {
return "iPhone 3Gs";
} else if (identifier.equals("iPhone3,1")) {
return "iPhone 4";
} else if (identifier.equals("iPhone3,2")) {
return "iPhone 4 (GSM)";
} else if (identifier.equals("iPhone3,3")) {
return "iPhone 4 (CDMA)";
} else if (identifier.equals("iPhone4,1")) {
return "iPhone 4s";
} else if (identifier.equals("iPhone5,1")) {
return "iPhone 5 (GSM)";
} else if (identifier.equals("iPhone5,2")) {
return "iPhone 5 (GSM/CDMA)";
} else if (identifier.equals("iPhone5,3")) {
return "iPhone 5c (GSM)";
} else if (identifier.equals("iPhone5,4")) {
return "iPhone 5c (Global)";
} else if (identifier.equals("iPhone6,1")) {
return "iPhone 5s (GSM)";
} else if (identifier.equals("iPhone6,2")) {
return "iPhone 5s (Global)";
} else if (identifier.equals("iPhone7,1")) {
return "iPhone 6 Plus";
} else if (identifier.equals("iPhone7,2")) {
return "iPhone 6";
} else if (identifier.equals("iPhone8,1")) {
return "iPhone 6s";
} else if (identifier.equals("iPhone8,2")) {
return "iPhone 6s Plus";
} else if (identifier.equals("iPhone8,4")) {
return "iPhone SE (1st generation)";
} else if (identifier.equals("iPhone9,1") || identifier.equals("iPhone9,3")) {
return "iPhone 7";
} else if (identifier.equals("iPhone9,2") || identifier.equals("iPhone9,4")) {
return "iPhone 7 Plus";
} else if (identifier.equals("iPhone10,1") || identifier.equals("iPhone10,4")) {
return "iPhone 8";
} else if (identifier.equals("iPhone10,2") || identifier.equals("iPhone10,5")) {
return "iPhone 8 Plus";
} else if (identifier.equals("iPhone10,3")) {
return "iPhone X (Global)";
} else if (identifier.equals("iPhone10,6")) {
return "iPhone X (GSM)";
} else if (identifier.equals("iPhone11,2")) {
return "iPhone Xs";
} else if (identifier.equals("iPhone11,4")) {
return "iPhone Xs Max";
} else if (identifier.equals("iPhone11,6")) {
return "iPhone Xs Max (Global)";
} else if (identifier.equals("iPhone11,8")) {
return "iPhone XR";
} else if (identifier.equals("iPhone12,1")) {
return "iPhone 11";
} else if (identifier.equals("iPhone12,3")) {
return "iPhone 11 Pro";
} else if (identifier.equals("iPhone12,5")) {
return "iPhone 11 Pro Max";
} else if (identifier.equals("iPhone12,8")) {
return "iPhone SE (2nd generation)";
} else if (identifier.equals("iPod1,1")) {
return "iPod touch 1G";
} else if (identifier.equals("iPod2,1")) {
return "iPod touch 2G";
} else if (identifier.equals("iPod3,1")) {
return "iPod touch 3G";
} else if (identifier.equals("iPod4,1")) {
return "iPod touch 4G";
} else if (identifier.equals("iPod5,1")) {
return "iPod touch 5G";
} else if (identifier.equals("iPod7,1")) {
return "iPod touch 6G";
} else if (identifier.equals("iPod9,1")) {
return "iPod touch 7G";
} else if (identifier.startsWith("iPad")) {
return "iPad";
}
return identifier;
}
} | 6,063 | Java | .java | TarballCoLtd/iOS-Restrictions-Recovery | 53 | 10 | 6 | 2020-02-19T04:41:52Z | 2022-12-07T01:18:36Z |
KeySaltPair.java | /FileExtraction/Java_unseen/TarballCoLtd_iOS-Restrictions-Recovery/src/com/alyxferrari/iosrr/KeySaltPair.java | package com.alyxferrari.iosrr;
public class KeySaltPair {
private final String key;
private final String salt;
public KeySaltPair(String key, String salt) {
this.key = key;
this.salt = salt;
}
public String getKey() {
return key;
}
public String getSalt() {
return salt;
}
} | 290 | Java | .java | TarballCoLtd/iOS-Restrictions-Recovery | 53 | 10 | 6 | 2020-02-19T04:41:52Z | 2022-12-07T01:18:36Z |
Config.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/Config.java | package net.rezxis.mctp.client;
import java.io.File;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
public class Config {
public String host = "mctp1.nohit.cc";
public int port = 9998;
public Config(JavaPlugin plugin) throws Exception {
FileConfiguration configuration = new YamlConfiguration();
File file = new File(plugin.getDataFolder(),"mctp.yml");
if (!file.exists()) {
configuration.set("host", host);
configuration.set("port", port);
configuration.save(file);
} else {
configuration.load(file);
host = configuration.getString("host");
port = configuration.getInt("port");
}
}
}
| 758 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
MCTPVars.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/MCTPVars.java | package net.rezxis.mctp.client;
import io.netty.buffer.ByteBuf;
import io.netty.util.AttributeKey;
import java.util.ArrayList;
public class MCTPVars {
public static final int CODE_INIT = 0x00;
public static final int CODE_READY = 0x01;
public static final int CODE_NEW = 0x02;
public static final int CODE_UPGRADE = 0x03;
public static final AttributeKey<ArrayList<ByteBuf>> PACKET_STACK = AttributeKey.newInstance("PACKET_STACK");
}
| 459 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
MCTPClient.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/MCTPClient.java | package net.rezxis.mctp.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import net.rezxis.mctp.client.proxied.ProxiedConnection;
import net.rezxis.mctp.client.util.PacketDecoder;
import net.rezxis.mctp.client.util.PacketEncoder;
import org.bukkit.Bukkit;
@ChannelHandler.Sharable
public class MCTPClient extends ChannelInboundHandlerAdapter implements Runnable {
private Channel channel;
private String host;
private int port;
public MCTPClient(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public void run() {
Bootstrap bs = new Bootstrap();
EventLoopGroup worker = new NioEventLoopGroup();
try{
bs.channel(NioSocketChannel.class)
.group(worker)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new PacketEncoder());
ch.pipeline().addLast(new PacketDecoder(), MCTPClient.this);
}
});
channel = bs.connect(host, port).sync().channel();
} catch(Exception e) {
e.printStackTrace();
MinecraftTransport.instance.getLogger().warning("failed to connect to MCTP server. reconnecting after 5 seconds.");
Bukkit.getScheduler().runTaskLaterAsynchronously(MinecraftTransport.instance, new Runnable() {
@Override
public void run() {
MCTPClient.this.run();
}
}, 20 * 5);
return;
}
sendInitPacket();
MinecraftTransport.instance.getLogger().info("connected to MCTP server.");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
int op = buf.readByte();
if (op == MCTPVars.CODE_READY) {
String host = readString(buf);
int port = buf.readInt();
MinecraftTransport.ip = host + ":" + port;
MinecraftTransport.instance.getLogger().info("connection has been authenticated.");
MinecraftTransport.instance.getLogger().info(host + ":" + port+" is assigned address to this server.");
} else if (op == MCTPVars.CODE_NEW) {
long secret = buf.readLong();
long id = buf.readLong();
new Thread(new ProxiedConnection(secret,id)).start();
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (!MinecraftTransport.instance.disabling) {
MinecraftTransport.instance.getLogger().warning("disconnected from MCTP server. reconnecting after 5 seconds.");
Bukkit.getScheduler().runTaskLaterAsynchronously(MinecraftTransport.instance, new Runnable() {
@Override
public void run() {
MCTPClient.this.run();
}
}, 20 * 5);
}
}
private String readString(ByteBuf buf){
int length = buf.readInt();
byte[] strBuf = new byte[length];
buf.readBytes(strBuf);
return new String(strBuf);
}
private ByteBuf createPacket(int size){
return Unpooled.buffer(size, size);
}
private void sendInitPacket() {
ByteBuf packet = createPacket(1);
packet.writeByte(MCTPVars.CODE_INIT);
channel.writeAndFlush(packet);
}
public void close() {
try {
channel.close().sync().awaitUninterruptibly();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 4,145 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
MinecraftTransport.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/MinecraftTransport.java | package net.rezxis.mctp.client;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import net.rezxis.mctp.client.netty.NettyChannelInitializer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
public class MinecraftTransport extends JavaPlugin {
public static MinecraftTransport instance;
public static String ip;
public static Config config;
public static MCTPClient client;
public static boolean disabling;
public void onLoad(){
instance = this;
try {
getLogger().info("Loading Config...");
config = new Config(this);
getLogger().info("MCTP-Host : "+config.host+":"+config.port);
getLogger().info("Loaded config!");
} catch (Exception e1) {
getLogger().warning("Failed to load config!");
e1.printStackTrace();
}
try {
getLogger().info("Injecting NettyHandler...");
inject();
getLogger().info("Injected NettyHandler!");
} catch (Exception e) {
getLogger().warning("Failed to inject NettyHandler!");
e.printStackTrace();
}
client = new MCTPClient(config.host,config.port);
new Thread(client).start();
}
public void onEnable() {
if (ip != null)
getLogger().info(ip+" is assigned address to this server.");
}
public void onDisable() {
disabling = true;
client.close();
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("checkip")) {
sender.sendMessage(ip+" is assigned address to this server.");
}
return true;
}
private void inject() throws Exception {
Method serverGetHandle = Bukkit.getServer().getClass().getDeclaredMethod("getServer");
Object minecraftServer = serverGetHandle.invoke(Bukkit.getServer());
Method serverConnectionMethod = null;
for(Method method : minecraftServer.getClass().getSuperclass().getDeclaredMethods()) {
if(!method.getReturnType().getSimpleName().equals("ServerConnection")) {
continue;
}
serverConnectionMethod = method;
break;
}
Object serverConnection = serverConnectionMethod.invoke(minecraftServer);
List<ChannelFuture> channelFutureList = null;
for (Field field : serverConnection.getClass().getDeclaredFields()) {
if (field.getType().getName().contains("List") ) {
if (((Class<?>)((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]).getName().contains("ChannelFuture")) {
field.setAccessible(true);
channelFutureList = (List<ChannelFuture>) field.get(serverConnection);
}
}
}
if (channelFutureList == null) {
throw new Exception("Failed to get channelFutureList.");
}
for (ChannelFuture channelFuture : channelFutureList) {
ChannelPipeline channelPipeline = channelFuture.channel().pipeline();
ChannelHandler serverBootstrapAcceptor = channelPipeline.first();
System.out.println(serverBootstrapAcceptor.getClass().getName());
ChannelInitializer<SocketChannel> oldChildHandler = ReflectionUtils.getPrivateField(serverBootstrapAcceptor.getClass(), serverBootstrapAcceptor, ChannelInitializer.class, "childHandler");
if (oldChildHandler instanceof NettyChannelInitializer)
break;
ReflectionUtils.setFinalField(serverBootstrapAcceptor.getClass(), serverBootstrapAcceptor, "childHandler", new NettyChannelInitializer(oldChildHandler));
}
}
}
| 3,669 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
ReflectionUtils.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/ReflectionUtils.java | package net.rezxis.mctp.client;
import sun.misc.Unsafe;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class ReflectionUtils {
private static final Field FIELD_MODIFIERS;
private static final Field FIELD_ACCESSSOR;
private static final Field FIELD_ACCESSSOR_OVERRIDE;
private static final Field FIELD_ROOT;
private static final Unsafe unsafe;
private static final int version = getVersion();
static {
if (version >= 12) {
FIELD_MODIFIERS = null;
FIELD_ACCESSSOR = null;
FIELD_ACCESSSOR_OVERRIDE = null;
FIELD_ROOT = null;
Unsafe us = null;
try {
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
us = (Unsafe) unsafeField.get(null);
} catch (Exception ex) {
ex.printStackTrace();
}
unsafe = us;
} else {
Field fieldModifiers = null;
Field fieldAccessor = null;
Field fieldAccessorOverride = null;
Field fieldRoot = null;
try {
fieldModifiers = Field.class.getDeclaredField("modifiers");
fieldModifiers.setAccessible(true);
fieldAccessor = Field.class.getDeclaredField("fieldAccessor");
fieldAccessor.setAccessible(true);
fieldAccessorOverride = Field.class.getDeclaredField("overrideFieldAccessor");
fieldAccessorOverride.setAccessible(true);
fieldRoot = Field.class.getDeclaredField("root");
fieldRoot.setAccessible(true);
} catch (Exception exception) {
exception.printStackTrace();
}
FIELD_MODIFIERS = fieldModifiers;
FIELD_ACCESSSOR = fieldAccessor;
FIELD_ACCESSSOR_OVERRIDE = fieldAccessorOverride;
FIELD_ROOT = fieldRoot;
unsafe = null;
}
}
public static void setFinalField(Class<?> objectClass, Object object, String fieldName, Object value) throws Exception {
Field field = objectClass.getDeclaredField(fieldName);
if (version >= 12) {
long offset = unsafe.objectFieldOffset(field);
unsafe.putObject(object, offset, value);
} else {
field.setAccessible(true);
if (Modifier.isFinal(field.getModifiers())) {
FIELD_MODIFIERS.setInt(field, field.getModifiers() & ~Modifier.FINAL);
Field currentField = field;
do {
FIELD_ACCESSSOR.set(currentField, null);
FIELD_ACCESSSOR_OVERRIDE.set(currentField, null);
} while ((currentField = (Field) FIELD_ROOT.get(currentField)) != null);
}
field.set(object, value);
}
}
@SuppressWarnings("unchecked")
public static <T> T getPrivateField(Class<?> objectClass, Object object, Class<T> fieldClass, String fieldName) throws Exception {
Field field = objectClass.getDeclaredField(fieldName);
field.setAccessible(true);
return (T) field.get(object);
}
private static int getVersion() {
String version = System.getProperty("java.version");
if(version.startsWith("1.")) {
version = version.substring(2, 3);
} else {
int dot = version.indexOf(".");
if(dot != -1) { version = version.substring(0, dot); }
} return Integer.parseInt(version);
}
}
| 3,045 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
ChannelMirror.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/ChannelMirror.java | package net.rezxis.mctp.client;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
@ChannelHandler.Sharable
public class ChannelMirror extends ChannelInboundHandlerAdapter {
private final Channel dest;
public ChannelMirror(Channel dest) {
this.dest = dest;
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (!dest.isActive())
return;
dest.close();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!dest.isActive()) {
ctx.channel().close();
return;
}
dest.writeAndFlush(msg);
}
} | 815 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
PacketEncoder.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/util/PacketEncoder.java | package net.rezxis.mctp.client.util;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
public class PacketEncoder extends MessageToByteEncoder<ByteBuf> {
@Override
protected void encode(ChannelHandlerContext ch, ByteBuf buf, ByteBuf out) throws Exception {
out.writeInt(buf.readableBytes());
out.writeBytes(buf);
}
} | 431 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
PacketDecoder.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/util/PacketDecoder.java | package net.rezxis.mctp.client.util;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
public class PacketDecoder extends ByteToMessageDecoder {
private int length;
public PacketDecoder() {
length = -1;
}
@Override
protected void decode(ChannelHandlerContext ch, ByteBuf buf, List<Object> out) throws Exception {
if(length == -1){
if(buf.readableBytes() < 4){
return;
}
length = buf.readInt();
}
if(buf.readableBytes() < length){
return;
}
ByteBuf o = buf.readBytes(length);
out.add(o);
length = -1;
}
} | 770 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
NettyChannelInitializer.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/netty/NettyChannelInitializer.java | package net.rezxis.mctp.client.netty;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import net.rezxis.mctp.client.haproxy.HAProxyMessage;
import net.rezxis.mctp.client.haproxy.HAProxyMessageDecoder;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Map;
import org.bukkit.Bukkit;
public class NettyChannelInitializer extends ChannelInitializer<SocketChannel> {
public static final String NMS_VERSION = Bukkit.getServer().getClass().getPackage().getName().substring(23);
private static Field fieldL;
private ChannelInitializer<SocketChannel> oldChildHandler;
private Method oldChildHandlerMethod;
public NettyChannelInitializer(ChannelInitializer<SocketChannel> oldChildHandler) throws Exception {
this.oldChildHandler = oldChildHandler;
this.oldChildHandlerMethod = this.oldChildHandler.getClass().getDeclaredMethod("initChannel", Channel.class);
this.oldChildHandlerMethod.setAccessible(true);
}
@Override
protected void initChannel(SocketChannel channel) throws Exception {
this.oldChildHandlerMethod.invoke(this.oldChildHandler, channel);
if (channel.pipeline().get("haproxy-decoder") == null )
channel.pipeline().addAfter("timeout", "haproxy-decoder", new HAProxyMessageDecoder());
if (channel.pipeline().get("haproxy-handler") == null )
channel.pipeline().addAfter("haproxy-decoder", "haproxy-handler", new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HAProxyMessage) {
HAProxyMessage message = (HAProxyMessage) msg;
String realaddress = message.sourceAddress();
int realport = message.sourcePort();
SocketAddress socketaddr = new InetSocketAddress(realaddress, realport);
fieldL.set(channel.pipeline().get("packet_handler"), socketaddr);
} else {
super.channelRead(ctx, msg);
}
}
});
}
static {
Class<?> NetworkManagerClz = null;
try {
NetworkManagerClz = Class.forName("net.minecraft.server."+NMS_VERSION+".NetworkManager");
} catch (Exception e) {
try {
NetworkManagerClz = Class.forName("net.minecraft.network.NetworkManager");
} catch (Exception e2) {
e2.printStackTrace();
}
}
try {
for (Field field : NetworkManagerClz.getDeclaredFields()) {
if (field.getType().getName().contains("java.net.SocketAddress")) {
fieldL = field;
}
}
fieldL.setAccessible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} | 2,741 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
NettyInjectHandler.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/netty/NettyInjectHandler.java | package net.rezxis.mctp.client.netty;
import io.netty.channel.ChannelHandlerContext;
public interface NettyInjectHandler {
public void packetReceived(NettyDecoderHandler handler, ChannelHandlerContext context, Object object) throws Exception;
public boolean isEnabled();
}
| 281 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
NettyDecoderHandler.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/netty/NettyDecoderHandler.java | package net.rezxis.mctp.client.netty;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.util.List;
public class NettyDecoderHandler extends MessageToMessageDecoder<Object> {
private NettyInjectHandler handler;
public NettyDecoderHandler(NettyInjectHandler handler) throws Exception {
this.handler = handler;
}
@Override
protected void decode(ChannelHandlerContext context, Object packet, List<Object> out) throws Exception {
this.handler.packetReceived(this, context, packet);
out.add(packet);
}
}
| 582 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
HAProxyMessage.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/haproxy/HAProxyMessage.java | package net.rezxis.mctp.client.haproxy;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufProcessor;
import io.netty.util.CharsetUtil;
import io.netty.util.NetUtil;
import net.rezxis.mctp.client.haproxy.HAProxyProxiedProtocol.AddressFamily;
/**
* Message container for decoded HAProxy proxy protocol parameters
*/
public final class HAProxyMessage {
/**
* Version 1 proxy protocol message for 'UNKNOWN' proxied protocols. Per spec, when the proxied protocol is
* 'UNKNOWN' we must discard all other header values.
*/
private static final HAProxyMessage V1_UNKNOWN_MSG = new HAProxyMessage(
HAProxyProtocolVersion.V1, HAProxyCommand.PROXY, HAProxyProxiedProtocol.UNKNOWN, null, null, 0, 0);
/**
* Version 2 proxy protocol message for 'UNKNOWN' proxied protocols. Per spec, when the proxied protocol is
* 'UNKNOWN' we must discard all other header values.
*/
private static final HAProxyMessage V2_UNKNOWN_MSG = new HAProxyMessage(
HAProxyProtocolVersion.V2, HAProxyCommand.PROXY, HAProxyProxiedProtocol.UNKNOWN, null, null, 0, 0);
/**
* Version 2 proxy protocol message for local requests. Per spec, we should use an unspecified protocol and family
* for 'LOCAL' commands. Per spec, when the proxied protocol is 'UNKNOWN' we must discard all other header values.
*/
private static final HAProxyMessage V2_LOCAL_MSG = new HAProxyMessage(
HAProxyProtocolVersion.V2, HAProxyCommand.LOCAL, HAProxyProxiedProtocol.UNKNOWN, null, null, 0, 0);
private final HAProxyProtocolVersion protocolVersion;
private final HAProxyCommand command;
private final HAProxyProxiedProtocol proxiedProtocol;
private final String sourceAddress;
private final String destinationAddress;
private final int sourcePort;
private final int destinationPort;
/**
* Creates a new instance
*/
private HAProxyMessage(
HAProxyProtocolVersion protocolVersion, HAProxyCommand command, HAProxyProxiedProtocol proxiedProtocol,
String sourceAddress, String destinationAddress, String sourcePort, String destinationPort) {
this(
protocolVersion, command, proxiedProtocol,
sourceAddress, destinationAddress, portStringToInt(sourcePort), portStringToInt(destinationPort));
}
/**
* Creates a new instance
*/
private HAProxyMessage(
HAProxyProtocolVersion protocolVersion, HAProxyCommand command, HAProxyProxiedProtocol proxiedProtocol,
String sourceAddress, String destinationAddress, int sourcePort, int destinationPort) {
if (proxiedProtocol == null) {
throw new NullPointerException("proxiedProtocol");
}
AddressFamily addrFamily = proxiedProtocol.addressFamily();
checkAddress(sourceAddress, addrFamily);
checkAddress(destinationAddress, addrFamily);
checkPort(sourcePort);
checkPort(destinationPort);
this.protocolVersion = protocolVersion;
this.command = command;
this.proxiedProtocol = proxiedProtocol;
this.sourceAddress = sourceAddress;
this.destinationAddress = destinationAddress;
this.sourcePort = sourcePort;
this.destinationPort = destinationPort;
}
/**
* Decodes a version 2, binary proxy protocol header.
*
* @param header a version 2 proxy protocol header
* @return {@link HAProxyMessage} instance
* @throws HAProxyProtocolException if any portion of the header is invalid
*/
static HAProxyMessage decodeHeader(ByteBuf header) {
if (header == null) {
throw new NullPointerException("header");
}
if (header.readableBytes() < 16) {
throw new HAProxyProtocolException(
"incomplete header: " + header.readableBytes() + " bytes (expected: 16+ bytes)");
}
// Per spec, the 13th byte is the protocol version and command byte
header.skipBytes(12);
final byte verCmdByte = header.readByte();
HAProxyProtocolVersion ver;
try {
ver = HAProxyProtocolVersion.valueOf(verCmdByte);
} catch (IllegalArgumentException e) {
throw new HAProxyProtocolException(e);
}
if (ver != HAProxyProtocolVersion.V2) {
throw new HAProxyProtocolException("version 1 unsupported: 0x" + Integer.toHexString(verCmdByte));
}
HAProxyCommand cmd;
try {
cmd = HAProxyCommand.valueOf(verCmdByte);
} catch (IllegalArgumentException e) {
throw new HAProxyProtocolException(e);
}
if (cmd == HAProxyCommand.LOCAL) {
return V2_LOCAL_MSG;
}
// Per spec, the 14th byte is the protocol and address family byte
HAProxyProxiedProtocol protAndFam;
try {
protAndFam = HAProxyProxiedProtocol.valueOf(header.readByte());
} catch (IllegalArgumentException e) {
throw new HAProxyProtocolException(e);
}
if (protAndFam == HAProxyProxiedProtocol.UNKNOWN) {
return V2_UNKNOWN_MSG;
}
int addressInfoLen = header.readUnsignedShort();
String srcAddress;
String dstAddress;
int addressLen;
int srcPort = 0;
int dstPort = 0;
AddressFamily addressFamily = protAndFam.addressFamily();
if (addressFamily == AddressFamily.AF_UNIX) {
// unix sockets require 216 bytes for address information
if (addressInfoLen < 216 || header.readableBytes() < 216) {
throw new HAProxyProtocolException(
"incomplete UNIX socket address information: " +
Math.min(addressInfoLen, header.readableBytes()) + " bytes (expected: 216+ bytes)");
}
int startIdx = header.readerIndex();
int addressEnd = header.forEachByte(startIdx, 108, ByteBufProcessor.FIND_NUL);
if (addressEnd == -1) {
addressLen = 108;
} else {
addressLen = addressEnd - startIdx;
}
srcAddress = header.toString(startIdx, addressLen, CharsetUtil.US_ASCII);
startIdx += 108;
addressEnd = header.forEachByte(startIdx, 108, ByteBufProcessor.FIND_NUL);
if (addressEnd == -1) {
addressLen = 108;
} else {
addressLen = addressEnd - startIdx;
}
dstAddress = header.toString(startIdx, addressLen, CharsetUtil.US_ASCII);
} else {
if (addressFamily == AddressFamily.AF_IPv4) {
// IPv4 requires 12 bytes for address information
if (addressInfoLen < 12 || header.readableBytes() < 12) {
throw new HAProxyProtocolException(
"incomplete IPv4 address information: " +
Math.min(addressInfoLen, header.readableBytes()) + " bytes (expected: 12+ bytes)");
}
addressLen = 4;
} else if (addressFamily == AddressFamily.AF_IPv6) {
// IPv6 requires 36 bytes for address information
if (addressInfoLen < 36 || header.readableBytes() < 36) {
throw new HAProxyProtocolException(
"incomplete IPv6 address information: " +
Math.min(addressInfoLen, header.readableBytes()) + " bytes (expected: 36+ bytes)");
}
addressLen = 16;
} else {
throw new HAProxyProtocolException(
"unable to parse address information (unkown address family: " + addressFamily + ')');
}
// Per spec, the src address begins at the 17th byte
srcAddress = ipBytestoString(header, addressLen);
dstAddress = ipBytestoString(header, addressLen);
srcPort = header.readUnsignedShort();
dstPort = header.readUnsignedShort();
}
return new HAProxyMessage(ver, cmd, protAndFam, srcAddress, dstAddress, srcPort, dstPort);
}
/**
* Decodes a version 1, human-readable proxy protocol header.
*
* @param header a version 1 proxy protocol header
* @return {@link HAProxyMessage} instance
* @throws HAProxyProtocolException if any portion of the header is invalid
*/
static HAProxyMessage decodeHeader(String header) {
if (header == null) {
throw new HAProxyProtocolException("header");
}
String[] parts = header.split(" ");
int numParts = parts.length;
if (numParts < 2) {
throw new HAProxyProtocolException(
"invalid header: " + header + " (expected: 'PROXY' and proxied protocol values)");
}
if (!"PROXY".equals(parts[0])) {
throw new HAProxyProtocolException("unknown identifier: " + parts[0]);
}
HAProxyProxiedProtocol protAndFam;
try {
protAndFam = HAProxyProxiedProtocol.valueOf(parts[1]);
} catch (IllegalArgumentException e) {
throw new HAProxyProtocolException(e);
}
if (protAndFam != HAProxyProxiedProtocol.TCP4 &&
protAndFam != HAProxyProxiedProtocol.TCP6 &&
protAndFam != HAProxyProxiedProtocol.UNKNOWN) {
throw new HAProxyProtocolException("unsupported v1 proxied protocol: " + parts[1]);
}
if (protAndFam == HAProxyProxiedProtocol.UNKNOWN) {
return V1_UNKNOWN_MSG;
}
if (numParts != 6) {
throw new HAProxyProtocolException("invalid TCP4/6 header: " + header + " (expected: 6 parts)");
}
return new HAProxyMessage(
HAProxyProtocolVersion.V1, HAProxyCommand.PROXY,
protAndFam, parts[2], parts[3], parts[4], parts[5]);
}
/**
* Convert ip address bytes to string representation
*
* @param header buffer containing ip address bytes
* @param addressLen number of bytes to read (4 bytes for IPv4, 16 bytes for IPv6)
* @return string representation of the ip address
*/
private static String ipBytestoString(ByteBuf header, int addressLen) {
StringBuilder sb = new StringBuilder();
if (addressLen == 4) {
sb.append(header.readByte() & 0xff);
sb.append('.');
sb.append(header.readByte() & 0xff);
sb.append('.');
sb.append(header.readByte() & 0xff);
sb.append('.');
sb.append(header.readByte() & 0xff);
} else {
sb.append(Integer.toHexString(header.readUnsignedShort()));
sb.append(':');
sb.append(Integer.toHexString(header.readUnsignedShort()));
sb.append(':');
sb.append(Integer.toHexString(header.readUnsignedShort()));
sb.append(':');
sb.append(Integer.toHexString(header.readUnsignedShort()));
sb.append(':');
sb.append(Integer.toHexString(header.readUnsignedShort()));
sb.append(':');
sb.append(Integer.toHexString(header.readUnsignedShort()));
sb.append(':');
sb.append(Integer.toHexString(header.readUnsignedShort()));
sb.append(':');
sb.append(Integer.toHexString(header.readUnsignedShort()));
}
return sb.toString();
}
/**
* Convert port to integer
*
* @param value the port
* @return port as an integer
* @throws HAProxyProtocolException if port is not a valid integer
*/
private static int portStringToInt(String value) {
int port;
try {
port = Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new HAProxyProtocolException("invalid port: " + value, e);
}
if (port <= 0 || port > 65535) {
throw new HAProxyProtocolException("invalid port: " + value + " (expected: 1 ~ 65535)");
}
return port;
}
/**
* Validate an address (IPv4, IPv6, Unix Socket)
*
* @param address human-readable address
* @param addrFamily the {@link AddressFamily} to check the address against
* @throws HAProxyProtocolException if the address is invalid
*/
@SuppressWarnings("incomplete-switch")
private static void checkAddress(String address, AddressFamily addrFamily) {
if (addrFamily == null) {
throw new NullPointerException("addrFamily");
}
switch (addrFamily) {
case AF_UNSPEC:
if (address != null) {
throw new HAProxyProtocolException("unable to validate an AF_UNSPEC address: " + address);
}
return;
case AF_UNIX:
return;
}
if (address == null) {
throw new NullPointerException("address");
}
switch (addrFamily) {
case AF_IPv4:
if (!NetUtil.isValidIpV4Address(address)) {
throw new HAProxyProtocolException("invalid IPv4 address: " + address);
}
break;
case AF_IPv6:
if (!NetUtil.isValidIpV6Address(address)) {
throw new HAProxyProtocolException("invalid IPv6 address: " + address);
}
break;
default:
throw new Error();
}
}
/**
* Validate a UDP/TCP port
*
* @param port the UDP/TCP port
* @throws HAProxyProtocolException if the port is out of range (0-65535 inclusive)
*/
private static void checkPort(int port) {
if (port < 0 || port > 65535) {
throw new HAProxyProtocolException("invalid port: " + port + " (expected: 1 ~ 65535)");
}
}
/**
* Returns the {@link HAProxyProtocolVersion} of this {@link HAProxyMessage}.
*/
public HAProxyProtocolVersion protocolVersion() {
return protocolVersion;
}
/**
* Returns the {@link HAProxyCommand} of this {@link HAProxyMessage}.
*/
public HAProxyCommand command() {
return command;
}
/**
* Returns the {@link HAProxyProxiedProtocol} of this {@link HAProxyMessage}.
*/
public HAProxyProxiedProtocol proxiedProtocol() {
return proxiedProtocol;
}
/**
* Returns the human-readable source address of this {@link HAProxyMessage}.
*/
public String sourceAddress() {
return sourceAddress;
}
/**
* Returns the human-readable destination address of this {@link HAProxyMessage}.
*/
public String destinationAddress() {
return destinationAddress;
}
/**
* Returns the UDP/TCP source port of this {@link HAProxyMessage}.
*/
public int sourcePort() {
return sourcePort;
}
/**
* Returns the UDP/TCP destination port of this {@link HAProxyMessage}.
*/
public int destinationPort() {
return destinationPort;
}
} | 15,470 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
HAProxyProtocolVersion.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/haproxy/HAProxyProtocolVersion.java | package net.rezxis.mctp.client.haproxy;
import static net.rezxis.mctp.client.haproxy.HAProxyConstants.*;
public enum HAProxyProtocolVersion {
/**
* The ONE proxy protocol version represents a version 1 (human-readable) header.
*/
V1(VERSION_ONE_BYTE),
/**
* The TWO proxy protocol version represents a version 2 (binary) header.
*/
V2(VERSION_TWO_BYTE);
/**
* The highest 4 bits of the protocol version and command byte contain the version
*/
private static final byte VERSION_MASK = (byte) 0xf0;
private final byte byteValue;
/**
* Creates a new instance
*/
HAProxyProtocolVersion(byte byteValue) {
this.byteValue = byteValue;
}
/**
* Returns the {@link HAProxyProtocolVersion} represented by the higest 4 bits of the specified byte.
*
* @param verCmdByte protocol version and command byte
*/
public static HAProxyProtocolVersion valueOf(byte verCmdByte) {
int version = verCmdByte & VERSION_MASK;
switch ((byte) version) {
case VERSION_TWO_BYTE:
return V2;
case VERSION_ONE_BYTE:
return V1;
default:
throw new IllegalArgumentException("unknown version: " + version);
}
}
/**
* Returns the byte value of this version.
*/
public byte byteValue() {
return byteValue;
}
} | 1,434 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
HAProxyConstants.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/haproxy/HAProxyConstants.java | package net.rezxis.mctp.client.haproxy;
final class HAProxyConstants {
/**
* Command byte constants
*/
static final byte COMMAND_LOCAL_BYTE = 0x00;
static final byte COMMAND_PROXY_BYTE = 0x01;
/**
* Version byte constants
*/
static final byte VERSION_ONE_BYTE = 0x10;
static final byte VERSION_TWO_BYTE = 0x20;
/**
* Transport protocol byte constants
*/
static final byte TRANSPORT_UNSPEC_BYTE = 0x00;
static final byte TRANSPORT_STREAM_BYTE = 0x01;
static final byte TRANSPORT_DGRAM_BYTE = 0x02;
/**
* Address family byte constants
*/
static final byte AF_UNSPEC_BYTE = 0x00;
static final byte AF_IPV4_BYTE = 0x10;
static final byte AF_IPV6_BYTE = 0x20;
static final byte AF_UNIX_BYTE = 0x30;
/**
* Transport protocol and address family byte constants
*/
static final byte TPAF_UNKNOWN_BYTE = 0x00;
static final byte TPAF_TCP4_BYTE = 0x11;
static final byte TPAF_TCP6_BYTE = 0x21;
static final byte TPAF_UDP4_BYTE = 0x12;
static final byte TPAF_UDP6_BYTE = 0x22;
static final byte TPAF_UNIX_STREAM_BYTE = 0x31;
static final byte TPAF_UNIX_DGRAM_BYTE = 0x32;
private HAProxyConstants() { }
}
| 1,245 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
HAProxyMessageDecoder.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/haproxy/HAProxyMessageDecoder.java | package net.rezxis.mctp.client.haproxy;
/*
* Copyright 2014 The Netty Project
*
* The Netty 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.
*/
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.util.CharsetUtil;
import java.util.List;
/**
* Decodes an HAProxy proxy protocol header
*
* @see <a href="http://haproxy.1wt.eu/download/1.5/doc/proxy-protocol.txt">Proxy Protocol Specification</a>
*/
public class HAProxyMessageDecoder extends ByteToMessageDecoder {
/**
* Maximum possible length of a v1 proxy protocol header per spec
*/
private static final int V1_MAX_LENGTH = 108;
/**
* Maximum possible length of a v2 proxy protocol header (fixed 16 bytes + max unsigned short)
*/
private static final int V2_MAX_LENGTH = 16 + 65535;
/**
* Minimum possible length of a fully functioning v2 proxy protocol header (fixed 16 bytes + v2 address info space)
*/
private static final int V2_MIN_LENGTH = 16 + 216;
/**
* Maximum possible length for v2 additional TLV data (max unsigned short - max v2 address info space)
*/
private static final int V2_MAX_TLV = 65535 - 216;
/**
* Version 1 header delimiter is always '\r\n' per spec
*/
private static final int DELIMITER_LENGTH = 2;
/**
* Binary header prefix
*/
private static final byte[] BINARY_PREFIX = {
(byte) 0x0D,
(byte) 0x0A,
(byte) 0x0D,
(byte) 0x0A,
(byte) 0x00,
(byte) 0x0D,
(byte) 0x0A,
(byte) 0x51,
(byte) 0x55,
(byte) 0x49,
(byte) 0x54,
(byte) 0x0A
};
private static final byte[] TEXT_PREFIX = {
(byte) 'P',
(byte) 'R',
(byte) 'O',
(byte) 'X',
(byte) 'Y',
};
/**
* Binary header prefix length
*/
private static final int BINARY_PREFIX_LENGTH = BINARY_PREFIX.length;
/**
* {@link ProtocolDetectionResult} for {@link HAProxyProtocolVersion#V1}.
*/
private static final ProtocolDetectionResult<HAProxyProtocolVersion> DETECTION_RESULT_V1 =
ProtocolDetectionResult.detected(HAProxyProtocolVersion.V1);
/**
* {@link ProtocolDetectionResult} for {@link HAProxyProtocolVersion#V2}.
*/
private static final ProtocolDetectionResult<HAProxyProtocolVersion> DETECTION_RESULT_V2 =
ProtocolDetectionResult.detected(HAProxyProtocolVersion.V2);
/**
* {@code true} if we're discarding input because we're already over maxLength
*/
private boolean discarding;
/**
* Number of discarded bytes
*/
private int discardedBytes;
/**
* {@code true} if we're finished decoding the proxy protocol header
*/
private boolean finished;
/**
* Protocol specification version
*/
private int version = -1;
/**
* The latest v2 spec (2014/05/18) allows for additional data to be sent in the proxy protocol header beyond the
* address information block so now we need a configurable max header size
*/
private final int v2MaxHeaderSize;
/**
* Creates a new decoder with no additional data (TLV) restrictions
*/
public HAProxyMessageDecoder() {
v2MaxHeaderSize = V2_MAX_LENGTH;
}
/**
* Creates a new decoder with restricted additional data (TLV) size
* <p>
* <b>Note:</b> limiting TLV size only affects processing of v2, binary headers. Also, as allowed by the 1.5 spec
* TLV data is currently ignored. For maximum performance it would be best to configure your upstream proxy host to
* <b>NOT</b> send TLV data and instantiate with a max TLV size of {@code 0}.
* </p>
*
* @param maxTlvSize maximum number of bytes allowed for additional data (Type-Length-Value vectors) in a v2 header
*/
public HAProxyMessageDecoder(int maxTlvSize) {
if (maxTlvSize < 1) {
v2MaxHeaderSize = V2_MIN_LENGTH;
} else if (maxTlvSize > V2_MAX_TLV) {
v2MaxHeaderSize = V2_MAX_LENGTH;
} else {
int calcMax = maxTlvSize + V2_MIN_LENGTH;
if (calcMax > V2_MAX_LENGTH) {
v2MaxHeaderSize = V2_MAX_LENGTH;
} else {
v2MaxHeaderSize = calcMax;
}
}
}
/**
* Returns the proxy protocol specification version in the buffer if the version is found.
* Returns -1 if no version was found in the buffer.
*/
private static int findVersion(final ByteBuf buffer) {
final int n = buffer.readableBytes();
// per spec, the version number is found in the 13th byte
if (n < 13) {
return -1;
}
int idx = buffer.readerIndex();
return match(BINARY_PREFIX, buffer, idx) ? buffer.getByte(idx + BINARY_PREFIX_LENGTH) : 1;
}
/**
* Returns the index in the buffer of the end of header if found.
* Returns -1 if no end of header was found in the buffer.
*/
private static int findEndOfHeader(final ByteBuf buffer) {
final int n = buffer.readableBytes();
// per spec, the 15th and 16th bytes contain the address length in bytes
if (n < 16) {
return -1;
}
int offset = buffer.readerIndex() + 14;
// the total header length will be a fixed 16 byte sequence + the dynamic address information block
int totalHeaderBytes = 16 + buffer.getUnsignedShort(offset);
// ensure we actually have the full header available
if (n >= totalHeaderBytes) {
return totalHeaderBytes;
} else {
return -1;
}
}
/**
* Returns the index in the buffer of the end of line found.
* Returns -1 if no end of line was found in the buffer.
*/
private static int findEndOfLine(final ByteBuf buffer) {
final int n = buffer.writerIndex();
for (int i = buffer.readerIndex(); i < n; i++) {
final byte b = buffer.getByte(i);
if (b == '\r' && i < n - 1 && buffer.getByte(i + 1) == '\n') {
return i; // \r\n
}
}
return -1; // Not found.
}
@Override
public boolean isSingleDecode() {
// ByteToMessageDecoder uses this method to optionally break out of the decoding loop after each unit of work.
// Since we only ever want to decode a single header we always return true to save a bit of work here.
return true;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
super.channelRead(ctx, msg);
if (finished) {
ctx.pipeline().remove(this);
}
}
@Override
protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
// determine the specification version
if (version == -1) {
if ((version = findVersion(in)) == -1) {
return;
}
}
ByteBuf decoded;
if (version == 1) {
decoded = decodeLine(ctx, in);
} else {
decoded = decodeStruct(ctx, in);
}
if (decoded != null) {
finished = true;
try {
if (version == 1) {
out.add(HAProxyMessage.decodeHeader(decoded.toString(CharsetUtil.US_ASCII)));
} else {
out.add(HAProxyMessage.decodeHeader(decoded));
}
} catch (HAProxyProtocolException e) {
fail(ctx, null, e);
}
} else {
ctx.pipeline().remove(this);
}
}
/**
* Create a frame out of the {@link ByteBuf} and return it.
* Based on code from {@link LineBasedFrameDecoder#decode(ChannelHandlerContext, ByteBuf)}.
*
* @param ctx the {@link ChannelHandlerContext} which this {@link HAProxyMessageDecoder} belongs to
* @param buffer the {@link ByteBuf} from which to read data
* @return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could
* be created
*/
private ByteBuf decodeStruct(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
final int eoh = findEndOfHeader(buffer);
if (!discarding) {
if (eoh >= 0) {
final int length = eoh - buffer.readerIndex();
if (length > v2MaxHeaderSize) {
buffer.readerIndex(eoh);
failOverLimit(ctx, length);
return null;
}
return buffer.readSlice(length);
} else {
final int length = buffer.readableBytes();
if (length > v2MaxHeaderSize) {
discardedBytes = length;
buffer.skipBytes(length);
discarding = true;
failOverLimit(ctx, "over " + discardedBytes);
}
return null;
}
} else {
if (eoh >= 0) {
buffer.readerIndex(eoh);
discardedBytes = 0;
discarding = false;
} else {
discardedBytes = buffer.readableBytes();
buffer.skipBytes(discardedBytes);
}
return null;
}
}
/**
* Create a frame out of the {@link ByteBuf} and return it.
* Based on code from {@link LineBasedFrameDecoder#decode(ChannelHandlerContext, ByteBuf)}.
*
* @param ctx the {@link ChannelHandlerContext} which this {@link HAProxyMessageDecoder} belongs to
* @param buffer the {@link ByteBuf} from which to read data
* @return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could
* be created
*/
private ByteBuf decodeLine(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
final int eol = findEndOfLine(buffer);
if (!discarding) {
if (eol >= 0) {
final int length = eol - buffer.readerIndex();
if (length > V1_MAX_LENGTH) {
buffer.readerIndex(eol + DELIMITER_LENGTH);
failOverLimit(ctx, length);
return null;
}
ByteBuf frame = buffer.readSlice(length);
buffer.skipBytes(DELIMITER_LENGTH);
return frame;
} else {
final int length = buffer.readableBytes();
if (length > V1_MAX_LENGTH) {
discardedBytes = length;
buffer.skipBytes(length);
discarding = true;
failOverLimit(ctx, "over " + discardedBytes);
}
return null;
}
} else {
if (eol >= 0) {
final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;
buffer.readerIndex(eol + delimLength);
discardedBytes = 0;
discarding = false;
} else {
discardedBytes = buffer.readableBytes();
buffer.skipBytes(discardedBytes);
}
return null;
}
}
private void failOverLimit(final ChannelHandlerContext ctx, int length) {
failOverLimit(ctx, String.valueOf(length));
}
private void failOverLimit(final ChannelHandlerContext ctx, String length) {
int maxLength = version == 1 ? V1_MAX_LENGTH : v2MaxHeaderSize;
fail(ctx, "header length (" + length + ") exceeds the allowed maximum (" + maxLength + ')', null);
}
private void fail(final ChannelHandlerContext ctx, String errMsg, Throwable t) {
finished = true;
ctx.close(); // drop connection immediately per spec
HAProxyProtocolException ppex;
if (errMsg != null && t != null) {
ppex = new HAProxyProtocolException(errMsg, t);
} else if (errMsg != null) {
ppex = new HAProxyProtocolException(errMsg);
} else if (t != null) {
ppex = new HAProxyProtocolException(t);
} else {
ppex = new HAProxyProtocolException();
}
throw ppex;
}
/**
* Returns the {@link ProtocolDetectionResult} for the given {@link ByteBuf}.
*/
public static ProtocolDetectionResult<HAProxyProtocolVersion> detectProtocol(ByteBuf buffer) {
if (buffer.readableBytes() < 12) {
return ProtocolDetectionResult.needsMoreData();
}
int idx = buffer.readerIndex();
if (match(BINARY_PREFIX, buffer, idx)) {
return DETECTION_RESULT_V2;
}
if (match(TEXT_PREFIX, buffer, idx)) {
return DETECTION_RESULT_V1;
}
return ProtocolDetectionResult.invalid();
}
private static boolean match(byte[] prefix, ByteBuf buffer, int idx) {
for (int i = 0; i < prefix.length; i++) {
final byte b = buffer.getByte(idx + i);
if (b != prefix[i]) {
return false;
}
}
return true;
}
} | 13,973 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
ProtocolDetectionState.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/haproxy/ProtocolDetectionState.java | package net.rezxis.mctp.client.haproxy;
public enum ProtocolDetectionState {
/**
* Need more data to detect the protocol.
*/
NEEDS_MORE_DATA,
/**
* The data was invalid.
*/
INVALID,
/**
* Protocol was detected,
*/
DETECTED
} | 281 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
ProtocolDetectionResult.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/haproxy/ProtocolDetectionResult.java | package net.rezxis.mctp.client.haproxy;
/**
* Result of detecting a protocol.
*
* @param <T> the type of the protocol
*/
public final class ProtocolDetectionResult<T> {
@SuppressWarnings({ "rawtypes", "unchecked" })
private static final ProtocolDetectionResult NEEDS_MORE_DATE =
new ProtocolDetectionResult(ProtocolDetectionState.NEEDS_MORE_DATA, null);
@SuppressWarnings({ "rawtypes", "unchecked" })
private static final ProtocolDetectionResult INVALID =
new ProtocolDetectionResult(ProtocolDetectionState.INVALID, null);
private final ProtocolDetectionState state;
private final T result;
/**
* Returns a {@link ProtocolDetectionResult} that signals that more data is needed to detect the protocol.
*/
@SuppressWarnings("unchecked")
public static <T> ProtocolDetectionResult<T> needsMoreData() {
return NEEDS_MORE_DATE;
}
/**
* Returns a {@link ProtocolDetectionResult} that signals the data was invalid for the protocol.
*/
@SuppressWarnings("unchecked")
public static <T> ProtocolDetectionResult<T> invalid() {
return INVALID;
}
/**
* Returns a {@link ProtocolDetectionResult} which holds the detected protocol.
*/
public static <T> ProtocolDetectionResult<T> detected(T protocol) {
return new ProtocolDetectionResult<T>(ProtocolDetectionState.DETECTED, checkNotNull(protocol, "protocol"));
}
private ProtocolDetectionResult(ProtocolDetectionState state, T result) {
this.state = state;
this.result = result;
}
/**
* Return the {@link ProtocolDetectionState}. If the state is {@link ProtocolDetectionState#DETECTED} you
* can retrieve the protocol via {@link #detectedProtocol()}.
*/
public ProtocolDetectionState state() {
return state;
}
/**
* Returns the protocol if {@link #state()} returns {@link ProtocolDetectionState#DETECTED}, otherwise {@code null}.
*/
public T detectedProtocol() {
return result;
}
public static <T> T checkNotNull(T arg, String text) {
if (arg == null) {
throw new NullPointerException(text);
}
return arg;
}
}
| 2,241 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
HAProxyProxiedProtocol.java | /FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/haproxy/HAProxyProxiedProtocol.java | package net.rezxis.mctp.client.haproxy;
/*
* Copyright 2014 The Netty Project
*
* The Netty 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.
*/
import static net.rezxis.mctp.client.haproxy.HAProxyConstants.*;
/**
* A protocol proxied by HAProxy which is represented by its transport protocol and address family.
*/
public enum HAProxyProxiedProtocol {
/**
* The UNKNOWN represents a connection which was forwarded for an unknown protocol and an unknown address family.
*/
UNKNOWN(TPAF_UNKNOWN_BYTE, AddressFamily.AF_UNSPEC, TransportProtocol.UNSPEC),
/**
* The TCP4 represents a connection which was forwarded for an IPv4 client over TCP.
*/
TCP4(TPAF_TCP4_BYTE, AddressFamily.AF_IPv4, TransportProtocol.STREAM),
/**
* The TCP6 represents a connection which was forwarded for an IPv6 client over TCP.
*/
TCP6(TPAF_TCP6_BYTE, AddressFamily.AF_IPv6, TransportProtocol.STREAM),
/**
* The UDP4 represents a connection which was forwarded for an IPv4 client over UDP.
*/
UDP4(TPAF_UDP4_BYTE, AddressFamily.AF_IPv4, TransportProtocol.DGRAM),
/**
* The UDP6 represents a connection which was forwarded for an IPv6 client over UDP.
*/
UDP6(TPAF_UDP6_BYTE, AddressFamily.AF_IPv6, TransportProtocol.DGRAM),
/**
* The UNIX_STREAM represents a connection which was forwarded for a UNIX stream socket.
*/
UNIX_STREAM(TPAF_UNIX_STREAM_BYTE, AddressFamily.AF_UNIX, TransportProtocol.STREAM),
/**
* The UNIX_DGRAM represents a connection which was forwarded for a UNIX datagram socket.
*/
UNIX_DGRAM(TPAF_UNIX_DGRAM_BYTE, AddressFamily.AF_UNIX, TransportProtocol.DGRAM);
private final byte byteValue;
private final AddressFamily addressFamily;
private final TransportProtocol transportProtocol;
/**
* Creates a new instance.
*/
HAProxyProxiedProtocol(
byte byteValue,
AddressFamily addressFamily,
TransportProtocol transportProtocol) {
this.byteValue = byteValue;
this.addressFamily = addressFamily;
this.transportProtocol = transportProtocol;
}
/**
* Returns the {@link HAProxyProxiedProtocol} represented by the specified byte.
*
* @param tpafByte transport protocol and address family byte
*/
public static HAProxyProxiedProtocol valueOf(byte tpafByte) {
switch (tpafByte) {
case TPAF_TCP4_BYTE:
return TCP4;
case TPAF_TCP6_BYTE:
return TCP6;
case TPAF_UNKNOWN_BYTE:
return UNKNOWN;
case TPAF_UDP4_BYTE:
return UDP4;
case TPAF_UDP6_BYTE:
return UDP6;
case TPAF_UNIX_STREAM_BYTE:
return UNIX_STREAM;
case TPAF_UNIX_DGRAM_BYTE:
return UNIX_DGRAM;
default:
throw new IllegalArgumentException(
"unknown transport protocol + address family: " + (tpafByte & 0xFF));
}
}
/**
* Returns the byte value of this protocol and address family.
*/
public byte byteValue() {
return byteValue;
}
/**
* Returns the {@link AddressFamily} of this protocol and address family.
*/
public AddressFamily addressFamily() {
return addressFamily;
}
/**
* Returns the {@link TransportProtocol} of this protocol and address family.
*/
public TransportProtocol transportProtocol() {
return transportProtocol;
}
/**
* The address family of an HAProxy proxy protocol header.
*/
public enum AddressFamily {
/**
* The UNSPECIFIED address family represents a connection which was forwarded for an unkown protocol.
*/
AF_UNSPEC(AF_UNSPEC_BYTE),
/**
* The IPV4 address family represents a connection which was forwarded for an IPV4 client.
*/
AF_IPv4(AF_IPV4_BYTE),
/**
* The IPV6 address family represents a connection which was forwarded for an IPV6 client.
*/
AF_IPv6(AF_IPV6_BYTE),
/**
* The UNIX address family represents a connection which was forwarded for a unix socket.
*/
AF_UNIX(AF_UNIX_BYTE);
/**
* The highest 4 bits of the transport protocol and address family byte contain the address family
*/
private static final byte FAMILY_MASK = (byte) 0xf0;
private final byte byteValue;
/**
* Creates a new instance
*/
AddressFamily(byte byteValue) {
this.byteValue = byteValue;
}
/**
* Returns the {@link AddressFamily} represented by the highest 4 bits of the specified byte.
*
* @param tpafByte transport protocol and address family byte
*/
public static AddressFamily valueOf(byte tpafByte) {
int addressFamily = tpafByte & FAMILY_MASK;
switch((byte) addressFamily) {
case AF_IPV4_BYTE:
return AF_IPv4;
case AF_IPV6_BYTE:
return AF_IPv6;
case AF_UNSPEC_BYTE:
return AF_UNSPEC;
case AF_UNIX_BYTE:
return AF_UNIX;
default:
throw new IllegalArgumentException("unknown address family: " + addressFamily);
}
}
/**
* Returns the byte value of this address family.
*/
public byte byteValue() {
return byteValue;
}
}
/**
* The transport protocol of an HAProxy proxy protocol header
*/
public enum TransportProtocol {
/**
* The UNSPEC transport protocol represents a connection which was forwarded for an unkown protocol.
*/
UNSPEC(TRANSPORT_UNSPEC_BYTE),
/**
* The STREAM transport protocol represents a connection which was forwarded for a TCP connection.
*/
STREAM(TRANSPORT_STREAM_BYTE),
/**
* The DGRAM transport protocol represents a connection which was forwarded for a UDP connection.
*/
DGRAM(TRANSPORT_DGRAM_BYTE);
/**
* The transport protocol is specified in the lowest 4 bits of the transport protocol and address family byte
*/
private static final byte TRANSPORT_MASK = 0x0f;
private final byte transportByte;
/**
* Creates a new instance.
*/
TransportProtocol(byte transportByte) {
this.transportByte = transportByte;
}
/**
* Returns the {@link TransportProtocol} represented by the lowest 4 bits of the specified byte.
*
* @param tpafByte transport protocol and address family byte
*/
public static TransportProtocol valueOf(byte tpafByte) {
int transportProtocol = tpafByte & TRANSPORT_MASK;
switch ((byte) transportProtocol) {
case TRANSPORT_STREAM_BYTE:
return STREAM;
case TRANSPORT_UNSPEC_BYTE:
return UNSPEC;
case TRANSPORT_DGRAM_BYTE:
return DGRAM;
default:
throw new IllegalArgumentException("unknown transport protocol: " + transportProtocol);
}
}
/**
* Returns the byte value of this transport protocol.
*/
public byte byteValue() {
return transportByte;
}
}
} | 8,195 | Java | .java | RezxisNetwork/MinecraftTransport-Client | 9 | 4 | 1 | 2020-12-23T08:32:18Z | 2021-07-31T14:09:19Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.