repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
docbleach/DocBleach | module/module-pdf/src/test/java/xyz/docbleach/module/pdf/PDDocumentCatalogBleachTest.java | // Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
//
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
| import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static xyz.docbleach.api.BleachTestBase.assertThreatsFound;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;
import org.apache.pdfbox.pdmodel.interactive.action.PDDocumentCatalogAdditionalActions;
import org.apache.pdfbox.pdmodel.interactive.action.PDFormFieldAdditionalActions;
import org.apache.pdfbox.pdmodel.interactive.action.PDPageAdditionalActions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession; | package xyz.docbleach.module.pdf;
class PDDocumentCatalogBleachTest {
private BleachSession session;
private PDDocumentCatalogBleach instance;
@BeforeEach
void setUp() {
session = mock(BleachSession.class);
instance = new PDDocumentCatalogBleach(new PdfBleachSession(session));
}
@Test
void sanitizeAcroFormActions() {
PDFormFieldAdditionalActions fieldActions = new PDFormFieldAdditionalActions();
fieldActions.setC(new PDActionJavaScript());
fieldActions.setF(new PDActionJavaScript());
fieldActions.setK(new PDActionJavaScript());
fieldActions.setV(new PDActionJavaScript());
instance.sanitizeFieldAdditionalActions(fieldActions); | // Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
//
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
// Path: module/module-pdf/src/test/java/xyz/docbleach/module/pdf/PDDocumentCatalogBleachTest.java
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static xyz.docbleach.api.BleachTestBase.assertThreatsFound;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;
import org.apache.pdfbox.pdmodel.interactive.action.PDDocumentCatalogAdditionalActions;
import org.apache.pdfbox.pdmodel.interactive.action.PDFormFieldAdditionalActions;
import org.apache.pdfbox.pdmodel.interactive.action.PDPageAdditionalActions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
package xyz.docbleach.module.pdf;
class PDDocumentCatalogBleachTest {
private BleachSession session;
private PDDocumentCatalogBleach instance;
@BeforeEach
void setUp() {
session = mock(BleachSession.class);
instance = new PDDocumentCatalogBleach(new PdfBleachSession(session));
}
@Test
void sanitizeAcroFormActions() {
PDFormFieldAdditionalActions fieldActions = new PDFormFieldAdditionalActions();
fieldActions.setC(new PDActionJavaScript());
fieldActions.setF(new PDActionJavaScript());
fieldActions.setK(new PDActionJavaScript());
fieldActions.setV(new PDActionJavaScript());
instance.sanitizeFieldAdditionalActions(fieldActions); | assertThreatsFound(session, 4); |
docbleach/DocBleach | module/module-pdf/src/test/java/xyz/docbleach/module/pdf/PDAnnotationBleachTest.java | // Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
//
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
| import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static xyz.docbleach.api.BleachTestBase.assertThreatsFound;
import java.lang.reflect.Method;
import org.apache.pdfbox.pdmodel.interactive.action.PDAction;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;
import org.apache.pdfbox.pdmodel.interactive.action.PDAnnotationAdditionalActions;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession; | package xyz.docbleach.module.pdf;
class PDAnnotationBleachTest {
private BleachSession session;
private PDAnnotationBleach instance;
@BeforeEach
void setUp() {
session = mock(BleachSession.class);
instance = new PDAnnotationBleach(new PdfBleachSession(session));
}
@Test
void sanitizeAnnotationLink() {
PDAnnotationLink annotationLink = new PDAnnotationLink();
annotationLink.setAction(new PDActionJavaScript());
instance.sanitizeLinkAnnotation(annotationLink);
| // Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
//
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
// Path: module/module-pdf/src/test/java/xyz/docbleach/module/pdf/PDAnnotationBleachTest.java
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static xyz.docbleach.api.BleachTestBase.assertThreatsFound;
import java.lang.reflect.Method;
import org.apache.pdfbox.pdmodel.interactive.action.PDAction;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;
import org.apache.pdfbox.pdmodel.interactive.action.PDAnnotationAdditionalActions;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
package xyz.docbleach.module.pdf;
class PDAnnotationBleachTest {
private BleachSession session;
private PDAnnotationBleach instance;
@BeforeEach
void setUp() {
session = mock(BleachSession.class);
instance = new PDAnnotationBleach(new PdfBleachSession(session));
}
@Test
void sanitizeAnnotationLink() {
PDAnnotationLink annotationLink = new PDAnnotationLink();
annotationLink.setAction(new PDActionJavaScript());
instance.sanitizeLinkAnnotation(annotationLink);
| assertThreatsFound(session, 1); |
docbleach/DocBleach | module/module-office/src/test/java/xyz/docbleach/module/ole2/MacroRemoverTest.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public abstract class BleachTestBase {
//
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
// }
| import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.Entry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.BleachTestBase; | package xyz.docbleach.module.ole2;
class MacroRemoverTest {
private MacroRemover instance; | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public abstract class BleachTestBase {
//
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
// }
// Path: module/module-office/src/test/java/xyz/docbleach/module/ole2/MacroRemoverTest.java
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.Entry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.BleachTestBase;
package xyz.docbleach.module.ole2;
class MacroRemoverTest {
private MacroRemover instance; | private BleachSession session; |
docbleach/DocBleach | module/module-office/src/test/java/xyz/docbleach/module/ole2/MacroRemoverTest.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public abstract class BleachTestBase {
//
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
// }
| import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.Entry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.BleachTestBase; | package xyz.docbleach.module.ole2;
class MacroRemoverTest {
private MacroRemover instance;
private BleachSession session;
@BeforeEach
void setUp() {
session = mock(BleachSession.class);
instance = spy(new MacroRemover(session));
}
@Test
void testRemovesMacro() {
Entry entry = mock(Entry.class);
doReturn("_VBA_PROJECT_CUR").when(entry).getName();
assertFalse(instance.test(entry), "A macro entry should not be copied over"); | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public abstract class BleachTestBase {
//
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
// }
// Path: module/module-office/src/test/java/xyz/docbleach/module/ole2/MacroRemoverTest.java
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.Entry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.BleachTestBase;
package xyz.docbleach.module.ole2;
class MacroRemoverTest {
private MacroRemover instance;
private BleachSession session;
@BeforeEach
void setUp() {
session = mock(BleachSession.class);
instance = spy(new MacroRemover(session));
}
@Test
void testRemovesMacro() {
Entry entry = mock(Entry.class);
doReturn("_VBA_PROJECT_CUR").when(entry).getName();
assertFalse(instance.test(entry), "A macro entry should not be copied over"); | BleachTestBase.assertThreatsFound(session, 1); |
docbleach/DocBleach | module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PdfBleachSession.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.io.ScratchFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.pdf;
class PdfBleachSession {
private static final Logger LOGGER = LoggerFactory.getLogger(PdfBleachSession.class);
private static final String[] COMMON_PASSWORDS =
new String[]{null, "", "test", "example", "sample", "malware", "infected", "password"};
private static final MemoryUsageSetting MEMORY_USAGE_SETTING =
MemoryUsageSetting.setupMixed(1024 * 100);
| // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PdfBleachSession.java
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.io.ScratchFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.pdf;
class PdfBleachSession {
private static final Logger LOGGER = LoggerFactory.getLogger(PdfBleachSession.class);
private static final String[] COMMON_PASSWORDS =
new String[]{null, "", "test", "example", "sample", "malware", "infected", "password"};
private static final MemoryUsageSetting MEMORY_USAGE_SETTING =
MemoryUsageSetting.setupMixed(1024 * 100);
| private final BleachSession session; |
docbleach/DocBleach | module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PdfBleachSession.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.io.ScratchFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.pdf;
class PdfBleachSession {
private static final Logger LOGGER = LoggerFactory.getLogger(PdfBleachSession.class);
private static final String[] COMMON_PASSWORDS =
new String[]{null, "", "test", "example", "sample", "malware", "infected", "password"};
private static final MemoryUsageSetting MEMORY_USAGE_SETTING =
MemoryUsageSetting.setupMixed(1024 * 100);
private final BleachSession session;
private final COSObjectBleach cosObjectBleach;
PdfBleachSession(BleachSession session) {
this.session = session;
cosObjectBleach = new COSObjectBleach(this);
}
void sanitize(RandomAccessRead source, OutputStream outputStream) | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PdfBleachSession.java
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.io.ScratchFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.pdf;
class PdfBleachSession {
private static final Logger LOGGER = LoggerFactory.getLogger(PdfBleachSession.class);
private static final String[] COMMON_PASSWORDS =
new String[]{null, "", "test", "example", "sample", "malware", "infected", "password"};
private static final MemoryUsageSetting MEMORY_USAGE_SETTING =
MemoryUsageSetting.setupMixed(1024 * 100);
private final BleachSession session;
private final COSObjectBleach cosObjectBleach;
PdfBleachSession(BleachSession session) {
this.session = session;
cosObjectBleach = new COSObjectBleach(this);
}
void sanitize(RandomAccessRead source, OutputStream outputStream) | throws IOException, BleachException { |
docbleach/DocBleach | http_server/src/main/java/xyz/docbleach/http_server/Main.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/DefaultBleach.java
// public class DefaultBleach extends CompositeBleach {
//
// public DefaultBleach() {
// super(getDefaultBleaches());
// }
//
// /**
// * Finds all statically loadable bleaches
// *
// * @return ordered list of statically loadable bleaches
// */
// private static Bleach[] getDefaultBleaches() {
// ServiceLoader<Bleach> services = ServiceLoader.load(Bleach.class);
//
// Collection<Bleach> list = new ArrayList<>();
// services.forEach(list::add);
//
// return list.toArray(new Bleach[0]);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
| import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.DefaultBleach;
import xyz.docbleach.api.exception.BleachException; | public void start() {
HttpServer server = vertx.createHttpServer();
Router router = Router.router(vertx);
router.route().handler(BodyHandler.create().setBodyLimit(BODY_LIMIT));
router
.post("/sanitize")
.handler(
routingContext -> {
Set<FileUpload> uploads = routingContext.fileUploads();
if (uploads.isEmpty()) {
routingContext.fail(404);
return;
}
for (FileUpload upload : uploads) {
LOGGER.info("FileName: {}", upload.fileName());
if (!"file".equals(upload.name())) {
removeFiles(new File(upload.uploadedFileName()));
continue;
}
// @TODO: split into multiple methods
LOGGER.info("UploadedFileName: {}", upload.fileName());
vertx.executeBlocking(
(Handler<Promise<File>>)
promise -> {
try {
promise.complete(sanitize(upload.uploadedFileName())); | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/DefaultBleach.java
// public class DefaultBleach extends CompositeBleach {
//
// public DefaultBleach() {
// super(getDefaultBleaches());
// }
//
// /**
// * Finds all statically loadable bleaches
// *
// * @return ordered list of statically loadable bleaches
// */
// private static Bleach[] getDefaultBleaches() {
// ServiceLoader<Bleach> services = ServiceLoader.load(Bleach.class);
//
// Collection<Bleach> list = new ArrayList<>();
// services.forEach(list::add);
//
// return list.toArray(new Bleach[0]);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
// Path: http_server/src/main/java/xyz/docbleach/http_server/Main.java
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.DefaultBleach;
import xyz.docbleach.api.exception.BleachException;
public void start() {
HttpServer server = vertx.createHttpServer();
Router router = Router.router(vertx);
router.route().handler(BodyHandler.create().setBodyLimit(BODY_LIMIT));
router
.post("/sanitize")
.handler(
routingContext -> {
Set<FileUpload> uploads = routingContext.fileUploads();
if (uploads.isEmpty()) {
routingContext.fail(404);
return;
}
for (FileUpload upload : uploads) {
LOGGER.info("FileName: {}", upload.fileName());
if (!"file".equals(upload.name())) {
removeFiles(new File(upload.uploadedFileName()));
continue;
}
// @TODO: split into multiple methods
LOGGER.info("UploadedFileName: {}", upload.fileName());
vertx.executeBlocking(
(Handler<Promise<File>>)
promise -> {
try {
promise.complete(sanitize(upload.uploadedFileName())); | } catch (IOException | BleachException e) { |
docbleach/DocBleach | http_server/src/main/java/xyz/docbleach/http_server/Main.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/DefaultBleach.java
// public class DefaultBleach extends CompositeBleach {
//
// public DefaultBleach() {
// super(getDefaultBleaches());
// }
//
// /**
// * Finds all statically loadable bleaches
// *
// * @return ordered list of statically loadable bleaches
// */
// private static Bleach[] getDefaultBleaches() {
// ServiceLoader<Bleach> services = ServiceLoader.load(Bleach.class);
//
// Collection<Bleach> list = new ArrayList<>();
// services.forEach(list::add);
//
// return list.toArray(new Bleach[0]);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
| import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.DefaultBleach;
import xyz.docbleach.api.exception.BleachException; |
private void sendFile(RoutingContext routingContext, String fileName, File saneFile) {
HttpServerResponse response = routingContext.response();
response.putHeader("Content-Description", "File Transfer");
response.putHeader("Content-Type", "application/octet-stream");
response.putHeader(
"Content-Disposition", "attachment; filename=" + fileName); // @TODO: don't trust this name?
response.putHeader("Content-Transfer-Encoding", "binary");
response.putHeader("Expires", "0");
response.putHeader("Pragma", "Public");
response.putHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.putHeader("Content-Length", "" + saneFile.length());
response.sendFile(saneFile.getAbsolutePath());
}
private void removeFiles(File... files) {
vertx.executeBlocking(
promise -> {
for (File f : files) {
if (!f.delete()) {
LOGGER.warn("Could not delete file{} ", f.getAbsolutePath());
}
}
},
__ -> {
});
}
private File sanitize(String uploadedFileName) throws IOException, BleachException { | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/DefaultBleach.java
// public class DefaultBleach extends CompositeBleach {
//
// public DefaultBleach() {
// super(getDefaultBleaches());
// }
//
// /**
// * Finds all statically loadable bleaches
// *
// * @return ordered list of statically loadable bleaches
// */
// private static Bleach[] getDefaultBleaches() {
// ServiceLoader<Bleach> services = ServiceLoader.load(Bleach.class);
//
// Collection<Bleach> list = new ArrayList<>();
// services.forEach(list::add);
//
// return list.toArray(new Bleach[0]);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
// Path: http_server/src/main/java/xyz/docbleach/http_server/Main.java
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.DefaultBleach;
import xyz.docbleach.api.exception.BleachException;
private void sendFile(RoutingContext routingContext, String fileName, File saneFile) {
HttpServerResponse response = routingContext.response();
response.putHeader("Content-Description", "File Transfer");
response.putHeader("Content-Type", "application/octet-stream");
response.putHeader(
"Content-Disposition", "attachment; filename=" + fileName); // @TODO: don't trust this name?
response.putHeader("Content-Transfer-Encoding", "binary");
response.putHeader("Expires", "0");
response.putHeader("Pragma", "Public");
response.putHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.putHeader("Content-Length", "" + saneFile.length());
response.sendFile(saneFile.getAbsolutePath());
}
private void removeFiles(File... files) {
vertx.executeBlocking(
promise -> {
for (File f : files) {
if (!f.delete()) {
LOGGER.warn("Could not delete file{} ", f.getAbsolutePath());
}
}
},
__ -> {
});
}
private File sanitize(String uploadedFileName) throws IOException, BleachException { | BleachSession session = new BleachSession(new DefaultBleach()); |
docbleach/DocBleach | http_server/src/main/java/xyz/docbleach/http_server/Main.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/DefaultBleach.java
// public class DefaultBleach extends CompositeBleach {
//
// public DefaultBleach() {
// super(getDefaultBleaches());
// }
//
// /**
// * Finds all statically loadable bleaches
// *
// * @return ordered list of statically loadable bleaches
// */
// private static Bleach[] getDefaultBleaches() {
// ServiceLoader<Bleach> services = ServiceLoader.load(Bleach.class);
//
// Collection<Bleach> list = new ArrayList<>();
// services.forEach(list::add);
//
// return list.toArray(new Bleach[0]);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
| import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.DefaultBleach;
import xyz.docbleach.api.exception.BleachException; |
private void sendFile(RoutingContext routingContext, String fileName, File saneFile) {
HttpServerResponse response = routingContext.response();
response.putHeader("Content-Description", "File Transfer");
response.putHeader("Content-Type", "application/octet-stream");
response.putHeader(
"Content-Disposition", "attachment; filename=" + fileName); // @TODO: don't trust this name?
response.putHeader("Content-Transfer-Encoding", "binary");
response.putHeader("Expires", "0");
response.putHeader("Pragma", "Public");
response.putHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.putHeader("Content-Length", "" + saneFile.length());
response.sendFile(saneFile.getAbsolutePath());
}
private void removeFiles(File... files) {
vertx.executeBlocking(
promise -> {
for (File f : files) {
if (!f.delete()) {
LOGGER.warn("Could not delete file{} ", f.getAbsolutePath());
}
}
},
__ -> {
});
}
private File sanitize(String uploadedFileName) throws IOException, BleachException { | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/DefaultBleach.java
// public class DefaultBleach extends CompositeBleach {
//
// public DefaultBleach() {
// super(getDefaultBleaches());
// }
//
// /**
// * Finds all statically loadable bleaches
// *
// * @return ordered list of statically loadable bleaches
// */
// private static Bleach[] getDefaultBleaches() {
// ServiceLoader<Bleach> services = ServiceLoader.load(Bleach.class);
//
// Collection<Bleach> list = new ArrayList<>();
// services.forEach(list::add);
//
// return list.toArray(new Bleach[0]);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
// Path: http_server/src/main/java/xyz/docbleach/http_server/Main.java
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.DefaultBleach;
import xyz.docbleach.api.exception.BleachException;
private void sendFile(RoutingContext routingContext, String fileName, File saneFile) {
HttpServerResponse response = routingContext.response();
response.putHeader("Content-Description", "File Transfer");
response.putHeader("Content-Type", "application/octet-stream");
response.putHeader(
"Content-Disposition", "attachment; filename=" + fileName); // @TODO: don't trust this name?
response.putHeader("Content-Transfer-Encoding", "binary");
response.putHeader("Expires", "0");
response.putHeader("Pragma", "Public");
response.putHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.putHeader("Content-Length", "" + saneFile.length());
response.sendFile(saneFile.getAbsolutePath());
}
private void removeFiles(File... files) {
vertx.executeBlocking(
promise -> {
for (File f : files) {
if (!f.delete()) {
LOGGER.warn("Could not delete file{} ", f.getAbsolutePath());
}
}
},
__ -> {
});
}
private File sanitize(String uploadedFileName) throws IOException, BleachException { | BleachSession session = new BleachSession(new DefaultBleach()); |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/MacroRemover.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.ole2;
public class MacroRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(MacroRemover.class);
private static final String VBA_ENTRY = "VBA";
private static final String MACRO_ENTRY = "Macros";
| // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/MacroRemover.java
import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.ole2;
public class MacroRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(MacroRemover.class);
private static final String VBA_ENTRY = "VBA";
private static final String MACRO_ENTRY = "Macros";
| public MacroRemover(BleachSession session) { |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/MacroRemover.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.ole2;
public class MacroRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(MacroRemover.class);
private static final String VBA_ENTRY = "VBA";
private static final String MACRO_ENTRY = "Macros";
public MacroRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
// Matches _VBA_PROJECT_CUR, VBA, ... :)
if (!isMacro(entryName)) {
return true;
}
LOGGER.info("Found Macros, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Macros' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
| // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/MacroRemover.java
import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.ole2;
public class MacroRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(MacroRemover.class);
private static final String VBA_ENTRY = "VBA";
private static final String MACRO_ENTRY = "Macros";
public MacroRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
// Matches _VBA_PROJECT_CUR, VBA, ... :)
if (!isMacro(entryName)) {
return true;
}
LOGGER.info("Found Macros, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Macros' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
| Threat threat = Threat.builder() |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/MacroRemover.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.ole2;
public class MacroRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(MacroRemover.class);
private static final String VBA_ENTRY = "VBA";
private static final String MACRO_ENTRY = "Macros";
public MacroRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
// Matches _VBA_PROJECT_CUR, VBA, ... :)
if (!isMacro(entryName)) {
return true;
}
LOGGER.info("Found Macros, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Macros' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
Threat threat = Threat.builder() | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/MacroRemover.java
import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.ole2;
public class MacroRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(MacroRemover.class);
private static final String VBA_ENTRY = "VBA";
private static final String MACRO_ENTRY = "Macros";
public MacroRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
// Matches _VBA_PROJECT_CUR, VBA, ... :)
if (!isMacro(entryName)) {
return true;
}
LOGGER.info("Found Macros, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Macros' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
Threat threat = Threat.builder() | .type(ThreatType.ACTIVE_CONTENT) |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/MacroRemover.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.ole2;
public class MacroRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(MacroRemover.class);
private static final String VBA_ENTRY = "VBA";
private static final String MACRO_ENTRY = "Macros";
public MacroRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
// Matches _VBA_PROJECT_CUR, VBA, ... :)
if (!isMacro(entryName)) {
return true;
}
LOGGER.info("Found Macros, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Macros' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
Threat threat = Threat.builder()
.type(ThreatType.ACTIVE_CONTENT) | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/MacroRemover.java
import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.ole2;
public class MacroRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(MacroRemover.class);
private static final String VBA_ENTRY = "VBA";
private static final String MACRO_ENTRY = "Macros";
public MacroRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
// Matches _VBA_PROJECT_CUR, VBA, ... :)
if (!isMacro(entryName)) {
return true;
}
LOGGER.info("Found Macros, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Macros' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
Threat threat = Threat.builder()
.type(ThreatType.ACTIVE_CONTENT) | .severity(ThreatSeverity.EXTREME) |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/MacroRemover.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.ole2;
public class MacroRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(MacroRemover.class);
private static final String VBA_ENTRY = "VBA";
private static final String MACRO_ENTRY = "Macros";
public MacroRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
// Matches _VBA_PROJECT_CUR, VBA, ... :)
if (!isMacro(entryName)) {
return true;
}
LOGGER.info("Found Macros, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Macros' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
Threat threat = Threat.builder()
.type(ThreatType.ACTIVE_CONTENT)
.severity(ThreatSeverity.EXTREME) | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/MacroRemover.java
import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.ole2;
public class MacroRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(MacroRemover.class);
private static final String VBA_ENTRY = "VBA";
private static final String MACRO_ENTRY = "Macros";
public MacroRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
// Matches _VBA_PROJECT_CUR, VBA, ... :)
if (!isMacro(entryName)) {
return true;
}
LOGGER.info("Found Macros, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Macros' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
Threat threat = Threat.builder()
.type(ThreatType.ACTIVE_CONTENT)
.severity(ThreatSeverity.EXTREME) | .action(ThreatAction.REMOVE) |
docbleach/DocBleach | cli/src/main/java/xyz/docbleach/cli/Main.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/DefaultBleach.java
// public class DefaultBleach extends CompositeBleach {
//
// public DefaultBleach() {
// super(getDefaultBleaches());
// }
//
// /**
// * Finds all statically loadable bleaches
// *
// * @return ordered list of statically loadable bleaches
// */
// private static Bleach[] getDefaultBleaches() {
// ServiceLoader<Bleach> services = ServiceLoader.load(Bleach.class);
//
// Collection<Bleach> list = new ArrayList<>();
// services.forEach(list::add);
//
// return list.toArray(new Bleach[0]);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
| import com.google.gson.Gson;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.SimpleLogger;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.DefaultBleach;
import xyz.docbleach.api.exception.BleachException; | package xyz.docbleach.cli;
@SuppressFBWarnings(value = "DM_EXIT", justification = "Used as an app, an exit code is expected")
public class Main {
private static Logger LOGGER = null;
private int verbosityLevel = 0;
private InputStream inputStream;
private OutputStream outputStream;
private boolean jsonOutput;
private Main() {
// Prevent instantiation from the outside worlds
}
public static void main(String[] args) throws IOException, ParseException {
// Set the security manager, preventing commands/network interactions.
System.setSecurityManager(new UnsafeSecurityManager());
// Hide macOS' Java icon in Dock
System.setProperty("java.awt.headless", "true");
Main main = new Main();
main.parseArguments(args);
try {
main.sanitize(); | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/DefaultBleach.java
// public class DefaultBleach extends CompositeBleach {
//
// public DefaultBleach() {
// super(getDefaultBleaches());
// }
//
// /**
// * Finds all statically loadable bleaches
// *
// * @return ordered list of statically loadable bleaches
// */
// private static Bleach[] getDefaultBleaches() {
// ServiceLoader<Bleach> services = ServiceLoader.load(Bleach.class);
//
// Collection<Bleach> list = new ArrayList<>();
// services.forEach(list::add);
//
// return list.toArray(new Bleach[0]);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
// Path: cli/src/main/java/xyz/docbleach/cli/Main.java
import com.google.gson.Gson;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.SimpleLogger;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.DefaultBleach;
import xyz.docbleach.api.exception.BleachException;
package xyz.docbleach.cli;
@SuppressFBWarnings(value = "DM_EXIT", justification = "Used as an app, an exit code is expected")
public class Main {
private static Logger LOGGER = null;
private int verbosityLevel = 0;
private InputStream inputStream;
private OutputStream outputStream;
private boolean jsonOutput;
private Main() {
// Prevent instantiation from the outside worlds
}
public static void main(String[] args) throws IOException, ParseException {
// Set the security manager, preventing commands/network interactions.
System.setSecurityManager(new UnsafeSecurityManager());
// Hide macOS' Java icon in Dock
System.setProperty("java.awt.headless", "true");
Main main = new Main();
main.parseArguments(args);
try {
main.sanitize(); | } catch (BleachException e) { |
docbleach/DocBleach | cli/src/main/java/xyz/docbleach/cli/Main.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/DefaultBleach.java
// public class DefaultBleach extends CompositeBleach {
//
// public DefaultBleach() {
// super(getDefaultBleaches());
// }
//
// /**
// * Finds all statically loadable bleaches
// *
// * @return ordered list of statically loadable bleaches
// */
// private static Bleach[] getDefaultBleaches() {
// ServiceLoader<Bleach> services = ServiceLoader.load(Bleach.class);
//
// Collection<Bleach> list = new ArrayList<>();
// services.forEach(list::add);
//
// return list.toArray(new Bleach[0]);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
| import com.google.gson.Gson;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.SimpleLogger;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.DefaultBleach;
import xyz.docbleach.api.exception.BleachException; | Main main = new Main();
main.parseArguments(args);
try {
main.sanitize();
} catch (BleachException e) {
exitError(e);
}
System.exit(0);
}
private static void exitError(Exception e) {
if (LOGGER == null) {
System.err.println("An error occured: " + e.getMessage());
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.error("An error occured", e);
} else {
LOGGER.error(e.getMessage());
}
}
System.exit(1);
}
/**
* Sanitizes the designated files
*/
private void sanitize() throws BleachException { | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/DefaultBleach.java
// public class DefaultBleach extends CompositeBleach {
//
// public DefaultBleach() {
// super(getDefaultBleaches());
// }
//
// /**
// * Finds all statically loadable bleaches
// *
// * @return ordered list of statically loadable bleaches
// */
// private static Bleach[] getDefaultBleaches() {
// ServiceLoader<Bleach> services = ServiceLoader.load(Bleach.class);
//
// Collection<Bleach> list = new ArrayList<>();
// services.forEach(list::add);
//
// return list.toArray(new Bleach[0]);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
// Path: cli/src/main/java/xyz/docbleach/cli/Main.java
import com.google.gson.Gson;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.SimpleLogger;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.DefaultBleach;
import xyz.docbleach.api.exception.BleachException;
Main main = new Main();
main.parseArguments(args);
try {
main.sanitize();
} catch (BleachException e) {
exitError(e);
}
System.exit(0);
}
private static void exitError(Exception e) {
if (LOGGER == null) {
System.err.println("An error occured: " + e.getMessage());
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.error("An error occured", e);
} else {
LOGGER.error(e.getMessage());
}
}
System.exit(1);
}
/**
* Sanitizes the designated files
*/
private void sanitize() throws BleachException { | BleachSession session = new BleachSession(new DefaultBleach()); |
docbleach/DocBleach | cli/src/main/java/xyz/docbleach/cli/Main.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/DefaultBleach.java
// public class DefaultBleach extends CompositeBleach {
//
// public DefaultBleach() {
// super(getDefaultBleaches());
// }
//
// /**
// * Finds all statically loadable bleaches
// *
// * @return ordered list of statically loadable bleaches
// */
// private static Bleach[] getDefaultBleaches() {
// ServiceLoader<Bleach> services = ServiceLoader.load(Bleach.class);
//
// Collection<Bleach> list = new ArrayList<>();
// services.forEach(list::add);
//
// return list.toArray(new Bleach[0]);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
| import com.google.gson.Gson;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.SimpleLogger;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.DefaultBleach;
import xyz.docbleach.api.exception.BleachException; | Main main = new Main();
main.parseArguments(args);
try {
main.sanitize();
} catch (BleachException e) {
exitError(e);
}
System.exit(0);
}
private static void exitError(Exception e) {
if (LOGGER == null) {
System.err.println("An error occured: " + e.getMessage());
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.error("An error occured", e);
} else {
LOGGER.error(e.getMessage());
}
}
System.exit(1);
}
/**
* Sanitizes the designated files
*/
private void sanitize() throws BleachException { | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/DefaultBleach.java
// public class DefaultBleach extends CompositeBleach {
//
// public DefaultBleach() {
// super(getDefaultBleaches());
// }
//
// /**
// * Finds all statically loadable bleaches
// *
// * @return ordered list of statically loadable bleaches
// */
// private static Bleach[] getDefaultBleaches() {
// ServiceLoader<Bleach> services = ServiceLoader.load(Bleach.class);
//
// Collection<Bleach> list = new ArrayList<>();
// services.forEach(list::add);
//
// return list.toArray(new Bleach[0]);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
// Path: cli/src/main/java/xyz/docbleach/cli/Main.java
import com.google.gson.Gson;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.SimpleLogger;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.DefaultBleach;
import xyz.docbleach.api.exception.BleachException;
Main main = new Main();
main.parseArguments(args);
try {
main.sanitize();
} catch (BleachException e) {
exitError(e);
}
System.exit(0);
}
private static void exitError(Exception e) {
if (LOGGER == null) {
System.err.println("An error occured: " + e.getMessage());
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.error("An error occured", e);
} else {
LOGGER.error(e.getMessage());
}
}
System.exit(1);
}
/**
* Sanitizes the designated files
*/
private void sanitize() throws BleachException { | BleachSession session = new BleachSession(new DefaultBleach()); |
docbleach/DocBleach | module/module-zip/src/main/java/xyz/docbleach/module/zip/ArchiveBleach.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/RecursionBleachException.java
// public class RecursionBleachException extends BleachException {
//
// /**
// * @param depth The depth of the recursion
// */
// public RecursionBleachException(int depth) {
// super("Recursion exploit? There are already " + depth + " sanitation tasks.");
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/CloseShieldInputStream.java
// public class CloseShieldInputStream extends FilterInputStream {
//
// public CloseShieldInputStream(InputStream inStream) {
// super(inStream);
// }
//
// @Override
// public void close() throws IOException {
// // no-action
// }
//
// public void _close() throws IOException {
// super.close();
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
| import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.exception.RecursionBleachException;
import xyz.docbleach.api.util.CloseShieldInputStream;
import xyz.docbleach.api.util.StreamUtils; | package xyz.docbleach.module.zip;
public class ArchiveBleach implements Bleach {
private static final Logger LOGGER = LoggerFactory.getLogger(ArchiveBleach.class);
private static final byte[] ZIP_MAGIC = new byte[]{0x50, 0x4B, 0x03, 0x04};
@Override
public boolean handlesMagic(InputStream stream) { | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/RecursionBleachException.java
// public class RecursionBleachException extends BleachException {
//
// /**
// * @param depth The depth of the recursion
// */
// public RecursionBleachException(int depth) {
// super("Recursion exploit? There are already " + depth + " sanitation tasks.");
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/CloseShieldInputStream.java
// public class CloseShieldInputStream extends FilterInputStream {
//
// public CloseShieldInputStream(InputStream inStream) {
// super(inStream);
// }
//
// @Override
// public void close() throws IOException {
// // no-action
// }
//
// public void _close() throws IOException {
// super.close();
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
// Path: module/module-zip/src/main/java/xyz/docbleach/module/zip/ArchiveBleach.java
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.exception.RecursionBleachException;
import xyz.docbleach.api.util.CloseShieldInputStream;
import xyz.docbleach.api.util.StreamUtils;
package xyz.docbleach.module.zip;
public class ArchiveBleach implements Bleach {
private static final Logger LOGGER = LoggerFactory.getLogger(ArchiveBleach.class);
private static final byte[] ZIP_MAGIC = new byte[]{0x50, 0x4B, 0x03, 0x04};
@Override
public boolean handlesMagic(InputStream stream) { | return StreamUtils.hasHeader(stream, ZIP_MAGIC); |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/ObjectRemover.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.ole2;
public class ObjectRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectRemover.class);
private static final String COMPOUND_OBJECT_ENTRY = "\u0001CompObj";
private static final String OBJECT_POOL_ENTRY = "ObjectPool";
| // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/ObjectRemover.java
import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.ole2;
public class ObjectRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectRemover.class);
private static final String COMPOUND_OBJECT_ENTRY = "\u0001CompObj";
private static final String OBJECT_POOL_ENTRY = "ObjectPool";
| public ObjectRemover(BleachSession session) { |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/ObjectRemover.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.ole2;
public class ObjectRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectRemover.class);
private static final String COMPOUND_OBJECT_ENTRY = "\u0001CompObj";
private static final String OBJECT_POOL_ENTRY = "ObjectPool";
public ObjectRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
if (!isObject(entryName)) {
return true;
}
LOGGER.info("Found Compound Objects, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Compound Objects' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
| // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/ObjectRemover.java
import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.ole2;
public class ObjectRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectRemover.class);
private static final String COMPOUND_OBJECT_ENTRY = "\u0001CompObj";
private static final String OBJECT_POOL_ENTRY = "ObjectPool";
public ObjectRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
if (!isObject(entryName)) {
return true;
}
LOGGER.info("Found Compound Objects, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Compound Objects' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
| Threat threat = Threat.builder() |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/ObjectRemover.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.ole2;
public class ObjectRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectRemover.class);
private static final String COMPOUND_OBJECT_ENTRY = "\u0001CompObj";
private static final String OBJECT_POOL_ENTRY = "ObjectPool";
public ObjectRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
if (!isObject(entryName)) {
return true;
}
LOGGER.info("Found Compound Objects, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Compound Objects' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
Threat threat = Threat.builder() | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/ObjectRemover.java
import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.ole2;
public class ObjectRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectRemover.class);
private static final String COMPOUND_OBJECT_ENTRY = "\u0001CompObj";
private static final String OBJECT_POOL_ENTRY = "ObjectPool";
public ObjectRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
if (!isObject(entryName)) {
return true;
}
LOGGER.info("Found Compound Objects, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Compound Objects' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
Threat threat = Threat.builder() | .type(ThreatType.EXTERNAL_CONTENT) |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/ObjectRemover.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.ole2;
public class ObjectRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectRemover.class);
private static final String COMPOUND_OBJECT_ENTRY = "\u0001CompObj";
private static final String OBJECT_POOL_ENTRY = "ObjectPool";
public ObjectRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
if (!isObject(entryName)) {
return true;
}
LOGGER.info("Found Compound Objects, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Compound Objects' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
Threat threat = Threat.builder()
.type(ThreatType.EXTERNAL_CONTENT) | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/ObjectRemover.java
import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.ole2;
public class ObjectRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectRemover.class);
private static final String COMPOUND_OBJECT_ENTRY = "\u0001CompObj";
private static final String OBJECT_POOL_ENTRY = "ObjectPool";
public ObjectRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
if (!isObject(entryName)) {
return true;
}
LOGGER.info("Found Compound Objects, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Compound Objects' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
Threat threat = Threat.builder()
.type(ThreatType.EXTERNAL_CONTENT) | .severity(ThreatSeverity.HIGH) |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/ObjectRemover.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.ole2;
public class ObjectRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectRemover.class);
private static final String COMPOUND_OBJECT_ENTRY = "\u0001CompObj";
private static final String OBJECT_POOL_ENTRY = "ObjectPool";
public ObjectRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
if (!isObject(entryName)) {
return true;
}
LOGGER.info("Found Compound Objects, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Compound Objects' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
Threat threat = Threat.builder()
.type(ThreatType.EXTERNAL_CONTENT)
.severity(ThreatSeverity.HIGH) | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/ObjectRemover.java
import java.util.Set;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.ole2;
public class ObjectRemover extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectRemover.class);
private static final String COMPOUND_OBJECT_ENTRY = "\u0001CompObj";
private static final String OBJECT_POOL_ENTRY = "ObjectPool";
public ObjectRemover(BleachSession session) {
super(session);
}
@Override
public boolean test(Entry entry) {
String entryName = entry.getName();
if (!isObject(entryName)) {
return true;
}
LOGGER.info("Found Compound Objects, removing them.");
StringBuilder infos = new StringBuilder();
if (entry instanceof DirectoryEntry) {
Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames();
LOGGER.trace("Compound Objects' entries: {}", entryNames);
infos.append("Entries: ").append(entryNames);
} else if (entry instanceof DocumentEntry) {
int size = ((DocumentEntry) entry).getSize();
infos.append("Size: ").append(size);
}
Threat threat = Threat.builder()
.type(ThreatType.EXTERNAL_CONTENT)
.severity(ThreatSeverity.HIGH) | .action(ThreatAction.REMOVE) |
docbleach/DocBleach | module/module-office/src/test/java/xyz/docbleach/module/ole2/SummaryInformationSanitiserTest.java | // Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
//
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
| import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static xyz.docbleach.api.BleachTestBase.assertThreatsFound;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession; | package xyz.docbleach.module.ole2;
class SummaryInformationSanitiserTest {
private SummaryInformationSanitiser instance; | // Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
//
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
// Path: module/module-office/src/test/java/xyz/docbleach/module/ole2/SummaryInformationSanitiserTest.java
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static xyz.docbleach.api.BleachTestBase.assertThreatsFound;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
package xyz.docbleach.module.ole2;
class SummaryInformationSanitiserTest {
private SummaryInformationSanitiser instance; | private BleachSession session; |
docbleach/DocBleach | module/module-office/src/test/java/xyz/docbleach/module/ole2/SummaryInformationSanitiserTest.java | // Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
//
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
| import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static xyz.docbleach.api.BleachTestBase.assertThreatsFound;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession; | reset(entry);
doReturn(SummaryInformation.DEFAULT_STREAM_NAME).when(entry).getName();
assertTrue(instance.test(entry));
verify(instance, never()).sanitizeSummaryInformation(eq(session), (DocumentEntry) any());
reset(instance, entry);
// Test a valid SummaryInformation name
DocumentEntry docEntry = mock(DocumentEntry.class);
doReturn(SummaryInformation.DEFAULT_STREAM_NAME).when(docEntry).getName();
doNothing().when(instance).sanitizeSummaryInformation(session, docEntry);
assertTrue(instance.test(docEntry));
verify(instance, atLeastOnce()).sanitizeSummaryInformation(session, docEntry);
}
@Test
void sanitizeSummaryInformation() {
}
@Test
void sanitizeSummaryInformation1() {
}
@Test
void sanitizeComments() {
SummaryInformation si = new SummaryInformation();
// When no comment is set, no error/threat is thrown
instance.sanitizeComments(session, si); | // Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
//
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
// Path: module/module-office/src/test/java/xyz/docbleach/module/ole2/SummaryInformationSanitiserTest.java
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static xyz.docbleach.api.BleachTestBase.assertThreatsFound;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
reset(entry);
doReturn(SummaryInformation.DEFAULT_STREAM_NAME).when(entry).getName();
assertTrue(instance.test(entry));
verify(instance, never()).sanitizeSummaryInformation(eq(session), (DocumentEntry) any());
reset(instance, entry);
// Test a valid SummaryInformation name
DocumentEntry docEntry = mock(DocumentEntry.class);
doReturn(SummaryInformation.DEFAULT_STREAM_NAME).when(docEntry).getName();
doNothing().when(instance).sanitizeSummaryInformation(session, docEntry);
assertTrue(instance.test(docEntry));
verify(instance, atLeastOnce()).sanitizeSummaryInformation(session, docEntry);
}
@Test
void sanitizeSummaryInformation() {
}
@Test
void sanitizeSummaryInformation1() {
}
@Test
void sanitizeComments() {
SummaryInformation si = new SummaryInformation();
// When no comment is set, no error/threat is thrown
instance.sanitizeComments(session, si); | assertThreatsFound(session, 0); |
docbleach/DocBleach | module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PDEmbeddedFileBleach.java | // Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
| import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.function.Consumer;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode;
import org.apache.pdfbox.pdmodel.common.COSObjectable;
import org.apache.pdfbox.pdmodel.common.PDNameTreeNode;
import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;
import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.exception.BleachException; | }
private void sanitizeEmbeddedFile(PDComplexFileSpecification fileSpec) {
LOGGER.trace("Embedded file found: {}", fileSpec.getFilename());
fileSpec.setEmbeddedFile(sanitizeEmbeddedFile(fileSpec.getEmbeddedFile()));
fileSpec.setEmbeddedFileDos(sanitizeEmbeddedFile(fileSpec.getEmbeddedFileDos()));
fileSpec.setEmbeddedFileMac(sanitizeEmbeddedFile(fileSpec.getEmbeddedFileMac()));
fileSpec.setEmbeddedFileUnicode(sanitizeEmbeddedFile(fileSpec.getEmbeddedFileUnicode()));
fileSpec.setEmbeddedFileUnix(sanitizeEmbeddedFile(fileSpec.getEmbeddedFileUnix()));
}
private PDEmbeddedFile sanitizeEmbeddedFile(PDEmbeddedFile file) {
if (file == null) {
return null;
}
LOGGER.debug("Sanitizing file: Size: {}, Mime-Type: {}, ", file.getSize(), file.getSubtype());
ByteArrayInputStream is;
try {
is = new ByteArrayInputStream(file.toByteArray());
} catch (IOException e) {
LOGGER.error("Error during original's file read", e);
return null;
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
pdfBleachSession.getSession().sanitize(is, os); | // Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
// Path: module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PDEmbeddedFileBleach.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.function.Consumer;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode;
import org.apache.pdfbox.pdmodel.common.COSObjectable;
import org.apache.pdfbox.pdmodel.common.PDNameTreeNode;
import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;
import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.exception.BleachException;
}
private void sanitizeEmbeddedFile(PDComplexFileSpecification fileSpec) {
LOGGER.trace("Embedded file found: {}", fileSpec.getFilename());
fileSpec.setEmbeddedFile(sanitizeEmbeddedFile(fileSpec.getEmbeddedFile()));
fileSpec.setEmbeddedFileDos(sanitizeEmbeddedFile(fileSpec.getEmbeddedFileDos()));
fileSpec.setEmbeddedFileMac(sanitizeEmbeddedFile(fileSpec.getEmbeddedFileMac()));
fileSpec.setEmbeddedFileUnicode(sanitizeEmbeddedFile(fileSpec.getEmbeddedFileUnicode()));
fileSpec.setEmbeddedFileUnix(sanitizeEmbeddedFile(fileSpec.getEmbeddedFileUnix()));
}
private PDEmbeddedFile sanitizeEmbeddedFile(PDEmbeddedFile file) {
if (file == null) {
return null;
}
LOGGER.debug("Sanitizing file: Size: {}, Mime-Type: {}, ", file.getSize(), file.getSubtype());
ByteArrayInputStream is;
try {
is = new ByteArrayInputStream(file.toByteArray());
} catch (IOException e) {
LOGGER.error("Error during original's file read", e);
return null;
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
pdfBleachSession.getSession().sanitize(is, os); | } catch (BleachException e) { |
tvportal/android | app/src/main/java/com/devspark/robototextview/widget/RobotoButton.java | // Path: app/src/main/java/com/devspark/robototextview/RobotoTypefaceManager.java
// public class RobotoTypefaceManager {
//
// /*
// * Available values for the "typeface" attribute.
// */
// private final static int ROBOTO_LIGHT = 0;
// private final static int ROBOTO_REGULAR = 1;
//
// /**
// * Array of created typefaces for later reused.
// */
// private final static SparseArray<Typeface> mTypefaces = new SparseArray<Typeface>(20);
//
// /**
// * Obtain typeface.
// *
// * @param context The Context the widget is running in, through which it can access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return specify {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// public static Typeface obtaintTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface = mTypefaces.get(typefaceValue);
// if (typeface == null) {
// typeface = createTypeface(context, typefaceValue);
// mTypefaces.put(typefaceValue, typeface);
// }
// return typeface;
// }
//
// /**
// * Create typeface from assets.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return Roboto {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// private static Typeface createTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface;
// switch (typefaceValue) {
// case ROBOTO_LIGHT:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
// break;
// case ROBOTO_REGULAR:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf");
// break;
// default:
// throw new IllegalArgumentException("Unknown `typeface` attribute value " + typefaceValue);
// }
// return typeface;
// }
//
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.Button;
import com.devspark.robototextview.RobotoTypefaceManager;
import com.mitechlt.tvportal.play.R; | /*
* Copyright (C) 2013 Evgeny Shishkin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.devspark.robototextview.widget;
/**
* Implementation of a {@link Button} with native support for all the Roboto fonts.
*
* @author Evgeny Shishkin
*/
public class RobotoButton extends Button {
/**
* Simple constructor to use when creating a widget from code.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
*/
public RobotoButton(Context context) {
super(context);
onInitTypeface(context, null, 0);
}
/**
* Constructor that is called when inflating a widget from XML. This is called
* when a widget is being constructed from an XML file, supplying attributes
* that were specified in the XML file. This version uses a default style of
* 0, so the only attribute values applied are those in the Context's Theme
* and the given AttributeSet.
* <p/>
* <p/>
* The method onFinishInflate() will be called after all children have been
* added.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @see #RobotoButton(Context, AttributeSet, int)
*/
public RobotoButton(Context context, AttributeSet attrs) {
super(context, attrs);
onInitTypeface(context, attrs, 0);
}
/**
* Perform inflation from XML and apply a class-specific base style. This
* constructor of View allows subclasses to use their own base style when
* they are inflating.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
* @see #RobotoButton(Context, AttributeSet)
*/
public RobotoButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
onInitTypeface(context, attrs, defStyle);
}
/**
* Setup Roboto typeface.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme).
*/
private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
// Typeface.createFromAsset doesn't work in the layout editor, so skipping.
if (isInEditMode()) {
return;
}
int typefaceValue = 0;
if (attrs != null) {
TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
values.recycle();
}
| // Path: app/src/main/java/com/devspark/robototextview/RobotoTypefaceManager.java
// public class RobotoTypefaceManager {
//
// /*
// * Available values for the "typeface" attribute.
// */
// private final static int ROBOTO_LIGHT = 0;
// private final static int ROBOTO_REGULAR = 1;
//
// /**
// * Array of created typefaces for later reused.
// */
// private final static SparseArray<Typeface> mTypefaces = new SparseArray<Typeface>(20);
//
// /**
// * Obtain typeface.
// *
// * @param context The Context the widget is running in, through which it can access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return specify {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// public static Typeface obtaintTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface = mTypefaces.get(typefaceValue);
// if (typeface == null) {
// typeface = createTypeface(context, typefaceValue);
// mTypefaces.put(typefaceValue, typeface);
// }
// return typeface;
// }
//
// /**
// * Create typeface from assets.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return Roboto {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// private static Typeface createTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface;
// switch (typefaceValue) {
// case ROBOTO_LIGHT:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
// break;
// case ROBOTO_REGULAR:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf");
// break;
// default:
// throw new IllegalArgumentException("Unknown `typeface` attribute value " + typefaceValue);
// }
// return typeface;
// }
//
// }
// Path: app/src/main/java/com/devspark/robototextview/widget/RobotoButton.java
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.Button;
import com.devspark.robototextview.RobotoTypefaceManager;
import com.mitechlt.tvportal.play.R;
/*
* Copyright (C) 2013 Evgeny Shishkin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.devspark.robototextview.widget;
/**
* Implementation of a {@link Button} with native support for all the Roboto fonts.
*
* @author Evgeny Shishkin
*/
public class RobotoButton extends Button {
/**
* Simple constructor to use when creating a widget from code.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
*/
public RobotoButton(Context context) {
super(context);
onInitTypeface(context, null, 0);
}
/**
* Constructor that is called when inflating a widget from XML. This is called
* when a widget is being constructed from an XML file, supplying attributes
* that were specified in the XML file. This version uses a default style of
* 0, so the only attribute values applied are those in the Context's Theme
* and the given AttributeSet.
* <p/>
* <p/>
* The method onFinishInflate() will be called after all children have been
* added.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @see #RobotoButton(Context, AttributeSet, int)
*/
public RobotoButton(Context context, AttributeSet attrs) {
super(context, attrs);
onInitTypeface(context, attrs, 0);
}
/**
* Perform inflation from XML and apply a class-specific base style. This
* constructor of View allows subclasses to use their own base style when
* they are inflating.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
* @see #RobotoButton(Context, AttributeSet)
*/
public RobotoButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
onInitTypeface(context, attrs, defStyle);
}
/**
* Setup Roboto typeface.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme).
*/
private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
// Typeface.createFromAsset doesn't work in the layout editor, so skipping.
if (isInEditMode()) {
return;
}
int typefaceValue = 0;
if (attrs != null) {
TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
values.recycle();
}
| Typeface robotoTypeface = RobotoTypefaceManager.obtaintTypeface(context, typefaceValue); |
tvportal/android | app/src/main/java/com/devspark/robototextview/widget/RobotoTextView.java | // Path: app/src/main/java/com/devspark/robototextview/RobotoTypefaceManager.java
// public class RobotoTypefaceManager {
//
// /*
// * Available values for the "typeface" attribute.
// */
// private final static int ROBOTO_LIGHT = 0;
// private final static int ROBOTO_REGULAR = 1;
//
// /**
// * Array of created typefaces for later reused.
// */
// private final static SparseArray<Typeface> mTypefaces = new SparseArray<Typeface>(20);
//
// /**
// * Obtain typeface.
// *
// * @param context The Context the widget is running in, through which it can access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return specify {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// public static Typeface obtaintTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface = mTypefaces.get(typefaceValue);
// if (typeface == null) {
// typeface = createTypeface(context, typefaceValue);
// mTypefaces.put(typefaceValue, typeface);
// }
// return typeface;
// }
//
// /**
// * Create typeface from assets.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return Roboto {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// private static Typeface createTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface;
// switch (typefaceValue) {
// case ROBOTO_LIGHT:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
// break;
// case ROBOTO_REGULAR:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf");
// break;
// default:
// throw new IllegalArgumentException("Unknown `typeface` attribute value " + typefaceValue);
// }
// return typeface;
// }
//
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
import com.devspark.robototextview.RobotoTypefaceManager;
import com.mitechlt.tvportal.play.R; | /*
* Copyright 2013 Evgeny Shishkin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.devspark.robototextview.widget;
/**
* Implementation of a {@link TextView} with native support for all the Roboto fonts.
*
* @author Evgeny Shishkin
*/
public class RobotoTextView extends TextView {
/**
* Simple constructor to use when creating a widget from code.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
*/
public RobotoTextView(Context context) {
super(context);
onInitTypeface(context, null, 0);
}
/**
* Constructor that is called when inflating a widget from XML. This is called
* when a widget is being constructed from an XML file, supplying attributes
* that were specified in the XML file. This version uses a default style of
* 0, so the only attribute values applied are those in the Context's Theme
* and the given AttributeSet.
* <p/>
* <p/>
* The method onFinishInflate() will be called after all children have been
* added.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @see #RobotoTextView(Context, AttributeSet, int)
*/
public RobotoTextView(Context context, AttributeSet attrs) {
super(context, attrs);
onInitTypeface(context, attrs, 0);
}
/**
* Perform inflation from XML and apply a class-specific base style. This
* constructor of View allows subclasses to use their own base style when
* they are inflating.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
* @see #RobotoTextView(Context, AttributeSet)
*/
public RobotoTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
onInitTypeface(context, attrs, defStyle);
}
/**
* Setup Roboto typeface.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme).
*/
private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
// Typeface.createFromAsset doesn't work in the layout editor, so skipping.
if (isInEditMode()) {
return;
}
int typefaceValue = 0;
if (attrs != null) {
TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
values.recycle();
}
| // Path: app/src/main/java/com/devspark/robototextview/RobotoTypefaceManager.java
// public class RobotoTypefaceManager {
//
// /*
// * Available values for the "typeface" attribute.
// */
// private final static int ROBOTO_LIGHT = 0;
// private final static int ROBOTO_REGULAR = 1;
//
// /**
// * Array of created typefaces for later reused.
// */
// private final static SparseArray<Typeface> mTypefaces = new SparseArray<Typeface>(20);
//
// /**
// * Obtain typeface.
// *
// * @param context The Context the widget is running in, through which it can access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return specify {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// public static Typeface obtaintTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface = mTypefaces.get(typefaceValue);
// if (typeface == null) {
// typeface = createTypeface(context, typefaceValue);
// mTypefaces.put(typefaceValue, typeface);
// }
// return typeface;
// }
//
// /**
// * Create typeface from assets.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return Roboto {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// private static Typeface createTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface;
// switch (typefaceValue) {
// case ROBOTO_LIGHT:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
// break;
// case ROBOTO_REGULAR:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf");
// break;
// default:
// throw new IllegalArgumentException("Unknown `typeface` attribute value " + typefaceValue);
// }
// return typeface;
// }
//
// }
// Path: app/src/main/java/com/devspark/robototextview/widget/RobotoTextView.java
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
import com.devspark.robototextview.RobotoTypefaceManager;
import com.mitechlt.tvportal.play.R;
/*
* Copyright 2013 Evgeny Shishkin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.devspark.robototextview.widget;
/**
* Implementation of a {@link TextView} with native support for all the Roboto fonts.
*
* @author Evgeny Shishkin
*/
public class RobotoTextView extends TextView {
/**
* Simple constructor to use when creating a widget from code.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
*/
public RobotoTextView(Context context) {
super(context);
onInitTypeface(context, null, 0);
}
/**
* Constructor that is called when inflating a widget from XML. This is called
* when a widget is being constructed from an XML file, supplying attributes
* that were specified in the XML file. This version uses a default style of
* 0, so the only attribute values applied are those in the Context's Theme
* and the given AttributeSet.
* <p/>
* <p/>
* The method onFinishInflate() will be called after all children have been
* added.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @see #RobotoTextView(Context, AttributeSet, int)
*/
public RobotoTextView(Context context, AttributeSet attrs) {
super(context, attrs);
onInitTypeface(context, attrs, 0);
}
/**
* Perform inflation from XML and apply a class-specific base style. This
* constructor of View allows subclasses to use their own base style when
* they are inflating.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
* @see #RobotoTextView(Context, AttributeSet)
*/
public RobotoTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
onInitTypeface(context, attrs, defStyle);
}
/**
* Setup Roboto typeface.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme).
*/
private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
// Typeface.createFromAsset doesn't work in the layout editor, so skipping.
if (isInEditMode()) {
return;
}
int typefaceValue = 0;
if (attrs != null) {
TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
values.recycle();
}
| Typeface robotoTypeface = RobotoTypefaceManager.obtaintTypeface(context, typefaceValue); |
tvportal/android | app/src/main/java/com/mitechlt/tvportal/play/adapters/FavoriteAdapter.java | // Path: app/src/main/java/com/mitechlt/tvportal/play/databases/FavoritesTable.java
// public class FavoritesTable extends SQLiteOpenHelper {
//
// public static final String TABLE_FAVORITES = "favorites";
// public static final String COLUMN_ID = "_id";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_TITLE = "title";
// public static final String COLUMN_LINK = "link";
// public static final String COLUMN_IMAGE = "image";
// public static final String COLUMN_RATING = "rating";
//
// private static final String DATABASE_NAME = "favorites.db";
// private static final int DATABASE_VERSION = 3;
//
// private static final String DATABASE_CREATE = "create table "
// + TABLE_FAVORITES + "("
// + COLUMN_ID + " integer primary key autoincrement, "
// + COLUMN_TITLE + " text not null, "
// + COLUMN_LINK + " text not null, "
// + COLUMN_IMAGE + " text not null, "
// + COLUMN_TYPE + " text not null, "
// + COLUMN_RATING + " integer);";
//
// public FavoritesTable(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// @Override
// public void onCreate(SQLiteDatabase database) {
// database.execSQL(DATABASE_CREATE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Log.w(FavoritesTable.class.getName(),
// "Upgrading database from version " + oldVersion + " to "
// + newVersion + ", which will destroy all old data"
// );
// db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
// onCreate(db);
// }
//
// }
| import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.mitechlt.tvportal.play.R;
import com.mitechlt.tvportal.play.databases.FavoritesTable;
import com.squareup.picasso.Picasso; | mData = new DataHolder[getCount()];
getColumnIndices(mFavouriteCursor);
Resources res = mContext.getResources();
for (int i = 0; i < getCount(); i++) {
mFavouriteCursor.moveToPosition(i);
mData[i] = new DataHolder();
mData[i].title = mFavouriteCursor.getString(mTitleIdx);
String type = mFavouriteCursor.getString(mTypeIdx);
if (type != null && type.equals("movie")) {
mData[i].typeBackgroundColor = res.getColor(R.color.holo_blue);
type = "Movie";
}
if (type != null && type.equals("tvshow")) {
mData[i].typeBackgroundColor = res.getColor(R.color.holo_green);
type = "TV Show";
}
mData[i].type = type;
mData[i].imgUri = mFavouriteCursor.getString(mImageIdx);
}
}
private void getColumnIndices(Cursor cursor) {
if (cursor != null && !cursor.isClosed()) { | // Path: app/src/main/java/com/mitechlt/tvportal/play/databases/FavoritesTable.java
// public class FavoritesTable extends SQLiteOpenHelper {
//
// public static final String TABLE_FAVORITES = "favorites";
// public static final String COLUMN_ID = "_id";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_TITLE = "title";
// public static final String COLUMN_LINK = "link";
// public static final String COLUMN_IMAGE = "image";
// public static final String COLUMN_RATING = "rating";
//
// private static final String DATABASE_NAME = "favorites.db";
// private static final int DATABASE_VERSION = 3;
//
// private static final String DATABASE_CREATE = "create table "
// + TABLE_FAVORITES + "("
// + COLUMN_ID + " integer primary key autoincrement, "
// + COLUMN_TITLE + " text not null, "
// + COLUMN_LINK + " text not null, "
// + COLUMN_IMAGE + " text not null, "
// + COLUMN_TYPE + " text not null, "
// + COLUMN_RATING + " integer);";
//
// public FavoritesTable(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// @Override
// public void onCreate(SQLiteDatabase database) {
// database.execSQL(DATABASE_CREATE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Log.w(FavoritesTable.class.getName(),
// "Upgrading database from version " + oldVersion + " to "
// + newVersion + ", which will destroy all old data"
// );
// db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
// onCreate(db);
// }
//
// }
// Path: app/src/main/java/com/mitechlt/tvportal/play/adapters/FavoriteAdapter.java
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.mitechlt.tvportal.play.R;
import com.mitechlt.tvportal.play.databases.FavoritesTable;
import com.squareup.picasso.Picasso;
mData = new DataHolder[getCount()];
getColumnIndices(mFavouriteCursor);
Resources res = mContext.getResources();
for (int i = 0; i < getCount(); i++) {
mFavouriteCursor.moveToPosition(i);
mData[i] = new DataHolder();
mData[i].title = mFavouriteCursor.getString(mTitleIdx);
String type = mFavouriteCursor.getString(mTypeIdx);
if (type != null && type.equals("movie")) {
mData[i].typeBackgroundColor = res.getColor(R.color.holo_blue);
type = "Movie";
}
if (type != null && type.equals("tvshow")) {
mData[i].typeBackgroundColor = res.getColor(R.color.holo_green);
type = "TV Show";
}
mData[i].type = type;
mData[i].imgUri = mFavouriteCursor.getString(mImageIdx);
}
}
private void getColumnIndices(Cursor cursor) {
if (cursor != null && !cursor.isClosed()) { | mTitleIdx = cursor.getColumnIndexOrThrow(FavoritesTable.COLUMN_TITLE); |
tvportal/android | app/src/main/java/com/mitechlt/tvportal/play/adapters/SocialAdapter.java | // Path: app/src/main/java/com/devspark/robototextview/widget/RobotoTextView.java
// public class RobotoTextView extends TextView {
//
// /**
// * Simple constructor to use when creating a widget from code.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// */
// public RobotoTextView(Context context) {
// super(context);
// onInitTypeface(context, null, 0);
// }
//
// /**
// * Constructor that is called when inflating a widget from XML. This is called
// * when a widget is being constructed from an XML file, supplying attributes
// * that were specified in the XML file. This version uses a default style of
// * 0, so the only attribute values applied are those in the Context's Theme
// * and the given AttributeSet.
// * <p/>
// * <p/>
// * The method onFinishInflate() will be called after all children have been
// * added.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param attrs The attributes of the XML tag that is inflating the widget.
// * @see #RobotoTextView(Context, AttributeSet, int)
// */
// public RobotoTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// onInitTypeface(context, attrs, 0);
// }
//
// /**
// * Perform inflation from XML and apply a class-specific base style. This
// * constructor of View allows subclasses to use their own base style when
// * they are inflating.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param attrs The attributes of the XML tag that is inflating the widget.
// * @param defStyle The default style to apply to this widget. If 0, no style
// * will be applied (beyond what is included in the theme). This may
// * either be an attribute resource, whose value will be retrieved
// * from the current theme, or an explicit style resource.
// * @see #RobotoTextView(Context, AttributeSet)
// */
// public RobotoTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// onInitTypeface(context, attrs, defStyle);
// }
//
// /**
// * Setup Roboto typeface.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param attrs The attributes of the XML tag that is inflating the widget.
// * @param defStyle The default style to apply to this widget. If 0, no style
// * will be applied (beyond what is included in the theme).
// */
// private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
// // Typeface.createFromAsset doesn't work in the layout editor, so skipping.
// if (isInEditMode()) {
// return;
// }
//
// int typefaceValue = 0;
// if (attrs != null) {
// TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
// typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
// values.recycle();
// }
//
// Typeface robotoTypeface = RobotoTypefaceManager.obtaintTypeface(context, typefaceValue);
// setTypeface(robotoTypeface);
// }
//
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.devspark.robototextview.widget.RobotoTextView;
import com.mitechlt.tvportal.play.R; | }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Recycle the ViewHolder
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_social, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Bind the data
holder.mTitle.setText(mTitles[position]);
holder.mIcon.setImageResource(mIcons.getResourceId(position, -1));
return convertView;
}
@Override
public boolean hasStableIds() {
return true;
}
/**
* ViewHolder implementation
*/
private static final class ViewHolder {
| // Path: app/src/main/java/com/devspark/robototextview/widget/RobotoTextView.java
// public class RobotoTextView extends TextView {
//
// /**
// * Simple constructor to use when creating a widget from code.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// */
// public RobotoTextView(Context context) {
// super(context);
// onInitTypeface(context, null, 0);
// }
//
// /**
// * Constructor that is called when inflating a widget from XML. This is called
// * when a widget is being constructed from an XML file, supplying attributes
// * that were specified in the XML file. This version uses a default style of
// * 0, so the only attribute values applied are those in the Context's Theme
// * and the given AttributeSet.
// * <p/>
// * <p/>
// * The method onFinishInflate() will be called after all children have been
// * added.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param attrs The attributes of the XML tag that is inflating the widget.
// * @see #RobotoTextView(Context, AttributeSet, int)
// */
// public RobotoTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// onInitTypeface(context, attrs, 0);
// }
//
// /**
// * Perform inflation from XML and apply a class-specific base style. This
// * constructor of View allows subclasses to use their own base style when
// * they are inflating.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param attrs The attributes of the XML tag that is inflating the widget.
// * @param defStyle The default style to apply to this widget. If 0, no style
// * will be applied (beyond what is included in the theme). This may
// * either be an attribute resource, whose value will be retrieved
// * from the current theme, or an explicit style resource.
// * @see #RobotoTextView(Context, AttributeSet)
// */
// public RobotoTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// onInitTypeface(context, attrs, defStyle);
// }
//
// /**
// * Setup Roboto typeface.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param attrs The attributes of the XML tag that is inflating the widget.
// * @param defStyle The default style to apply to this widget. If 0, no style
// * will be applied (beyond what is included in the theme).
// */
// private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
// // Typeface.createFromAsset doesn't work in the layout editor, so skipping.
// if (isInEditMode()) {
// return;
// }
//
// int typefaceValue = 0;
// if (attrs != null) {
// TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
// typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
// values.recycle();
// }
//
// Typeface robotoTypeface = RobotoTypefaceManager.obtaintTypeface(context, typefaceValue);
// setTypeface(robotoTypeface);
// }
//
// }
// Path: app/src/main/java/com/mitechlt/tvportal/play/adapters/SocialAdapter.java
import android.content.Context;
import android.content.res.TypedArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.devspark.robototextview.widget.RobotoTextView;
import com.mitechlt.tvportal.play.R;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Recycle the ViewHolder
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_social, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Bind the data
holder.mTitle.setText(mTitles[position]);
holder.mIcon.setImageResource(mIcons.getResourceId(position, -1));
return convertView;
}
@Override
public boolean hasStableIds() {
return true;
}
/**
* ViewHolder implementation
*/
private static final class ViewHolder {
| private final RobotoTextView mTitle; |
tvportal/android | app/src/main/java/com/mitechlt/tvportal/play/adapters/RecentAdapter.java | // Path: app/src/main/java/com/mitechlt/tvportal/play/databases/RecentTable.java
// public class RecentTable extends SQLiteOpenHelper {
//
// public static final String TABLE_RECENTS = "recents";
// public static final String COLUMN_ID = "_id";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_TITLE = "title";
// public static final String COLUMN_LINK = "link";
// public static final String COLUMN_SEASON = "season";
// public static final String COLUMN_EPISODE = "episode";
// public static final String COLUMN_IMAGE = "image";
// public static final String COLUMN_NUM_SEASONS = "num_seasons";
// public static final String COLUMN_NUM_EPISODES = "num_episodes";
// public static final String COLUMN_RATING = "rating";
//
// private static final String DATABASE_NAME = "recents.db";
// private static final int DATABASE_VERSION = 2;
//
// private static final String DATABASE_CREATE = "create table "
// + TABLE_RECENTS + "("
// + COLUMN_ID + " integer primary key autoincrement, "
// + COLUMN_TITLE + " text not null, "
// + COLUMN_LINK + " text not null, "
// + COLUMN_TYPE + " text not null, "
// + COLUMN_NUM_EPISODES + " text not null, "
// + COLUMN_NUM_SEASONS + " text not null, "
// + COLUMN_EPISODE + " text, "
// + COLUMN_SEASON + " text, "
// + COLUMN_IMAGE + " text not null, "
// + COLUMN_RATING + " integer);";
//
// public RecentTable(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// @Override
// public void onCreate(SQLiteDatabase database) {
// database.execSQL(DATABASE_CREATE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Log.w(RecentTable.class.getName(),
// "Upgrading database from version " + oldVersion + " to "
// + newVersion + ", which will destroy all old data"
// );
// db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECENTS);
// onCreate(db);
// }
//
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.mitechlt.tvportal.play.R;
import com.mitechlt.tvportal.play.databases.RecentTable;
import com.squareup.picasso.Picasso; |
String type = mRecentCursor.getString(mTypeIdx);
if (type != null && type.equals("movie")) {
mData[i].typeBackgroundColor = res.getColor(R.color.holo_blue);
type = "Movie";
} else if (type != null && type.equals("tvshow")) {
mData[i].typeBackgroundColor = res.getColor(R.color.holo_green);
StringBuilder seasonString = new StringBuilder();
seasonString.append("S");
if (seasonNum < 10) {
seasonString.append("0");
}
seasonString.append(seasonNum);
mData[i].season = seasonString.toString();
StringBuilder episodeString = new StringBuilder();
episodeString.append("E");
if (episodeNum < 10) {
episodeString.append("0");
}
episodeString.append(episodeNum);
mData[i].episode = episodeString.toString();
type = "TV Show";
}
mData[i].type = type;
}
}
private void getColumnIndices(Cursor cursor) {
if (cursor != null && !cursor.isClosed()) { | // Path: app/src/main/java/com/mitechlt/tvportal/play/databases/RecentTable.java
// public class RecentTable extends SQLiteOpenHelper {
//
// public static final String TABLE_RECENTS = "recents";
// public static final String COLUMN_ID = "_id";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_TITLE = "title";
// public static final String COLUMN_LINK = "link";
// public static final String COLUMN_SEASON = "season";
// public static final String COLUMN_EPISODE = "episode";
// public static final String COLUMN_IMAGE = "image";
// public static final String COLUMN_NUM_SEASONS = "num_seasons";
// public static final String COLUMN_NUM_EPISODES = "num_episodes";
// public static final String COLUMN_RATING = "rating";
//
// private static final String DATABASE_NAME = "recents.db";
// private static final int DATABASE_VERSION = 2;
//
// private static final String DATABASE_CREATE = "create table "
// + TABLE_RECENTS + "("
// + COLUMN_ID + " integer primary key autoincrement, "
// + COLUMN_TITLE + " text not null, "
// + COLUMN_LINK + " text not null, "
// + COLUMN_TYPE + " text not null, "
// + COLUMN_NUM_EPISODES + " text not null, "
// + COLUMN_NUM_SEASONS + " text not null, "
// + COLUMN_EPISODE + " text, "
// + COLUMN_SEASON + " text, "
// + COLUMN_IMAGE + " text not null, "
// + COLUMN_RATING + " integer);";
//
// public RecentTable(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// @Override
// public void onCreate(SQLiteDatabase database) {
// database.execSQL(DATABASE_CREATE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Log.w(RecentTable.class.getName(),
// "Upgrading database from version " + oldVersion + " to "
// + newVersion + ", which will destroy all old data"
// );
// db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECENTS);
// onCreate(db);
// }
//
// }
// Path: app/src/main/java/com/mitechlt/tvportal/play/adapters/RecentAdapter.java
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.mitechlt.tvportal.play.R;
import com.mitechlt.tvportal.play.databases.RecentTable;
import com.squareup.picasso.Picasso;
String type = mRecentCursor.getString(mTypeIdx);
if (type != null && type.equals("movie")) {
mData[i].typeBackgroundColor = res.getColor(R.color.holo_blue);
type = "Movie";
} else if (type != null && type.equals("tvshow")) {
mData[i].typeBackgroundColor = res.getColor(R.color.holo_green);
StringBuilder seasonString = new StringBuilder();
seasonString.append("S");
if (seasonNum < 10) {
seasonString.append("0");
}
seasonString.append(seasonNum);
mData[i].season = seasonString.toString();
StringBuilder episodeString = new StringBuilder();
episodeString.append("E");
if (episodeNum < 10) {
episodeString.append("0");
}
episodeString.append(episodeNum);
mData[i].episode = episodeString.toString();
type = "TV Show";
}
mData[i].type = type;
}
}
private void getColumnIndices(Cursor cursor) {
if (cursor != null && !cursor.isClosed()) { | mTitleIdx = cursor.getColumnIndexOrThrow(RecentTable.COLUMN_TITLE); |
tvportal/android | app/src/main/java/com/devspark/robototextview/widget/RobotoEditText.java | // Path: app/src/main/java/com/devspark/robototextview/RobotoTypefaceManager.java
// public class RobotoTypefaceManager {
//
// /*
// * Available values for the "typeface" attribute.
// */
// private final static int ROBOTO_LIGHT = 0;
// private final static int ROBOTO_REGULAR = 1;
//
// /**
// * Array of created typefaces for later reused.
// */
// private final static SparseArray<Typeface> mTypefaces = new SparseArray<Typeface>(20);
//
// /**
// * Obtain typeface.
// *
// * @param context The Context the widget is running in, through which it can access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return specify {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// public static Typeface obtaintTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface = mTypefaces.get(typefaceValue);
// if (typeface == null) {
// typeface = createTypeface(context, typefaceValue);
// mTypefaces.put(typefaceValue, typeface);
// }
// return typeface;
// }
//
// /**
// * Create typeface from assets.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return Roboto {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// private static Typeface createTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface;
// switch (typefaceValue) {
// case ROBOTO_LIGHT:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
// break;
// case ROBOTO_REGULAR:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf");
// break;
// default:
// throw new IllegalArgumentException("Unknown `typeface` attribute value " + typefaceValue);
// }
// return typeface;
// }
//
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.EditText;
import com.devspark.robototextview.RobotoTypefaceManager;
import com.mitechlt.tvportal.play.R; | /*
* Copyright (C) 2013 Evgeny Shishkin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.devspark.robototextview.widget;
/**
* Implementation of a {@link EditText} with native support for all the Roboto fonts.
*
* @author Evgeny Shishkin
*/
public class RobotoEditText extends EditText {
/**
* Simple constructor to use when creating a widget from code.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
*/
public RobotoEditText(Context context) {
super(context);
onInitTypeface(context, null, 0);
}
/**
* Constructor that is called when inflating a widget from XML. This is called
* when a widget is being constructed from an XML file, supplying attributes
* that were specified in the XML file. This version uses a default style of
* 0, so the only attribute values applied are those in the Context's Theme
* and the given AttributeSet.
* <p/>
* <p/>
* The method onFinishInflate() will be called after all children have been
* added.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @see #RobotoEditText(Context, android.util.AttributeSet, int)
*/
public RobotoEditText(Context context, AttributeSet attrs) {
super(context, attrs);
onInitTypeface(context, attrs, 0);
}
/**
* Perform inflation from XML and apply a class-specific base style. This
* constructor of View allows subclasses to use their own base style when
* they are inflating.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
* @see #RobotoEditText(Context, AttributeSet)
*/
public RobotoEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
onInitTypeface(context, attrs, defStyle);
}
/**
* Setup Roboto typeface.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme).
*/
private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
// Typeface.createFromAsset doesn't work in the layout editor, so skipping.
if (isInEditMode()) {
return;
}
int typefaceValue = 0;
if (attrs != null) {
TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
values.recycle();
}
| // Path: app/src/main/java/com/devspark/robototextview/RobotoTypefaceManager.java
// public class RobotoTypefaceManager {
//
// /*
// * Available values for the "typeface" attribute.
// */
// private final static int ROBOTO_LIGHT = 0;
// private final static int ROBOTO_REGULAR = 1;
//
// /**
// * Array of created typefaces for later reused.
// */
// private final static SparseArray<Typeface> mTypefaces = new SparseArray<Typeface>(20);
//
// /**
// * Obtain typeface.
// *
// * @param context The Context the widget is running in, through which it can access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return specify {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// public static Typeface obtaintTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface = mTypefaces.get(typefaceValue);
// if (typeface == null) {
// typeface = createTypeface(context, typefaceValue);
// mTypefaces.put(typefaceValue, typeface);
// }
// return typeface;
// }
//
// /**
// * Create typeface from assets.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return Roboto {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// private static Typeface createTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface;
// switch (typefaceValue) {
// case ROBOTO_LIGHT:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
// break;
// case ROBOTO_REGULAR:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf");
// break;
// default:
// throw new IllegalArgumentException("Unknown `typeface` attribute value " + typefaceValue);
// }
// return typeface;
// }
//
// }
// Path: app/src/main/java/com/devspark/robototextview/widget/RobotoEditText.java
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.EditText;
import com.devspark.robototextview.RobotoTypefaceManager;
import com.mitechlt.tvportal.play.R;
/*
* Copyright (C) 2013 Evgeny Shishkin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.devspark.robototextview.widget;
/**
* Implementation of a {@link EditText} with native support for all the Roboto fonts.
*
* @author Evgeny Shishkin
*/
public class RobotoEditText extends EditText {
/**
* Simple constructor to use when creating a widget from code.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
*/
public RobotoEditText(Context context) {
super(context);
onInitTypeface(context, null, 0);
}
/**
* Constructor that is called when inflating a widget from XML. This is called
* when a widget is being constructed from an XML file, supplying attributes
* that were specified in the XML file. This version uses a default style of
* 0, so the only attribute values applied are those in the Context's Theme
* and the given AttributeSet.
* <p/>
* <p/>
* The method onFinishInflate() will be called after all children have been
* added.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @see #RobotoEditText(Context, android.util.AttributeSet, int)
*/
public RobotoEditText(Context context, AttributeSet attrs) {
super(context, attrs);
onInitTypeface(context, attrs, 0);
}
/**
* Perform inflation from XML and apply a class-specific base style. This
* constructor of View allows subclasses to use their own base style when
* they are inflating.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
* @see #RobotoEditText(Context, AttributeSet)
*/
public RobotoEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
onInitTypeface(context, attrs, defStyle);
}
/**
* Setup Roboto typeface.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme).
*/
private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
// Typeface.createFromAsset doesn't work in the layout editor, so skipping.
if (isInEditMode()) {
return;
}
int typefaceValue = 0;
if (attrs != null) {
TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
values.recycle();
}
| Typeface robotoTypeface = RobotoTypefaceManager.obtaintTypeface(context, typefaceValue); |
tvportal/android | app/src/main/java/com/mitechlt/tvportal/play/adapters/MovieAdapter.java | // Path: app/src/main/java/com/mitechlt/tvportal/play/model/Movie.java
// public class Movie {
//
// /**
// * The title of the movie
// */
// public String title;
//
// /**
// * The link to the movie detail page
// */
// public String link;
//
// /**
// * The link to the movie's image
// */
// public String imageUri;
//
// /**
// * The rating of this movie (out of 100)
// */
// public int rating;
//
// /**
// * The year this movie was released
// */
// public String year;
//
// /**
// * The series of "|" separated genres that this movie belongs to
// */
// public String genres;
//
//
// /**
// * @param title the title of the movie
// * @param link the link to the movie detail page
// * @param imageUri the link to the movie's image
// * @param rating the rating of this movie
// * @param year the year this movie was released
// * @param genres the series of "|" separated genres that this movie belongs to
// */
// public Movie(String title, String link, String imageUri, int rating, String year, String genres
// ) {
// this.title = title;
// this.link = link;
// this.imageUri = imageUri;
// this.rating = rating;
// this.year = year;
// this.genres = genres;
// }
// }
| import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.mitechlt.tvportal.play.R;
import com.mitechlt.tvportal.play.model.Movie;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; | package com.mitechlt.tvportal.play.adapters;
public class MovieAdapter extends BaseAdapter {
private final static String TAG = "MovieAdapter";
/**
* The data used in the Adapter
*/ | // Path: app/src/main/java/com/mitechlt/tvportal/play/model/Movie.java
// public class Movie {
//
// /**
// * The title of the movie
// */
// public String title;
//
// /**
// * The link to the movie detail page
// */
// public String link;
//
// /**
// * The link to the movie's image
// */
// public String imageUri;
//
// /**
// * The rating of this movie (out of 100)
// */
// public int rating;
//
// /**
// * The year this movie was released
// */
// public String year;
//
// /**
// * The series of "|" separated genres that this movie belongs to
// */
// public String genres;
//
//
// /**
// * @param title the title of the movie
// * @param link the link to the movie detail page
// * @param imageUri the link to the movie's image
// * @param rating the rating of this movie
// * @param year the year this movie was released
// * @param genres the series of "|" separated genres that this movie belongs to
// */
// public Movie(String title, String link, String imageUri, int rating, String year, String genres
// ) {
// this.title = title;
// this.link = link;
// this.imageUri = imageUri;
// this.rating = rating;
// this.year = year;
// this.genres = genres;
// }
// }
// Path: app/src/main/java/com/mitechlt/tvportal/play/adapters/MovieAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.mitechlt.tvportal.play.R;
import com.mitechlt.tvportal.play.model.Movie;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
package com.mitechlt.tvportal.play.adapters;
public class MovieAdapter extends BaseAdapter {
private final static String TAG = "MovieAdapter";
/**
* The data used in the Adapter
*/ | private final List<Movie> mData = new ArrayList<Movie>(); |
tvportal/android | app/src/main/java/com/mitechlt/tvportal/play/utils/Config.java | // Path: app/src/main/java/com/mitechlt/tvportal/play/databases/FavoritesTable.java
// public class FavoritesTable extends SQLiteOpenHelper {
//
// public static final String TABLE_FAVORITES = "favorites";
// public static final String COLUMN_ID = "_id";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_TITLE = "title";
// public static final String COLUMN_LINK = "link";
// public static final String COLUMN_IMAGE = "image";
// public static final String COLUMN_RATING = "rating";
//
// private static final String DATABASE_NAME = "favorites.db";
// private static final int DATABASE_VERSION = 3;
//
// private static final String DATABASE_CREATE = "create table "
// + TABLE_FAVORITES + "("
// + COLUMN_ID + " integer primary key autoincrement, "
// + COLUMN_TITLE + " text not null, "
// + COLUMN_LINK + " text not null, "
// + COLUMN_IMAGE + " text not null, "
// + COLUMN_TYPE + " text not null, "
// + COLUMN_RATING + " integer);";
//
// public FavoritesTable(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// @Override
// public void onCreate(SQLiteDatabase database) {
// database.execSQL(DATABASE_CREATE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Log.w(FavoritesTable.class.getName(),
// "Upgrading database from version " + oldVersion + " to "
// + newVersion + ", which will destroy all old data"
// );
// db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
// onCreate(db);
// }
//
// }
//
// Path: app/src/main/java/com/mitechlt/tvportal/play/databases/RecentTable.java
// public class RecentTable extends SQLiteOpenHelper {
//
// public static final String TABLE_RECENTS = "recents";
// public static final String COLUMN_ID = "_id";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_TITLE = "title";
// public static final String COLUMN_LINK = "link";
// public static final String COLUMN_SEASON = "season";
// public static final String COLUMN_EPISODE = "episode";
// public static final String COLUMN_IMAGE = "image";
// public static final String COLUMN_NUM_SEASONS = "num_seasons";
// public static final String COLUMN_NUM_EPISODES = "num_episodes";
// public static final String COLUMN_RATING = "rating";
//
// private static final String DATABASE_NAME = "recents.db";
// private static final int DATABASE_VERSION = 2;
//
// private static final String DATABASE_CREATE = "create table "
// + TABLE_RECENTS + "("
// + COLUMN_ID + " integer primary key autoincrement, "
// + COLUMN_TITLE + " text not null, "
// + COLUMN_LINK + " text not null, "
// + COLUMN_TYPE + " text not null, "
// + COLUMN_NUM_EPISODES + " text not null, "
// + COLUMN_NUM_SEASONS + " text not null, "
// + COLUMN_EPISODE + " text, "
// + COLUMN_SEASON + " text, "
// + COLUMN_IMAGE + " text not null, "
// + COLUMN_RATING + " integer);";
//
// public RecentTable(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// @Override
// public void onCreate(SQLiteDatabase database) {
// database.execSQL(DATABASE_CREATE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Log.w(RecentTable.class.getName(),
// "Upgrading database from version " + oldVersion + " to "
// + newVersion + ", which will destroy all old data"
// );
// db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECENTS);
// onCreate(db);
// }
//
// }
| import com.mitechlt.tvportal.play.databases.FavoritesTable;
import com.mitechlt.tvportal.play.databases.RecentTable; | public final static String LAST_WATCHED_SEASON_1 = "last_watched_season_1";
public final static String LAST_WATCHED_EPISODE_1 = "last_watched_episode_1";
public final static String LAST_WATCHED_SEASON_2 = "last_watched_season_2";
public final static String LAST_WATCHED_EPISODE_2 = "last_watched_episode_2";
//google analytics id
public final static String GA_PROPERTY_ID = "UA-51779131-1";
public final static String MOBFOX_AD_ID = "faac43911a78fc8c4abee5d3240b79ef";
public final static String BANNER_AD_UNIT_ID = "ca-app-pub-3835186866229262/6645856032";
public final static String INTERSTITIAL_AD_UNIT_ID = "ca-app-pub-3835186866229262/2891164033";
public final static String TEST_DEVICE_ID_1 = "A67F4255A67458D42E12695CDA84EB78";
public final static String TEST_DEVICE_ID_2 = "34F64524C97707B4";
public final static String REVMOB_AD_ID = "53347dee00b628f37bc0b657";
public final static String SORT_ORDER_FAVORITE = "sort_order_favorite";
public final static String SORT_FAVORITE_DEFAULT = FavoritesTable.COLUMN_ID;
public final static String SORT_FAVORITE_MOVIES_AZ = FavoritesTable.COLUMN_TYPE + ", " + FavoritesTable.COLUMN_TITLE + " COLLATE NOCASE ASC";
public final static String SORT_FAVORITE_TV_SHOWS_AZ = FavoritesTable.COLUMN_TYPE + " DESC" + ", " + FavoritesTable.COLUMN_TITLE + " COLLATE NOCASE ASC";
public final static String SORT_ORDER_RECENT = "sort_order_recent"; | // Path: app/src/main/java/com/mitechlt/tvportal/play/databases/FavoritesTable.java
// public class FavoritesTable extends SQLiteOpenHelper {
//
// public static final String TABLE_FAVORITES = "favorites";
// public static final String COLUMN_ID = "_id";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_TITLE = "title";
// public static final String COLUMN_LINK = "link";
// public static final String COLUMN_IMAGE = "image";
// public static final String COLUMN_RATING = "rating";
//
// private static final String DATABASE_NAME = "favorites.db";
// private static final int DATABASE_VERSION = 3;
//
// private static final String DATABASE_CREATE = "create table "
// + TABLE_FAVORITES + "("
// + COLUMN_ID + " integer primary key autoincrement, "
// + COLUMN_TITLE + " text not null, "
// + COLUMN_LINK + " text not null, "
// + COLUMN_IMAGE + " text not null, "
// + COLUMN_TYPE + " text not null, "
// + COLUMN_RATING + " integer);";
//
// public FavoritesTable(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// @Override
// public void onCreate(SQLiteDatabase database) {
// database.execSQL(DATABASE_CREATE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Log.w(FavoritesTable.class.getName(),
// "Upgrading database from version " + oldVersion + " to "
// + newVersion + ", which will destroy all old data"
// );
// db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
// onCreate(db);
// }
//
// }
//
// Path: app/src/main/java/com/mitechlt/tvportal/play/databases/RecentTable.java
// public class RecentTable extends SQLiteOpenHelper {
//
// public static final String TABLE_RECENTS = "recents";
// public static final String COLUMN_ID = "_id";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_TITLE = "title";
// public static final String COLUMN_LINK = "link";
// public static final String COLUMN_SEASON = "season";
// public static final String COLUMN_EPISODE = "episode";
// public static final String COLUMN_IMAGE = "image";
// public static final String COLUMN_NUM_SEASONS = "num_seasons";
// public static final String COLUMN_NUM_EPISODES = "num_episodes";
// public static final String COLUMN_RATING = "rating";
//
// private static final String DATABASE_NAME = "recents.db";
// private static final int DATABASE_VERSION = 2;
//
// private static final String DATABASE_CREATE = "create table "
// + TABLE_RECENTS + "("
// + COLUMN_ID + " integer primary key autoincrement, "
// + COLUMN_TITLE + " text not null, "
// + COLUMN_LINK + " text not null, "
// + COLUMN_TYPE + " text not null, "
// + COLUMN_NUM_EPISODES + " text not null, "
// + COLUMN_NUM_SEASONS + " text not null, "
// + COLUMN_EPISODE + " text, "
// + COLUMN_SEASON + " text, "
// + COLUMN_IMAGE + " text not null, "
// + COLUMN_RATING + " integer);";
//
// public RecentTable(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// @Override
// public void onCreate(SQLiteDatabase database) {
// database.execSQL(DATABASE_CREATE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Log.w(RecentTable.class.getName(),
// "Upgrading database from version " + oldVersion + " to "
// + newVersion + ", which will destroy all old data"
// );
// db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECENTS);
// onCreate(db);
// }
//
// }
// Path: app/src/main/java/com/mitechlt/tvportal/play/utils/Config.java
import com.mitechlt.tvportal.play.databases.FavoritesTable;
import com.mitechlt.tvportal.play.databases.RecentTable;
public final static String LAST_WATCHED_SEASON_1 = "last_watched_season_1";
public final static String LAST_WATCHED_EPISODE_1 = "last_watched_episode_1";
public final static String LAST_WATCHED_SEASON_2 = "last_watched_season_2";
public final static String LAST_WATCHED_EPISODE_2 = "last_watched_episode_2";
//google analytics id
public final static String GA_PROPERTY_ID = "UA-51779131-1";
public final static String MOBFOX_AD_ID = "faac43911a78fc8c4abee5d3240b79ef";
public final static String BANNER_AD_UNIT_ID = "ca-app-pub-3835186866229262/6645856032";
public final static String INTERSTITIAL_AD_UNIT_ID = "ca-app-pub-3835186866229262/2891164033";
public final static String TEST_DEVICE_ID_1 = "A67F4255A67458D42E12695CDA84EB78";
public final static String TEST_DEVICE_ID_2 = "34F64524C97707B4";
public final static String REVMOB_AD_ID = "53347dee00b628f37bc0b657";
public final static String SORT_ORDER_FAVORITE = "sort_order_favorite";
public final static String SORT_FAVORITE_DEFAULT = FavoritesTable.COLUMN_ID;
public final static String SORT_FAVORITE_MOVIES_AZ = FavoritesTable.COLUMN_TYPE + ", " + FavoritesTable.COLUMN_TITLE + " COLLATE NOCASE ASC";
public final static String SORT_FAVORITE_TV_SHOWS_AZ = FavoritesTable.COLUMN_TYPE + " DESC" + ", " + FavoritesTable.COLUMN_TITLE + " COLLATE NOCASE ASC";
public final static String SORT_ORDER_RECENT = "sort_order_recent"; | public final static String SORT_RECENT_DEFAULT = RecentTable.COLUMN_ID; |
tvportal/android | app/src/main/java/com/mitechlt/tvportal/play/adapters/ChooserAdapter.java | // Path: app/src/main/java/com/devspark/robototextview/widget/RobotoTextView.java
// public class RobotoTextView extends TextView {
//
// /**
// * Simple constructor to use when creating a widget from code.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// */
// public RobotoTextView(Context context) {
// super(context);
// onInitTypeface(context, null, 0);
// }
//
// /**
// * Constructor that is called when inflating a widget from XML. This is called
// * when a widget is being constructed from an XML file, supplying attributes
// * that were specified in the XML file. This version uses a default style of
// * 0, so the only attribute values applied are those in the Context's Theme
// * and the given AttributeSet.
// * <p/>
// * <p/>
// * The method onFinishInflate() will be called after all children have been
// * added.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param attrs The attributes of the XML tag that is inflating the widget.
// * @see #RobotoTextView(Context, AttributeSet, int)
// */
// public RobotoTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// onInitTypeface(context, attrs, 0);
// }
//
// /**
// * Perform inflation from XML and apply a class-specific base style. This
// * constructor of View allows subclasses to use their own base style when
// * they are inflating.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param attrs The attributes of the XML tag that is inflating the widget.
// * @param defStyle The default style to apply to this widget. If 0, no style
// * will be applied (beyond what is included in the theme). This may
// * either be an attribute resource, whose value will be retrieved
// * from the current theme, or an explicit style resource.
// * @see #RobotoTextView(Context, AttributeSet)
// */
// public RobotoTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// onInitTypeface(context, attrs, defStyle);
// }
//
// /**
// * Setup Roboto typeface.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param attrs The attributes of the XML tag that is inflating the widget.
// * @param defStyle The default style to apply to this widget. If 0, no style
// * will be applied (beyond what is included in the theme).
// */
// private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
// // Typeface.createFromAsset doesn't work in the layout editor, so skipping.
// if (isInEditMode()) {
// return;
// }
//
// int typefaceValue = 0;
// if (attrs != null) {
// TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
// typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
// values.recycle();
// }
//
// Typeface robotoTypeface = RobotoTypefaceManager.obtaintTypeface(context, typefaceValue);
// setTypeface(robotoTypeface);
// }
//
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.devspark.robototextview.widget.RobotoTextView;
import com.mitechlt.tvportal.play.R; | }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Recycle the ViewHolder
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_social, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Bind the data
holder.mTitle.setText(mTitles[position]);
holder.mIcon.setImageResource(mIcons.getResourceId(position, -1));
return convertView;
}
@Override
public boolean hasStableIds() {
return true;
}
/**
* ViewHolder implementation
*/
private static final class ViewHolder {
| // Path: app/src/main/java/com/devspark/robototextview/widget/RobotoTextView.java
// public class RobotoTextView extends TextView {
//
// /**
// * Simple constructor to use when creating a widget from code.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// */
// public RobotoTextView(Context context) {
// super(context);
// onInitTypeface(context, null, 0);
// }
//
// /**
// * Constructor that is called when inflating a widget from XML. This is called
// * when a widget is being constructed from an XML file, supplying attributes
// * that were specified in the XML file. This version uses a default style of
// * 0, so the only attribute values applied are those in the Context's Theme
// * and the given AttributeSet.
// * <p/>
// * <p/>
// * The method onFinishInflate() will be called after all children have been
// * added.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param attrs The attributes of the XML tag that is inflating the widget.
// * @see #RobotoTextView(Context, AttributeSet, int)
// */
// public RobotoTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// onInitTypeface(context, attrs, 0);
// }
//
// /**
// * Perform inflation from XML and apply a class-specific base style. This
// * constructor of View allows subclasses to use their own base style when
// * they are inflating.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param attrs The attributes of the XML tag that is inflating the widget.
// * @param defStyle The default style to apply to this widget. If 0, no style
// * will be applied (beyond what is included in the theme). This may
// * either be an attribute resource, whose value will be retrieved
// * from the current theme, or an explicit style resource.
// * @see #RobotoTextView(Context, AttributeSet)
// */
// public RobotoTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// onInitTypeface(context, attrs, defStyle);
// }
//
// /**
// * Setup Roboto typeface.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param attrs The attributes of the XML tag that is inflating the widget.
// * @param defStyle The default style to apply to this widget. If 0, no style
// * will be applied (beyond what is included in the theme).
// */
// private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
// // Typeface.createFromAsset doesn't work in the layout editor, so skipping.
// if (isInEditMode()) {
// return;
// }
//
// int typefaceValue = 0;
// if (attrs != null) {
// TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
// typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
// values.recycle();
// }
//
// Typeface robotoTypeface = RobotoTypefaceManager.obtaintTypeface(context, typefaceValue);
// setTypeface(robotoTypeface);
// }
//
// }
// Path: app/src/main/java/com/mitechlt/tvportal/play/adapters/ChooserAdapter.java
import android.content.Context;
import android.content.res.TypedArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.devspark.robototextview.widget.RobotoTextView;
import com.mitechlt.tvportal.play.R;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Recycle the ViewHolder
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_social, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Bind the data
holder.mTitle.setText(mTitles[position]);
holder.mIcon.setImageResource(mIcons.getResourceId(position, -1));
return convertView;
}
@Override
public boolean hasStableIds() {
return true;
}
/**
* ViewHolder implementation
*/
private static final class ViewHolder {
| private final RobotoTextView mTitle; |
tvportal/android | app/src/main/java/com/devspark/robototextview/widget/RobotoCheckBox.java | // Path: app/src/main/java/com/devspark/robototextview/RobotoTypefaceManager.java
// public class RobotoTypefaceManager {
//
// /*
// * Available values for the "typeface" attribute.
// */
// private final static int ROBOTO_LIGHT = 0;
// private final static int ROBOTO_REGULAR = 1;
//
// /**
// * Array of created typefaces for later reused.
// */
// private final static SparseArray<Typeface> mTypefaces = new SparseArray<Typeface>(20);
//
// /**
// * Obtain typeface.
// *
// * @param context The Context the widget is running in, through which it can access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return specify {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// public static Typeface obtaintTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface = mTypefaces.get(typefaceValue);
// if (typeface == null) {
// typeface = createTypeface(context, typefaceValue);
// mTypefaces.put(typefaceValue, typeface);
// }
// return typeface;
// }
//
// /**
// * Create typeface from assets.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return Roboto {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// private static Typeface createTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface;
// switch (typefaceValue) {
// case ROBOTO_LIGHT:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
// break;
// case ROBOTO_REGULAR:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf");
// break;
// default:
// throw new IllegalArgumentException("Unknown `typeface` attribute value " + typefaceValue);
// }
// return typeface;
// }
//
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.CheckBox;
import com.devspark.robototextview.RobotoTypefaceManager;
import com.mitechlt.tvportal.play.R; | /*
* Copyright (C) 2013 Evgeny Shishkin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.devspark.robototextview.widget;
/**
* Implementation of a {@link CheckBox} with native support for all the Roboto fonts.
*
* @author Evgeny Shishkin
*/
public class RobotoCheckBox extends CheckBox {
/**
* Simple constructor to use when creating a widget from code.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
*/
public RobotoCheckBox(Context context) {
super(context);
onInitTypeface(context, null, 0);
}
/**
* Constructor that is called when inflating a widget from XML. This is called
* when a widget is being constructed from an XML file, supplying attributes
* that were specified in the XML file. This version uses a default style of
* 0, so the only attribute values applied are those in the Context's Theme
* and the given AttributeSet.
* <p/>
* <p/>
* The method onFinishInflate() will be called after all children have been
* added.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @see #RobotoCheckBox(Context, android.util.AttributeSet, int)
*/
public RobotoCheckBox(Context context, AttributeSet attrs) {
super(context, attrs);
onInitTypeface(context, attrs, 0);
}
/**
* Perform inflation from XML and apply a class-specific base style. This
* constructor of View allows subclasses to use their own base style when
* they are inflating.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
* @see #RobotoCheckBox(Context, AttributeSet)
*/
public RobotoCheckBox(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
onInitTypeface(context, attrs, defStyle);
}
/**
* Setup Roboto typeface.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme).
*/
private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
// Typeface.createFromAsset doesn't work in the layout editor, so skipping.
if (isInEditMode()) {
return;
}
int typefaceValue = 0;
if (attrs != null) {
TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
values.recycle();
}
| // Path: app/src/main/java/com/devspark/robototextview/RobotoTypefaceManager.java
// public class RobotoTypefaceManager {
//
// /*
// * Available values for the "typeface" attribute.
// */
// private final static int ROBOTO_LIGHT = 0;
// private final static int ROBOTO_REGULAR = 1;
//
// /**
// * Array of created typefaces for later reused.
// */
// private final static SparseArray<Typeface> mTypefaces = new SparseArray<Typeface>(20);
//
// /**
// * Obtain typeface.
// *
// * @param context The Context the widget is running in, through which it can access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return specify {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// public static Typeface obtaintTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface = mTypefaces.get(typefaceValue);
// if (typeface == null) {
// typeface = createTypeface(context, typefaceValue);
// mTypefaces.put(typefaceValue, typeface);
// }
// return typeface;
// }
//
// /**
// * Create typeface from assets.
// *
// * @param context The Context the widget is running in, through which it can
// * access the current theme, resources, etc.
// * @param typefaceValue The value of "typeface" attribute
// * @return Roboto {@link Typeface}
// * @throws IllegalArgumentException if unknown `typeface` attribute value.
// */
// private static Typeface createTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
// Typeface typeface;
// switch (typefaceValue) {
// case ROBOTO_LIGHT:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
// break;
// case ROBOTO_REGULAR:
// typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf");
// break;
// default:
// throw new IllegalArgumentException("Unknown `typeface` attribute value " + typefaceValue);
// }
// return typeface;
// }
//
// }
// Path: app/src/main/java/com/devspark/robototextview/widget/RobotoCheckBox.java
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.CheckBox;
import com.devspark.robototextview.RobotoTypefaceManager;
import com.mitechlt.tvportal.play.R;
/*
* Copyright (C) 2013 Evgeny Shishkin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.devspark.robototextview.widget;
/**
* Implementation of a {@link CheckBox} with native support for all the Roboto fonts.
*
* @author Evgeny Shishkin
*/
public class RobotoCheckBox extends CheckBox {
/**
* Simple constructor to use when creating a widget from code.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
*/
public RobotoCheckBox(Context context) {
super(context);
onInitTypeface(context, null, 0);
}
/**
* Constructor that is called when inflating a widget from XML. This is called
* when a widget is being constructed from an XML file, supplying attributes
* that were specified in the XML file. This version uses a default style of
* 0, so the only attribute values applied are those in the Context's Theme
* and the given AttributeSet.
* <p/>
* <p/>
* The method onFinishInflate() will be called after all children have been
* added.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @see #RobotoCheckBox(Context, android.util.AttributeSet, int)
*/
public RobotoCheckBox(Context context, AttributeSet attrs) {
super(context, attrs);
onInitTypeface(context, attrs, 0);
}
/**
* Perform inflation from XML and apply a class-specific base style. This
* constructor of View allows subclasses to use their own base style when
* they are inflating.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
* @see #RobotoCheckBox(Context, AttributeSet)
*/
public RobotoCheckBox(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
onInitTypeface(context, attrs, defStyle);
}
/**
* Setup Roboto typeface.
*
* @param context The Context the widget is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the widget.
* @param defStyle The default style to apply to this widget. If 0, no style
* will be applied (beyond what is included in the theme).
*/
private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
// Typeface.createFromAsset doesn't work in the layout editor, so skipping.
if (isInEditMode()) {
return;
}
int typefaceValue = 0;
if (attrs != null) {
TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
values.recycle();
}
| Typeface robotoTypeface = RobotoTypefaceManager.obtaintTypeface(context, typefaceValue); |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/filters/CsrfProtectionFilter.java | // Path: src/main/java/org/owasp/oneliner/exceptions/BadCsrfProtectionTokenException.java
// public class BadCsrfProtectionTokenException extends RuntimeException {
//
// public static final BadCsrfProtectionTokenException INSTANCE = new BadCsrfProtectionTokenException();
// public final ReasonWrapper reasonWrapper;
// public final Reason reason;
//
// private BadCsrfProtectionTokenException() {
// this.reason = Reason.FORBIDDEN;
// this.reasonWrapper = new ReasonWrapper(reason);
// this.setStackTrace(new StackTraceElement[]{}); // Empty stack trace since this is a signaling exception
// }
//
// public enum Reason {
// FORBIDDEN (Response.Status.FORBIDDEN);
//
// public final Response.Status status;
// Reason(Response.Status status) {
// this.status = status;
// }
// }
//
// @XmlRootElement
// public static class ReasonWrapper {
// public final Reason reason;
// public ReasonWrapper(Reason reason) { this.reason = reason; }
// private ReasonWrapper() { this.reason = null; } // here for JAXB
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/util/RandomAlphaNumericString.java
// public static boolean isValidAlphaNumericString(String string) {
// int length = string.length();
// if (length > MAX_SIZE) {
// return false;
// }
// for (int index=0; index < length; index++) {
// if (CHARS.indexOf(string.charAt(index)) == -1) {
// if (logger.isDebugEnabled()) { logger.debug("Found illegal cookie character: " + string.charAt(index)); }
// return false;
// }
// }
// return true;
// }
| import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import com.sun.jersey.spi.container.ResourceFilter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.BadCsrfProtectionTokenException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import static org.owasp.oneliner.util.RandomAlphaNumericString.isValidAlphaNumericString; | package org.owasp.oneliner.filters;
/**
* Author: @johnwilander
* Date: 2010-nov-07
*/
public class CsrfProtectionFilter implements ResourceFilter, ContainerRequestFilter {
private static final Log logger = LogFactory.getLog(CsrfProtectionFilter.class);
public static final String SIMPLE_COOKIE_NAME = "cookieToken";
public static final int RANDOM_COOKIE_NAME_LENGTH = 16;
public static final int RANDOM_COOKIE_VALUE_LENGTH = 16;
public static final String PARAM_TOKEN = "paramToken";
private HttpServletRequest httpServletRequest;
public CsrfProtectionFilter(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
| // Path: src/main/java/org/owasp/oneliner/exceptions/BadCsrfProtectionTokenException.java
// public class BadCsrfProtectionTokenException extends RuntimeException {
//
// public static final BadCsrfProtectionTokenException INSTANCE = new BadCsrfProtectionTokenException();
// public final ReasonWrapper reasonWrapper;
// public final Reason reason;
//
// private BadCsrfProtectionTokenException() {
// this.reason = Reason.FORBIDDEN;
// this.reasonWrapper = new ReasonWrapper(reason);
// this.setStackTrace(new StackTraceElement[]{}); // Empty stack trace since this is a signaling exception
// }
//
// public enum Reason {
// FORBIDDEN (Response.Status.FORBIDDEN);
//
// public final Response.Status status;
// Reason(Response.Status status) {
// this.status = status;
// }
// }
//
// @XmlRootElement
// public static class ReasonWrapper {
// public final Reason reason;
// public ReasonWrapper(Reason reason) { this.reason = reason; }
// private ReasonWrapper() { this.reason = null; } // here for JAXB
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/util/RandomAlphaNumericString.java
// public static boolean isValidAlphaNumericString(String string) {
// int length = string.length();
// if (length > MAX_SIZE) {
// return false;
// }
// for (int index=0; index < length; index++) {
// if (CHARS.indexOf(string.charAt(index)) == -1) {
// if (logger.isDebugEnabled()) { logger.debug("Found illegal cookie character: " + string.charAt(index)); }
// return false;
// }
// }
// return true;
// }
// Path: src/main/java/org/owasp/oneliner/filters/CsrfProtectionFilter.java
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import com.sun.jersey.spi.container.ResourceFilter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.BadCsrfProtectionTokenException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import static org.owasp.oneliner.util.RandomAlphaNumericString.isValidAlphaNumericString;
package org.owasp.oneliner.filters;
/**
* Author: @johnwilander
* Date: 2010-nov-07
*/
public class CsrfProtectionFilter implements ResourceFilter, ContainerRequestFilter {
private static final Log logger = LogFactory.getLog(CsrfProtectionFilter.class);
public static final String SIMPLE_COOKIE_NAME = "cookieToken";
public static final int RANDOM_COOKIE_NAME_LENGTH = 16;
public static final int RANDOM_COOKIE_VALUE_LENGTH = 16;
public static final String PARAM_TOKEN = "paramToken";
private HttpServletRequest httpServletRequest;
public CsrfProtectionFilter(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
| public ContainerRequest filter(ContainerRequest containerRequest) throws BadCsrfProtectionTokenException { |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/filters/CsrfProtectionFilter.java | // Path: src/main/java/org/owasp/oneliner/exceptions/BadCsrfProtectionTokenException.java
// public class BadCsrfProtectionTokenException extends RuntimeException {
//
// public static final BadCsrfProtectionTokenException INSTANCE = new BadCsrfProtectionTokenException();
// public final ReasonWrapper reasonWrapper;
// public final Reason reason;
//
// private BadCsrfProtectionTokenException() {
// this.reason = Reason.FORBIDDEN;
// this.reasonWrapper = new ReasonWrapper(reason);
// this.setStackTrace(new StackTraceElement[]{}); // Empty stack trace since this is a signaling exception
// }
//
// public enum Reason {
// FORBIDDEN (Response.Status.FORBIDDEN);
//
// public final Response.Status status;
// Reason(Response.Status status) {
// this.status = status;
// }
// }
//
// @XmlRootElement
// public static class ReasonWrapper {
// public final Reason reason;
// public ReasonWrapper(Reason reason) { this.reason = reason; }
// private ReasonWrapper() { this.reason = null; } // here for JAXB
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/util/RandomAlphaNumericString.java
// public static boolean isValidAlphaNumericString(String string) {
// int length = string.length();
// if (length > MAX_SIZE) {
// return false;
// }
// for (int index=0; index < length; index++) {
// if (CHARS.indexOf(string.charAt(index)) == -1) {
// if (logger.isDebugEnabled()) { logger.debug("Found illegal cookie character: " + string.charAt(index)); }
// return false;
// }
// }
// return true;
// }
| import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import com.sun.jersey.spi.container.ResourceFilter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.BadCsrfProtectionTokenException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import static org.owasp.oneliner.util.RandomAlphaNumericString.isValidAlphaNumericString; | throw BadCsrfProtectionTokenException.INSTANCE;
}
}
public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
public ContainerRequestFilter getRequestFilter() {
return this;
}
public ContainerResponseFilter getResponseFilter() {
return null; // No response filter
}
// Private help methods
private String getCsrfProtectionTokenCookie() {
int numOfSimpleCookies = 0, numOfRandomCookies = 0;
boolean foundRandomCookie = false;
Cookie[] cookies = httpServletRequest.getCookies();
String csrfProtectionCookieValue = null;
for (Cookie cookie : cookies) {
String cookieName = cookie.getName();
if (logger.isDebugEnabled()) { logger.debug("Checking cookie: " + cookieName); }
if (!foundRandomCookie && SIMPLE_COOKIE_NAME.equals(cookieName)) {
csrfProtectionCookieValue = cookie.getValue();
numOfSimpleCookies++;
} else if (cookieName.length() == RANDOM_COOKIE_NAME_LENGTH && | // Path: src/main/java/org/owasp/oneliner/exceptions/BadCsrfProtectionTokenException.java
// public class BadCsrfProtectionTokenException extends RuntimeException {
//
// public static final BadCsrfProtectionTokenException INSTANCE = new BadCsrfProtectionTokenException();
// public final ReasonWrapper reasonWrapper;
// public final Reason reason;
//
// private BadCsrfProtectionTokenException() {
// this.reason = Reason.FORBIDDEN;
// this.reasonWrapper = new ReasonWrapper(reason);
// this.setStackTrace(new StackTraceElement[]{}); // Empty stack trace since this is a signaling exception
// }
//
// public enum Reason {
// FORBIDDEN (Response.Status.FORBIDDEN);
//
// public final Response.Status status;
// Reason(Response.Status status) {
// this.status = status;
// }
// }
//
// @XmlRootElement
// public static class ReasonWrapper {
// public final Reason reason;
// public ReasonWrapper(Reason reason) { this.reason = reason; }
// private ReasonWrapper() { this.reason = null; } // here for JAXB
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/util/RandomAlphaNumericString.java
// public static boolean isValidAlphaNumericString(String string) {
// int length = string.length();
// if (length > MAX_SIZE) {
// return false;
// }
// for (int index=0; index < length; index++) {
// if (CHARS.indexOf(string.charAt(index)) == -1) {
// if (logger.isDebugEnabled()) { logger.debug("Found illegal cookie character: " + string.charAt(index)); }
// return false;
// }
// }
// return true;
// }
// Path: src/main/java/org/owasp/oneliner/filters/CsrfProtectionFilter.java
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import com.sun.jersey.spi.container.ResourceFilter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.BadCsrfProtectionTokenException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import static org.owasp.oneliner.util.RandomAlphaNumericString.isValidAlphaNumericString;
throw BadCsrfProtectionTokenException.INSTANCE;
}
}
public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
public ContainerRequestFilter getRequestFilter() {
return this;
}
public ContainerResponseFilter getResponseFilter() {
return null; // No response filter
}
// Private help methods
private String getCsrfProtectionTokenCookie() {
int numOfSimpleCookies = 0, numOfRandomCookies = 0;
boolean foundRandomCookie = false;
Cookie[] cookies = httpServletRequest.getCookies();
String csrfProtectionCookieValue = null;
for (Cookie cookie : cookies) {
String cookieName = cookie.getName();
if (logger.isDebugEnabled()) { logger.debug("Checking cookie: " + cookieName); }
if (!foundRandomCookie && SIMPLE_COOKIE_NAME.equals(cookieName)) {
csrfProtectionCookieValue = cookie.getValue();
numOfSimpleCookies++;
} else if (cookieName.length() == RANDOM_COOKIE_NAME_LENGTH && | isValidAlphaNumericString(cookieName)) { |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/user/UserFactory.java | // Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
| import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import javax.annotation.Resource; | package org.owasp.oneliner.user;
/**
* Author: @johnwilander
* Date: 2010-12-18
*/
public class UserFactory {
@Resource | // Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
// Path: src/main/java/org/owasp/oneliner/user/UserFactory.java
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import javax.annotation.Resource;
package org.owasp.oneliner.user;
/**
* Author: @johnwilander
* Date: 2010-12-18
*/
public class UserFactory {
@Resource | HashedPasswordFactory hashedPasswordFactory; |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/user/UserFactory.java | // Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
| import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import javax.annotation.Resource; | package org.owasp.oneliner.user;
/**
* Author: @johnwilander
* Date: 2010-12-18
*/
public class UserFactory {
@Resource
HashedPasswordFactory hashedPasswordFactory;
public User createUser(String userName, String nickName, String password) {
return createUser(userName, nickName, hashedPasswordFactory.createHashedPassword(password));
}
| // Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
// Path: src/main/java/org/owasp/oneliner/user/UserFactory.java
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import javax.annotation.Resource;
package org.owasp.oneliner.user;
/**
* Author: @johnwilander
* Date: 2010-12-18
*/
public class UserFactory {
@Resource
HashedPasswordFactory hashedPasswordFactory;
public User createUser(String userName, String nickName, String password) {
return createUser(userName, nickName, hashedPasswordFactory.createHashedPassword(password));
}
| public User createUser(String userName, String nickName, HashedPassword hashedPassword) { |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/user/User.java | // Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/session/SessionId.java
// public class SessionId {
// private static final Log logger = LogFactory.getLog(SessionId.class);
// private static final long SESSION_MAX_AGE_IN_MILLIS = 1000L * 60 * 60 * 24; // One day
//
// private final String sessionId;
// private final Date starts;
// private final Date expires;
//
// public Date starts() {
// return starts;
// }
//
// public Date expires() {
// return expires;
// }
//
// public int maxAgeInSeconds() {
// int currentMaxAgeInSeconds = (int)((expires.getTime() - System.currentTimeMillis()) / 1000);
// int returnValue;
// return currentMaxAgeInSeconds > 0 ? currentMaxAgeInSeconds : 0;
// }
//
// @Override
// public String toString() {
// return sessionId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof SessionId)) return false;
//
// SessionId sessionId1 = (SessionId) o;
//
// if (sessionId != null ? !sessionId.equals(sessionId1.sessionId) : sessionId1.sessionId != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return sessionId != null ? sessionId.hashCode() : 0;
// }
//
// // Package default to give access to factory class only
// SessionId(String sessionId) {
// this.sessionId = sessionId;
// this.starts = new Date();
// this.expires = new Date(System.currentTimeMillis() + SESSION_MAX_AGE_IN_MILLIS);
// if(logger.isDebugEnabled()) { logger.debug("New session id: " + sessionId + ", expires " + expires); }
// }
//
// // Here for JAXB
// public SessionId() {
// this.sessionId = null;
// this.starts = null;
// this.expires = null;
// }
// }
| import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.session.SessionId;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date; | package org.owasp.oneliner.user;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement
public class User {
public final String userName;
public final String nickName; | // Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/session/SessionId.java
// public class SessionId {
// private static final Log logger = LogFactory.getLog(SessionId.class);
// private static final long SESSION_MAX_AGE_IN_MILLIS = 1000L * 60 * 60 * 24; // One day
//
// private final String sessionId;
// private final Date starts;
// private final Date expires;
//
// public Date starts() {
// return starts;
// }
//
// public Date expires() {
// return expires;
// }
//
// public int maxAgeInSeconds() {
// int currentMaxAgeInSeconds = (int)((expires.getTime() - System.currentTimeMillis()) / 1000);
// int returnValue;
// return currentMaxAgeInSeconds > 0 ? currentMaxAgeInSeconds : 0;
// }
//
// @Override
// public String toString() {
// return sessionId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof SessionId)) return false;
//
// SessionId sessionId1 = (SessionId) o;
//
// if (sessionId != null ? !sessionId.equals(sessionId1.sessionId) : sessionId1.sessionId != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return sessionId != null ? sessionId.hashCode() : 0;
// }
//
// // Package default to give access to factory class only
// SessionId(String sessionId) {
// this.sessionId = sessionId;
// this.starts = new Date();
// this.expires = new Date(System.currentTimeMillis() + SESSION_MAX_AGE_IN_MILLIS);
// if(logger.isDebugEnabled()) { logger.debug("New session id: " + sessionId + ", expires " + expires); }
// }
//
// // Here for JAXB
// public SessionId() {
// this.sessionId = null;
// this.starts = null;
// this.expires = null;
// }
// }
// Path: src/main/java/org/owasp/oneliner/user/User.java
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.session.SessionId;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;
package org.owasp.oneliner.user;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement
public class User {
public final String userName;
public final String nickName; | private HashedPassword hashedPassword; |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/user/User.java | // Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/session/SessionId.java
// public class SessionId {
// private static final Log logger = LogFactory.getLog(SessionId.class);
// private static final long SESSION_MAX_AGE_IN_MILLIS = 1000L * 60 * 60 * 24; // One day
//
// private final String sessionId;
// private final Date starts;
// private final Date expires;
//
// public Date starts() {
// return starts;
// }
//
// public Date expires() {
// return expires;
// }
//
// public int maxAgeInSeconds() {
// int currentMaxAgeInSeconds = (int)((expires.getTime() - System.currentTimeMillis()) / 1000);
// int returnValue;
// return currentMaxAgeInSeconds > 0 ? currentMaxAgeInSeconds : 0;
// }
//
// @Override
// public String toString() {
// return sessionId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof SessionId)) return false;
//
// SessionId sessionId1 = (SessionId) o;
//
// if (sessionId != null ? !sessionId.equals(sessionId1.sessionId) : sessionId1.sessionId != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return sessionId != null ? sessionId.hashCode() : 0;
// }
//
// // Package default to give access to factory class only
// SessionId(String sessionId) {
// this.sessionId = sessionId;
// this.starts = new Date();
// this.expires = new Date(System.currentTimeMillis() + SESSION_MAX_AGE_IN_MILLIS);
// if(logger.isDebugEnabled()) { logger.debug("New session id: " + sessionId + ", expires " + expires); }
// }
//
// // Here for JAXB
// public SessionId() {
// this.sessionId = null;
// this.starts = null;
// this.expires = null;
// }
// }
| import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.session.SessionId;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date; | package org.owasp.oneliner.user;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement
public class User {
public final String userName;
public final String nickName;
private HashedPassword hashedPassword; | // Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/session/SessionId.java
// public class SessionId {
// private static final Log logger = LogFactory.getLog(SessionId.class);
// private static final long SESSION_MAX_AGE_IN_MILLIS = 1000L * 60 * 60 * 24; // One day
//
// private final String sessionId;
// private final Date starts;
// private final Date expires;
//
// public Date starts() {
// return starts;
// }
//
// public Date expires() {
// return expires;
// }
//
// public int maxAgeInSeconds() {
// int currentMaxAgeInSeconds = (int)((expires.getTime() - System.currentTimeMillis()) / 1000);
// int returnValue;
// return currentMaxAgeInSeconds > 0 ? currentMaxAgeInSeconds : 0;
// }
//
// @Override
// public String toString() {
// return sessionId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof SessionId)) return false;
//
// SessionId sessionId1 = (SessionId) o;
//
// if (sessionId != null ? !sessionId.equals(sessionId1.sessionId) : sessionId1.sessionId != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return sessionId != null ? sessionId.hashCode() : 0;
// }
//
// // Package default to give access to factory class only
// SessionId(String sessionId) {
// this.sessionId = sessionId;
// this.starts = new Date();
// this.expires = new Date(System.currentTimeMillis() + SESSION_MAX_AGE_IN_MILLIS);
// if(logger.isDebugEnabled()) { logger.debug("New session id: " + sessionId + ", expires " + expires); }
// }
//
// // Here for JAXB
// public SessionId() {
// this.sessionId = null;
// this.starts = null;
// this.expires = null;
// }
// }
// Path: src/main/java/org/owasp/oneliner/user/User.java
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.session.SessionId;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;
package org.owasp.oneliner.user;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement
public class User {
public final String userName;
public final String nickName;
private HashedPassword hashedPassword; | private SessionId sessionId; |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/persistence/OneLinerDb.java | // Path: src/main/java/org/owasp/oneliner/oneLiner/DbSize.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlRootElement
// public class DbSize {
// private int size;
// private Date timeStamp;
//
// public int getSize() {
// return size;
// }
//
// public void setSize(int size) {
// this.size = size;
// }
//
// public Date getTimeStamp() {
// return timeStamp;
// }
//
// public void setTimeStamp(Date timeStamp) {
// this.timeStamp = timeStamp;
// }
//
// @Override
// public String toString() {
// return "DbSize{" +
// "size=" + size +
// ", timeStamp=" + timeStamp +
// '}';
// }
//
// public DbSize(int size) {
// this.size = size;
// this.timeStamp = new Date();
// }
//
// public DbSize() {}; // Here for JAXB
// }
//
// Path: src/main/java/org/owasp/oneliner/oneLiner/OneLiner.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlRootElement
// public class OneLiner {
// protected int id;
// protected String nickName;
// protected String oneLiner;
// protected Date timestamp;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public void setNickName(String nickName) {
// this.nickName = nickName;
// }
//
// public String getOneLiner() {
// return oneLiner;
// }
//
// public void setOneLiner(String oneLiner) {
// this.oneLiner = oneLiner;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// OneLiner(int id, String nickName, String oneLiner, Date timestamp) throws IllegalArgumentException {
// if (nickOK(nickName) && oneLinerOK(oneLiner)) {
// this.id = id;
// this.nickName = nickName;
// this.oneLiner = oneLiner;
// this.timestamp = timestamp;
// } else {
// throw new IllegalArgumentException();
// }
// }
//
// public OneLiner() { } // Here for JAX-B
//
// private boolean nickOK(String nickName) {
// final int MAX_NICK_NAME_SIZE = 32;
// return (nickName != null && !"".equals(nickName) && nickName.length() <= MAX_NICK_NAME_SIZE);
// }
//
// private boolean oneLinerOK(String oneLiner) {
// final int MAX_ONE_LINER_SIZE = 160;
// return (oneLiner != null && !"".equals(oneLiner) && oneLiner.length() <= MAX_ONE_LINER_SIZE);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other instanceof OneLiner) {
// OneLiner otherOneLiner = (OneLiner)other;
// return id == otherOneLiner.id &&
// nickName != null && nickName.equals(otherOneLiner.nickName) &&
// oneLiner != null && oneLiner.equals(otherOneLiner.oneLiner);
// } else {
// return false;
// }
// }
//
// @Override
// public String toString() {
// return "{" + id + " " + nickName + ":" + oneLiner + ":" + timestamp + "}";
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.oneLiner.DbSize;
import org.owasp.oneliner.oneLiner.OneLiner;
import java.util.ArrayList;
import java.util.List; | package org.owasp.oneliner.persistence;
/**
* Author: @johnwilander
* Date: 2010-12-12
*/
public class OneLinerDb {
private static final Log logger = LogFactory.getLog(OneLinerDb.class); | // Path: src/main/java/org/owasp/oneliner/oneLiner/DbSize.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlRootElement
// public class DbSize {
// private int size;
// private Date timeStamp;
//
// public int getSize() {
// return size;
// }
//
// public void setSize(int size) {
// this.size = size;
// }
//
// public Date getTimeStamp() {
// return timeStamp;
// }
//
// public void setTimeStamp(Date timeStamp) {
// this.timeStamp = timeStamp;
// }
//
// @Override
// public String toString() {
// return "DbSize{" +
// "size=" + size +
// ", timeStamp=" + timeStamp +
// '}';
// }
//
// public DbSize(int size) {
// this.size = size;
// this.timeStamp = new Date();
// }
//
// public DbSize() {}; // Here for JAXB
// }
//
// Path: src/main/java/org/owasp/oneliner/oneLiner/OneLiner.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlRootElement
// public class OneLiner {
// protected int id;
// protected String nickName;
// protected String oneLiner;
// protected Date timestamp;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public void setNickName(String nickName) {
// this.nickName = nickName;
// }
//
// public String getOneLiner() {
// return oneLiner;
// }
//
// public void setOneLiner(String oneLiner) {
// this.oneLiner = oneLiner;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// OneLiner(int id, String nickName, String oneLiner, Date timestamp) throws IllegalArgumentException {
// if (nickOK(nickName) && oneLinerOK(oneLiner)) {
// this.id = id;
// this.nickName = nickName;
// this.oneLiner = oneLiner;
// this.timestamp = timestamp;
// } else {
// throw new IllegalArgumentException();
// }
// }
//
// public OneLiner() { } // Here for JAX-B
//
// private boolean nickOK(String nickName) {
// final int MAX_NICK_NAME_SIZE = 32;
// return (nickName != null && !"".equals(nickName) && nickName.length() <= MAX_NICK_NAME_SIZE);
// }
//
// private boolean oneLinerOK(String oneLiner) {
// final int MAX_ONE_LINER_SIZE = 160;
// return (oneLiner != null && !"".equals(oneLiner) && oneLiner.length() <= MAX_ONE_LINER_SIZE);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other instanceof OneLiner) {
// OneLiner otherOneLiner = (OneLiner)other;
// return id == otherOneLiner.id &&
// nickName != null && nickName.equals(otherOneLiner.nickName) &&
// oneLiner != null && oneLiner.equals(otherOneLiner.oneLiner);
// } else {
// return false;
// }
// }
//
// @Override
// public String toString() {
// return "{" + id + " " + nickName + ":" + oneLiner + ":" + timestamp + "}";
// }
// }
// Path: src/main/java/org/owasp/oneliner/persistence/OneLinerDb.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.oneLiner.DbSize;
import org.owasp.oneliner.oneLiner.OneLiner;
import java.util.ArrayList;
import java.util.List;
package org.owasp.oneliner.persistence;
/**
* Author: @johnwilander
* Date: 2010-12-12
*/
public class OneLinerDb {
private static final Log logger = LogFactory.getLog(OneLinerDb.class); | private List<OneLiner> initialList; |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/persistence/OneLinerDb.java | // Path: src/main/java/org/owasp/oneliner/oneLiner/DbSize.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlRootElement
// public class DbSize {
// private int size;
// private Date timeStamp;
//
// public int getSize() {
// return size;
// }
//
// public void setSize(int size) {
// this.size = size;
// }
//
// public Date getTimeStamp() {
// return timeStamp;
// }
//
// public void setTimeStamp(Date timeStamp) {
// this.timeStamp = timeStamp;
// }
//
// @Override
// public String toString() {
// return "DbSize{" +
// "size=" + size +
// ", timeStamp=" + timeStamp +
// '}';
// }
//
// public DbSize(int size) {
// this.size = size;
// this.timeStamp = new Date();
// }
//
// public DbSize() {}; // Here for JAXB
// }
//
// Path: src/main/java/org/owasp/oneliner/oneLiner/OneLiner.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlRootElement
// public class OneLiner {
// protected int id;
// protected String nickName;
// protected String oneLiner;
// protected Date timestamp;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public void setNickName(String nickName) {
// this.nickName = nickName;
// }
//
// public String getOneLiner() {
// return oneLiner;
// }
//
// public void setOneLiner(String oneLiner) {
// this.oneLiner = oneLiner;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// OneLiner(int id, String nickName, String oneLiner, Date timestamp) throws IllegalArgumentException {
// if (nickOK(nickName) && oneLinerOK(oneLiner)) {
// this.id = id;
// this.nickName = nickName;
// this.oneLiner = oneLiner;
// this.timestamp = timestamp;
// } else {
// throw new IllegalArgumentException();
// }
// }
//
// public OneLiner() { } // Here for JAX-B
//
// private boolean nickOK(String nickName) {
// final int MAX_NICK_NAME_SIZE = 32;
// return (nickName != null && !"".equals(nickName) && nickName.length() <= MAX_NICK_NAME_SIZE);
// }
//
// private boolean oneLinerOK(String oneLiner) {
// final int MAX_ONE_LINER_SIZE = 160;
// return (oneLiner != null && !"".equals(oneLiner) && oneLiner.length() <= MAX_ONE_LINER_SIZE);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other instanceof OneLiner) {
// OneLiner otherOneLiner = (OneLiner)other;
// return id == otherOneLiner.id &&
// nickName != null && nickName.equals(otherOneLiner.nickName) &&
// oneLiner != null && oneLiner.equals(otherOneLiner.oneLiner);
// } else {
// return false;
// }
// }
//
// @Override
// public String toString() {
// return "{" + id + " " + nickName + ":" + oneLiner + ":" + timestamp + "}";
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.oneLiner.DbSize;
import org.owasp.oneliner.oneLiner.OneLiner;
import java.util.ArrayList;
import java.util.List; | package org.owasp.oneliner.persistence;
/**
* Author: @johnwilander
* Date: 2010-12-12
*/
public class OneLinerDb {
private static final Log logger = LogFactory.getLog(OneLinerDb.class);
private List<OneLiner> initialList;
private List<OneLiner> oneLiners;
public List<OneLiner> getLatestOneLiners(int maxNumber) {
if (logger.isDebugEnabled()) { logger.debug("Getting latest one liners. DB size = " + oneLiners.size()); }
if (maxNumber >= oneLiners.size()) {
return oneLiners;
} else {
int endIndex = oneLiners.size() - 1;
return oneLiners.subList(endIndex - maxNumber, endIndex);
}
}
| // Path: src/main/java/org/owasp/oneliner/oneLiner/DbSize.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlRootElement
// public class DbSize {
// private int size;
// private Date timeStamp;
//
// public int getSize() {
// return size;
// }
//
// public void setSize(int size) {
// this.size = size;
// }
//
// public Date getTimeStamp() {
// return timeStamp;
// }
//
// public void setTimeStamp(Date timeStamp) {
// this.timeStamp = timeStamp;
// }
//
// @Override
// public String toString() {
// return "DbSize{" +
// "size=" + size +
// ", timeStamp=" + timeStamp +
// '}';
// }
//
// public DbSize(int size) {
// this.size = size;
// this.timeStamp = new Date();
// }
//
// public DbSize() {}; // Here for JAXB
// }
//
// Path: src/main/java/org/owasp/oneliner/oneLiner/OneLiner.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlRootElement
// public class OneLiner {
// protected int id;
// protected String nickName;
// protected String oneLiner;
// protected Date timestamp;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public void setNickName(String nickName) {
// this.nickName = nickName;
// }
//
// public String getOneLiner() {
// return oneLiner;
// }
//
// public void setOneLiner(String oneLiner) {
// this.oneLiner = oneLiner;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// OneLiner(int id, String nickName, String oneLiner, Date timestamp) throws IllegalArgumentException {
// if (nickOK(nickName) && oneLinerOK(oneLiner)) {
// this.id = id;
// this.nickName = nickName;
// this.oneLiner = oneLiner;
// this.timestamp = timestamp;
// } else {
// throw new IllegalArgumentException();
// }
// }
//
// public OneLiner() { } // Here for JAX-B
//
// private boolean nickOK(String nickName) {
// final int MAX_NICK_NAME_SIZE = 32;
// return (nickName != null && !"".equals(nickName) && nickName.length() <= MAX_NICK_NAME_SIZE);
// }
//
// private boolean oneLinerOK(String oneLiner) {
// final int MAX_ONE_LINER_SIZE = 160;
// return (oneLiner != null && !"".equals(oneLiner) && oneLiner.length() <= MAX_ONE_LINER_SIZE);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other instanceof OneLiner) {
// OneLiner otherOneLiner = (OneLiner)other;
// return id == otherOneLiner.id &&
// nickName != null && nickName.equals(otherOneLiner.nickName) &&
// oneLiner != null && oneLiner.equals(otherOneLiner.oneLiner);
// } else {
// return false;
// }
// }
//
// @Override
// public String toString() {
// return "{" + id + " " + nickName + ":" + oneLiner + ":" + timestamp + "}";
// }
// }
// Path: src/main/java/org/owasp/oneliner/persistence/OneLinerDb.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.oneLiner.DbSize;
import org.owasp.oneliner.oneLiner.OneLiner;
import java.util.ArrayList;
import java.util.List;
package org.owasp.oneliner.persistence;
/**
* Author: @johnwilander
* Date: 2010-12-12
*/
public class OneLinerDb {
private static final Log logger = LogFactory.getLog(OneLinerDb.class);
private List<OneLiner> initialList;
private List<OneLiner> oneLiners;
public List<OneLiner> getLatestOneLiners(int maxNumber) {
if (logger.isDebugEnabled()) { logger.debug("Getting latest one liners. DB size = " + oneLiners.size()); }
if (maxNumber >= oneLiners.size()) {
return oneLiners;
} else {
int endIndex = oneLiners.size() - 1;
return oneLiners.subList(endIndex - maxNumber, endIndex);
}
}
| public DbSize getNumberOfOneliners() { |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/authentication/Authenticator.java | // Path: src/main/java/org/owasp/oneliner/exceptions/AuthenticationException.java
// public class AuthenticationException extends Exception {
// public static final AuthenticationException INTERNAL_ERROR =
// new AuthenticationException("Could not authenticate due to an internal error");
// public static final AuthenticationException UNKNOWN_USER_NAME_OR_PASSWORD =
// new AuthenticationException("Wrong user name or password");
//
// // SecBug: Information leakage
// public static final AuthenticationException UNKNOWN_USER_NAME =
// new AuthenticationException("Wrong user name");
// public static final AuthenticationException NOT_AUTHENTICATED =
// new AuthenticationException("Authentication failed");
//
// private AuthenticationException (String message) {
// super(message);
// this.setStackTrace(new StackTraceElement[0]); // No stack trace needed
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.AuthenticationException;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import org.owasp.oneliner.user.User;
import javax.annotation.Resource; | package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-dec-05
*/
public class Authenticator {
private static final Log logger = LogFactory.getLog(Authenticator.class);
@Resource
private UserDataBase userDataBase;
@Resource | // Path: src/main/java/org/owasp/oneliner/exceptions/AuthenticationException.java
// public class AuthenticationException extends Exception {
// public static final AuthenticationException INTERNAL_ERROR =
// new AuthenticationException("Could not authenticate due to an internal error");
// public static final AuthenticationException UNKNOWN_USER_NAME_OR_PASSWORD =
// new AuthenticationException("Wrong user name or password");
//
// // SecBug: Information leakage
// public static final AuthenticationException UNKNOWN_USER_NAME =
// new AuthenticationException("Wrong user name");
// public static final AuthenticationException NOT_AUTHENTICATED =
// new AuthenticationException("Authentication failed");
//
// private AuthenticationException (String message) {
// super(message);
// this.setStackTrace(new StackTraceElement[0]); // No stack trace needed
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
// Path: src/main/java/org/owasp/oneliner/authentication/Authenticator.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.AuthenticationException;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import org.owasp.oneliner.user.User;
import javax.annotation.Resource;
package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-dec-05
*/
public class Authenticator {
private static final Log logger = LogFactory.getLog(Authenticator.class);
@Resource
private UserDataBase userDataBase;
@Resource | private HashedPasswordFactory hashedPasswordFactory; |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/authentication/Authenticator.java | // Path: src/main/java/org/owasp/oneliner/exceptions/AuthenticationException.java
// public class AuthenticationException extends Exception {
// public static final AuthenticationException INTERNAL_ERROR =
// new AuthenticationException("Could not authenticate due to an internal error");
// public static final AuthenticationException UNKNOWN_USER_NAME_OR_PASSWORD =
// new AuthenticationException("Wrong user name or password");
//
// // SecBug: Information leakage
// public static final AuthenticationException UNKNOWN_USER_NAME =
// new AuthenticationException("Wrong user name");
// public static final AuthenticationException NOT_AUTHENTICATED =
// new AuthenticationException("Authentication failed");
//
// private AuthenticationException (String message) {
// super(message);
// this.setStackTrace(new StackTraceElement[0]); // No stack trace needed
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.AuthenticationException;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import org.owasp.oneliner.user.User;
import javax.annotation.Resource; | package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-dec-05
*/
public class Authenticator {
private static final Log logger = LogFactory.getLog(Authenticator.class);
@Resource
private UserDataBase userDataBase;
@Resource
private HashedPasswordFactory hashedPasswordFactory;
| // Path: src/main/java/org/owasp/oneliner/exceptions/AuthenticationException.java
// public class AuthenticationException extends Exception {
// public static final AuthenticationException INTERNAL_ERROR =
// new AuthenticationException("Could not authenticate due to an internal error");
// public static final AuthenticationException UNKNOWN_USER_NAME_OR_PASSWORD =
// new AuthenticationException("Wrong user name or password");
//
// // SecBug: Information leakage
// public static final AuthenticationException UNKNOWN_USER_NAME =
// new AuthenticationException("Wrong user name");
// public static final AuthenticationException NOT_AUTHENTICATED =
// new AuthenticationException("Authentication failed");
//
// private AuthenticationException (String message) {
// super(message);
// this.setStackTrace(new StackTraceElement[0]); // No stack trace needed
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
// Path: src/main/java/org/owasp/oneliner/authentication/Authenticator.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.AuthenticationException;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import org.owasp.oneliner.user.User;
import javax.annotation.Resource;
package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-dec-05
*/
public class Authenticator {
private static final Log logger = LogFactory.getLog(Authenticator.class);
@Resource
private UserDataBase userDataBase;
@Resource
private HashedPasswordFactory hashedPasswordFactory;
| public User authenticate(String userName, String suppliedPassword) throws AuthenticationException { |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/authentication/Authenticator.java | // Path: src/main/java/org/owasp/oneliner/exceptions/AuthenticationException.java
// public class AuthenticationException extends Exception {
// public static final AuthenticationException INTERNAL_ERROR =
// new AuthenticationException("Could not authenticate due to an internal error");
// public static final AuthenticationException UNKNOWN_USER_NAME_OR_PASSWORD =
// new AuthenticationException("Wrong user name or password");
//
// // SecBug: Information leakage
// public static final AuthenticationException UNKNOWN_USER_NAME =
// new AuthenticationException("Wrong user name");
// public static final AuthenticationException NOT_AUTHENTICATED =
// new AuthenticationException("Authentication failed");
//
// private AuthenticationException (String message) {
// super(message);
// this.setStackTrace(new StackTraceElement[0]); // No stack trace needed
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.AuthenticationException;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import org.owasp.oneliner.user.User;
import javax.annotation.Resource; | package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-dec-05
*/
public class Authenticator {
private static final Log logger = LogFactory.getLog(Authenticator.class);
@Resource
private UserDataBase userDataBase;
@Resource
private HashedPasswordFactory hashedPasswordFactory;
| // Path: src/main/java/org/owasp/oneliner/exceptions/AuthenticationException.java
// public class AuthenticationException extends Exception {
// public static final AuthenticationException INTERNAL_ERROR =
// new AuthenticationException("Could not authenticate due to an internal error");
// public static final AuthenticationException UNKNOWN_USER_NAME_OR_PASSWORD =
// new AuthenticationException("Wrong user name or password");
//
// // SecBug: Information leakage
// public static final AuthenticationException UNKNOWN_USER_NAME =
// new AuthenticationException("Wrong user name");
// public static final AuthenticationException NOT_AUTHENTICATED =
// new AuthenticationException("Authentication failed");
//
// private AuthenticationException (String message) {
// super(message);
// this.setStackTrace(new StackTraceElement[0]); // No stack trace needed
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
// Path: src/main/java/org/owasp/oneliner/authentication/Authenticator.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.AuthenticationException;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import org.owasp.oneliner.user.User;
import javax.annotation.Resource;
package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-dec-05
*/
public class Authenticator {
private static final Log logger = LogFactory.getLog(Authenticator.class);
@Resource
private UserDataBase userDataBase;
@Resource
private HashedPasswordFactory hashedPasswordFactory;
| public User authenticate(String userName, String suppliedPassword) throws AuthenticationException { |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/authentication/Authenticator.java | // Path: src/main/java/org/owasp/oneliner/exceptions/AuthenticationException.java
// public class AuthenticationException extends Exception {
// public static final AuthenticationException INTERNAL_ERROR =
// new AuthenticationException("Could not authenticate due to an internal error");
// public static final AuthenticationException UNKNOWN_USER_NAME_OR_PASSWORD =
// new AuthenticationException("Wrong user name or password");
//
// // SecBug: Information leakage
// public static final AuthenticationException UNKNOWN_USER_NAME =
// new AuthenticationException("Wrong user name");
// public static final AuthenticationException NOT_AUTHENTICATED =
// new AuthenticationException("Authentication failed");
//
// private AuthenticationException (String message) {
// super(message);
// this.setStackTrace(new StackTraceElement[0]); // No stack trace needed
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.AuthenticationException;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import org.owasp.oneliner.user.User;
import javax.annotation.Resource; | package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-dec-05
*/
public class Authenticator {
private static final Log logger = LogFactory.getLog(Authenticator.class);
@Resource
private UserDataBase userDataBase;
@Resource
private HashedPasswordFactory hashedPasswordFactory;
public User authenticate(String userName, String suppliedPassword) throws AuthenticationException {
User user;
try {
user = userDataBase.getUserByUserName(userName); | // Path: src/main/java/org/owasp/oneliner/exceptions/AuthenticationException.java
// public class AuthenticationException extends Exception {
// public static final AuthenticationException INTERNAL_ERROR =
// new AuthenticationException("Could not authenticate due to an internal error");
// public static final AuthenticationException UNKNOWN_USER_NAME_OR_PASSWORD =
// new AuthenticationException("Wrong user name or password");
//
// // SecBug: Information leakage
// public static final AuthenticationException UNKNOWN_USER_NAME =
// new AuthenticationException("Wrong user name");
// public static final AuthenticationException NOT_AUTHENTICATED =
// new AuthenticationException("Authentication failed");
//
// private AuthenticationException (String message) {
// super(message);
// this.setStackTrace(new StackTraceElement[0]); // No stack trace needed
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
// Path: src/main/java/org/owasp/oneliner/authentication/Authenticator.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.AuthenticationException;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import org.owasp.oneliner.user.User;
import javax.annotation.Resource;
package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-dec-05
*/
public class Authenticator {
private static final Log logger = LogFactory.getLog(Authenticator.class);
@Resource
private UserDataBase userDataBase;
@Resource
private HashedPasswordFactory hashedPasswordFactory;
public User authenticate(String userName, String suppliedPassword) throws AuthenticationException {
User user;
try {
user = userDataBase.getUserByUserName(userName); | } catch (NoSuchUserException e) { |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/authentication/Authenticator.java | // Path: src/main/java/org/owasp/oneliner/exceptions/AuthenticationException.java
// public class AuthenticationException extends Exception {
// public static final AuthenticationException INTERNAL_ERROR =
// new AuthenticationException("Could not authenticate due to an internal error");
// public static final AuthenticationException UNKNOWN_USER_NAME_OR_PASSWORD =
// new AuthenticationException("Wrong user name or password");
//
// // SecBug: Information leakage
// public static final AuthenticationException UNKNOWN_USER_NAME =
// new AuthenticationException("Wrong user name");
// public static final AuthenticationException NOT_AUTHENTICATED =
// new AuthenticationException("Authentication failed");
//
// private AuthenticationException (String message) {
// super(message);
// this.setStackTrace(new StackTraceElement[0]); // No stack trace needed
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.AuthenticationException;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import org.owasp.oneliner.user.User;
import javax.annotation.Resource; | package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-dec-05
*/
public class Authenticator {
private static final Log logger = LogFactory.getLog(Authenticator.class);
@Resource
private UserDataBase userDataBase;
@Resource
private HashedPasswordFactory hashedPasswordFactory;
public User authenticate(String userName, String suppliedPassword) throws AuthenticationException {
User user;
try {
user = userDataBase.getUserByUserName(userName);
} catch (NoSuchUserException e) {
logger.info("No such user: " + userName);
// SecBug: Information leakage
// throw AuthenticationException.UNKNOWN_USER_NAME;
throw AuthenticationException.UNKNOWN_USER_NAME_OR_PASSWORD;
} | // Path: src/main/java/org/owasp/oneliner/exceptions/AuthenticationException.java
// public class AuthenticationException extends Exception {
// public static final AuthenticationException INTERNAL_ERROR =
// new AuthenticationException("Could not authenticate due to an internal error");
// public static final AuthenticationException UNKNOWN_USER_NAME_OR_PASSWORD =
// new AuthenticationException("Wrong user name or password");
//
// // SecBug: Information leakage
// public static final AuthenticationException UNKNOWN_USER_NAME =
// new AuthenticationException("Wrong user name");
// public static final AuthenticationException NOT_AUTHENTICATED =
// new AuthenticationException("Authentication failed");
//
// private AuthenticationException (String message) {
// super(message);
// this.setStackTrace(new StackTraceElement[0]); // No stack trace needed
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPassword.java
// public class HashedPassword {
// private final String hashedPassword;
// private final long salt;
//
// // Package default to give access to factory class only
// HashedPassword(String hashedPassword, long salt) {
// this.salt = salt;
// this.hashedPassword = hashedPassword;
// }
//
// public long getSalt() {
// return salt;
// }
//
// public boolean equals(Object other) {
// if (!(other instanceof HashedPassword)) {
// return false;
// } else {
// HashedPassword otherHashedPassword = (HashedPassword)other;
// return hashedPassword.equals(otherHashedPassword.hashedPassword) &&
// salt == otherHashedPassword.salt;
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/password/HashedPasswordFactory.java
// public class HashedPasswordFactory {
// @Resource
// private SecureRandom secureRandom;
//
// public HashedPassword createHashedPassword(String plainTextPassword) {
// long salt = secureRandom.nextLong();
// return createHashedPassword(plainTextPassword, salt);
// }
//
// public HashedPassword createHashedPassword(String plainTextPassword, long salt) {
// String hashedPasswordStr = null;
// try {
// hashedPasswordStr = new String(sha256.digest((plainTextPassword + salt).getBytes("UTF8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new HashedPassword(hashedPasswordStr, salt);
// }
//
// private static MessageDigest sha256;
// static {
// try {
// sha256 = MessageDigest.getInstance("SHA-256");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
// Path: src/main/java/org/owasp/oneliner/authentication/Authenticator.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.AuthenticationException;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.password.HashedPassword;
import org.owasp.oneliner.password.HashedPasswordFactory;
import org.owasp.oneliner.user.User;
import javax.annotation.Resource;
package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-dec-05
*/
public class Authenticator {
private static final Log logger = LogFactory.getLog(Authenticator.class);
@Resource
private UserDataBase userDataBase;
@Resource
private HashedPasswordFactory hashedPasswordFactory;
public User authenticate(String userName, String suppliedPassword) throws AuthenticationException {
User user;
try {
user = userDataBase.getUserByUserName(userName);
} catch (NoSuchUserException e) {
logger.info("No such user: " + userName);
// SecBug: Information leakage
// throw AuthenticationException.UNKNOWN_USER_NAME;
throw AuthenticationException.UNKNOWN_USER_NAME_OR_PASSWORD;
} | HashedPassword realHashedPassword = user.getHashedPassword(); |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/authentication/UserDataBase.java | // Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.user.User;
import java.util.HashSet;
import java.util.Set; | package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
public class UserDataBase {
private static final Log logger = LogFactory.getLog(UserDataBase.class); | // Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
// Path: src/main/java/org/owasp/oneliner/authentication/UserDataBase.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.user.User;
import java.util.HashSet;
import java.util.Set;
package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
public class UserDataBase {
private static final Log logger = LogFactory.getLog(UserDataBase.class); | private final Set<User> userSet = new HashSet<User>(); |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/authentication/UserDataBase.java | // Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.user.User;
import java.util.HashSet;
import java.util.Set; | package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
public class UserDataBase {
private static final Log logger = LogFactory.getLog(UserDataBase.class);
private final Set<User> userSet = new HashSet<User>();
public UserDataBase() {}
public UserDataBase(Set<User> initialUsers) {
userSet.addAll(initialUsers);
}
public boolean addUser(User user) {
boolean wasAdded;
synchronized (userSet) {
wasAdded = userSet.add(user);
}
if (!wasAdded) {
logger.info("User " + user + " was already present in the database.");
}
return wasAdded;
}
| // Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
// Path: src/main/java/org/owasp/oneliner/authentication/UserDataBase.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.user.User;
import java.util.HashSet;
import java.util.Set;
package org.owasp.oneliner.authentication;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
public class UserDataBase {
private static final Log logger = LogFactory.getLog(UserDataBase.class);
private final Set<User> userSet = new HashSet<User>();
public UserDataBase() {}
public UserDataBase(Set<User> initialUsers) {
userSet.addAll(initialUsers);
}
public boolean addUser(User user) {
boolean wasAdded;
synchronized (userSet) {
wasAdded = userSet.add(user);
}
if (!wasAdded) {
logger.info("User " + user + " was already present in the database.");
}
return wasAdded;
}
| public User getUserByUserName(String userName) throws NoSuchUserException { |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/session/SessionManager.java | // Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
| import org.owasp.oneliner.user.User;
import javax.annotation.Resource; | package org.owasp.oneliner.session;
/**
* Author: @johnwilander
* Date: 2010-12-18
*/
public class SessionManager {
@Resource
SessionIdFactory sessionIdFactory;
| // Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
// Path: src/main/java/org/owasp/oneliner/session/SessionManager.java
import org.owasp.oneliner.user.User;
import javax.annotation.Resource;
package org.owasp.oneliner.session;
/**
* Author: @johnwilander
* Date: 2010-12-18
*/
public class SessionManager {
@Resource
SessionIdFactory sessionIdFactory;
| public SessionId createAuthenticatedSession(User user) { |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/rest/UserResource.java | // Path: src/main/java/org/owasp/oneliner/authentication/UserDataBase.java
// public class UserDataBase {
// private static final Log logger = LogFactory.getLog(UserDataBase.class);
// private final Set<User> userSet = new HashSet<User>();
//
// public UserDataBase() {}
//
// public UserDataBase(Set<User> initialUsers) {
// userSet.addAll(initialUsers);
// }
//
// public boolean addUser(User user) {
// boolean wasAdded;
// synchronized (userSet) {
// wasAdded = userSet.add(user);
// }
// if (!wasAdded) {
// logger.info("User " + user + " was already present in the database.");
// }
// return wasAdded;
// }
//
// public User getUserByUserName(String userName) throws NoSuchUserException {
// for (User user : userSet) {
// if (user.getUserName().equals(userName)) {
// return user;
// }
// }
// throw NoSuchUserException.NO_SUCH_USER;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/UserFactory.java
// public class UserFactory {
// @Resource
// HashedPasswordFactory hashedPasswordFactory;
//
// public User createUser(String userName, String nickName, String password) {
// return createUser(userName, nickName, hashedPasswordFactory.createHashedPassword(password));
// }
//
// public User createUser(String userName, String nickName, HashedPassword hashedPassword) {
// return new User(userName, nickName, hashedPassword);
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.authentication.UserDataBase;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.user.User;
import org.owasp.oneliner.user.UserFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; | package org.owasp.oneliner.rest;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
@Path("/user")
@Component
public class UserResource {
private static final Log logger = LogFactory.getLog(UserResource.class);
@Resource | // Path: src/main/java/org/owasp/oneliner/authentication/UserDataBase.java
// public class UserDataBase {
// private static final Log logger = LogFactory.getLog(UserDataBase.class);
// private final Set<User> userSet = new HashSet<User>();
//
// public UserDataBase() {}
//
// public UserDataBase(Set<User> initialUsers) {
// userSet.addAll(initialUsers);
// }
//
// public boolean addUser(User user) {
// boolean wasAdded;
// synchronized (userSet) {
// wasAdded = userSet.add(user);
// }
// if (!wasAdded) {
// logger.info("User " + user + " was already present in the database.");
// }
// return wasAdded;
// }
//
// public User getUserByUserName(String userName) throws NoSuchUserException {
// for (User user : userSet) {
// if (user.getUserName().equals(userName)) {
// return user;
// }
// }
// throw NoSuchUserException.NO_SUCH_USER;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/UserFactory.java
// public class UserFactory {
// @Resource
// HashedPasswordFactory hashedPasswordFactory;
//
// public User createUser(String userName, String nickName, String password) {
// return createUser(userName, nickName, hashedPasswordFactory.createHashedPassword(password));
// }
//
// public User createUser(String userName, String nickName, HashedPassword hashedPassword) {
// return new User(userName, nickName, hashedPassword);
// }
// }
// Path: src/main/java/org/owasp/oneliner/rest/UserResource.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.authentication.UserDataBase;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.user.User;
import org.owasp.oneliner.user.UserFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
package org.owasp.oneliner.rest;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
@Path("/user")
@Component
public class UserResource {
private static final Log logger = LogFactory.getLog(UserResource.class);
@Resource | private UserDataBase userDataBase; |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/rest/UserResource.java | // Path: src/main/java/org/owasp/oneliner/authentication/UserDataBase.java
// public class UserDataBase {
// private static final Log logger = LogFactory.getLog(UserDataBase.class);
// private final Set<User> userSet = new HashSet<User>();
//
// public UserDataBase() {}
//
// public UserDataBase(Set<User> initialUsers) {
// userSet.addAll(initialUsers);
// }
//
// public boolean addUser(User user) {
// boolean wasAdded;
// synchronized (userSet) {
// wasAdded = userSet.add(user);
// }
// if (!wasAdded) {
// logger.info("User " + user + " was already present in the database.");
// }
// return wasAdded;
// }
//
// public User getUserByUserName(String userName) throws NoSuchUserException {
// for (User user : userSet) {
// if (user.getUserName().equals(userName)) {
// return user;
// }
// }
// throw NoSuchUserException.NO_SUCH_USER;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/UserFactory.java
// public class UserFactory {
// @Resource
// HashedPasswordFactory hashedPasswordFactory;
//
// public User createUser(String userName, String nickName, String password) {
// return createUser(userName, nickName, hashedPasswordFactory.createHashedPassword(password));
// }
//
// public User createUser(String userName, String nickName, HashedPassword hashedPassword) {
// return new User(userName, nickName, hashedPassword);
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.authentication.UserDataBase;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.user.User;
import org.owasp.oneliner.user.UserFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; | package org.owasp.oneliner.rest;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
@Path("/user")
@Component
public class UserResource {
private static final Log logger = LogFactory.getLog(UserResource.class);
@Resource
private UserDataBase userDataBase;
@Resource | // Path: src/main/java/org/owasp/oneliner/authentication/UserDataBase.java
// public class UserDataBase {
// private static final Log logger = LogFactory.getLog(UserDataBase.class);
// private final Set<User> userSet = new HashSet<User>();
//
// public UserDataBase() {}
//
// public UserDataBase(Set<User> initialUsers) {
// userSet.addAll(initialUsers);
// }
//
// public boolean addUser(User user) {
// boolean wasAdded;
// synchronized (userSet) {
// wasAdded = userSet.add(user);
// }
// if (!wasAdded) {
// logger.info("User " + user + " was already present in the database.");
// }
// return wasAdded;
// }
//
// public User getUserByUserName(String userName) throws NoSuchUserException {
// for (User user : userSet) {
// if (user.getUserName().equals(userName)) {
// return user;
// }
// }
// throw NoSuchUserException.NO_SUCH_USER;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/UserFactory.java
// public class UserFactory {
// @Resource
// HashedPasswordFactory hashedPasswordFactory;
//
// public User createUser(String userName, String nickName, String password) {
// return createUser(userName, nickName, hashedPasswordFactory.createHashedPassword(password));
// }
//
// public User createUser(String userName, String nickName, HashedPassword hashedPassword) {
// return new User(userName, nickName, hashedPassword);
// }
// }
// Path: src/main/java/org/owasp/oneliner/rest/UserResource.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.authentication.UserDataBase;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.user.User;
import org.owasp.oneliner.user.UserFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
package org.owasp.oneliner.rest;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
@Path("/user")
@Component
public class UserResource {
private static final Log logger = LogFactory.getLog(UserResource.class);
@Resource
private UserDataBase userDataBase;
@Resource | private UserFactory userFactory; |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/rest/UserResource.java | // Path: src/main/java/org/owasp/oneliner/authentication/UserDataBase.java
// public class UserDataBase {
// private static final Log logger = LogFactory.getLog(UserDataBase.class);
// private final Set<User> userSet = new HashSet<User>();
//
// public UserDataBase() {}
//
// public UserDataBase(Set<User> initialUsers) {
// userSet.addAll(initialUsers);
// }
//
// public boolean addUser(User user) {
// boolean wasAdded;
// synchronized (userSet) {
// wasAdded = userSet.add(user);
// }
// if (!wasAdded) {
// logger.info("User " + user + " was already present in the database.");
// }
// return wasAdded;
// }
//
// public User getUserByUserName(String userName) throws NoSuchUserException {
// for (User user : userSet) {
// if (user.getUserName().equals(userName)) {
// return user;
// }
// }
// throw NoSuchUserException.NO_SUCH_USER;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/UserFactory.java
// public class UserFactory {
// @Resource
// HashedPasswordFactory hashedPasswordFactory;
//
// public User createUser(String userName, String nickName, String password) {
// return createUser(userName, nickName, hashedPasswordFactory.createHashedPassword(password));
// }
//
// public User createUser(String userName, String nickName, HashedPassword hashedPassword) {
// return new User(userName, nickName, hashedPassword);
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.authentication.UserDataBase;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.user.User;
import org.owasp.oneliner.user.UserFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; | package org.owasp.oneliner.rest;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
@Path("/user")
@Component
public class UserResource {
private static final Log logger = LogFactory.getLog(UserResource.class);
@Resource
private UserDataBase userDataBase;
@Resource
private UserFactory userFactory;
@GET
@Path("/{userName}")
@Produces({MediaType.APPLICATION_JSON}) | // Path: src/main/java/org/owasp/oneliner/authentication/UserDataBase.java
// public class UserDataBase {
// private static final Log logger = LogFactory.getLog(UserDataBase.class);
// private final Set<User> userSet = new HashSet<User>();
//
// public UserDataBase() {}
//
// public UserDataBase(Set<User> initialUsers) {
// userSet.addAll(initialUsers);
// }
//
// public boolean addUser(User user) {
// boolean wasAdded;
// synchronized (userSet) {
// wasAdded = userSet.add(user);
// }
// if (!wasAdded) {
// logger.info("User " + user + " was already present in the database.");
// }
// return wasAdded;
// }
//
// public User getUserByUserName(String userName) throws NoSuchUserException {
// for (User user : userSet) {
// if (user.getUserName().equals(userName)) {
// return user;
// }
// }
// throw NoSuchUserException.NO_SUCH_USER;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/UserFactory.java
// public class UserFactory {
// @Resource
// HashedPasswordFactory hashedPasswordFactory;
//
// public User createUser(String userName, String nickName, String password) {
// return createUser(userName, nickName, hashedPasswordFactory.createHashedPassword(password));
// }
//
// public User createUser(String userName, String nickName, HashedPassword hashedPassword) {
// return new User(userName, nickName, hashedPassword);
// }
// }
// Path: src/main/java/org/owasp/oneliner/rest/UserResource.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.authentication.UserDataBase;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.user.User;
import org.owasp.oneliner.user.UserFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
package org.owasp.oneliner.rest;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
@Path("/user")
@Component
public class UserResource {
private static final Log logger = LogFactory.getLog(UserResource.class);
@Resource
private UserDataBase userDataBase;
@Resource
private UserFactory userFactory;
@GET
@Path("/{userName}")
@Produces({MediaType.APPLICATION_JSON}) | public Response getUser(@PathParam("userName") String userName) throws NoSuchUserException { |
johnwilander/owasp-1-liner | src/main/java/org/owasp/oneliner/rest/UserResource.java | // Path: src/main/java/org/owasp/oneliner/authentication/UserDataBase.java
// public class UserDataBase {
// private static final Log logger = LogFactory.getLog(UserDataBase.class);
// private final Set<User> userSet = new HashSet<User>();
//
// public UserDataBase() {}
//
// public UserDataBase(Set<User> initialUsers) {
// userSet.addAll(initialUsers);
// }
//
// public boolean addUser(User user) {
// boolean wasAdded;
// synchronized (userSet) {
// wasAdded = userSet.add(user);
// }
// if (!wasAdded) {
// logger.info("User " + user + " was already present in the database.");
// }
// return wasAdded;
// }
//
// public User getUserByUserName(String userName) throws NoSuchUserException {
// for (User user : userSet) {
// if (user.getUserName().equals(userName)) {
// return user;
// }
// }
// throw NoSuchUserException.NO_SUCH_USER;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/UserFactory.java
// public class UserFactory {
// @Resource
// HashedPasswordFactory hashedPasswordFactory;
//
// public User createUser(String userName, String nickName, String password) {
// return createUser(userName, nickName, hashedPasswordFactory.createHashedPassword(password));
// }
//
// public User createUser(String userName, String nickName, HashedPassword hashedPassword) {
// return new User(userName, nickName, hashedPassword);
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.authentication.UserDataBase;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.user.User;
import org.owasp.oneliner.user.UserFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; | package org.owasp.oneliner.rest;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
@Path("/user")
@Component
public class UserResource {
private static final Log logger = LogFactory.getLog(UserResource.class);
@Resource
private UserDataBase userDataBase;
@Resource
private UserFactory userFactory;
@GET
@Path("/{userName}")
@Produces({MediaType.APPLICATION_JSON})
public Response getUser(@PathParam("userName") String userName) throws NoSuchUserException { | // Path: src/main/java/org/owasp/oneliner/authentication/UserDataBase.java
// public class UserDataBase {
// private static final Log logger = LogFactory.getLog(UserDataBase.class);
// private final Set<User> userSet = new HashSet<User>();
//
// public UserDataBase() {}
//
// public UserDataBase(Set<User> initialUsers) {
// userSet.addAll(initialUsers);
// }
//
// public boolean addUser(User user) {
// boolean wasAdded;
// synchronized (userSet) {
// wasAdded = userSet.add(user);
// }
// if (!wasAdded) {
// logger.info("User " + user + " was already present in the database.");
// }
// return wasAdded;
// }
//
// public User getUserByUserName(String userName) throws NoSuchUserException {
// for (User user : userSet) {
// if (user.getUserName().equals(userName)) {
// return user;
// }
// }
// throw NoSuchUserException.NO_SUCH_USER;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/exceptions/NoSuchUserException.java
// public class NoSuchUserException extends Exception {
// public static final NoSuchUserException NO_SUCH_USER = new NoSuchUserException("No such user");
//
// public NoSuchUserException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/User.java
// @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
// @XmlRootElement
// public class User {
// public final String userName;
// public final String nickName;
// private HashedPassword hashedPassword;
// private SessionId sessionId;
//
// // Package default to give access to factory class only
// User(String userName, String nickName, HashedPassword hashedPassword) {
// this.userName = userName;
// this.nickName = nickName;
// this.hashedPassword = hashedPassword;
// }
//
// @Override
// public String toString() {
// return userName + ":" + nickName;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public HashedPassword getHashedPassword() {
// return hashedPassword;
// }
//
// public SessionId getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(SessionId sessionId) {
// this.sessionId = sessionId;
// }
//
// public boolean hasActiveSession() {
// Date now = new Date();
// return now.before(sessionId.expires()) && now.after(sessionId.starts());
// }
//
// // Here for JAXB
// public User() {
// this.userName = null;
// this.nickName = null;
// }
// }
//
// Path: src/main/java/org/owasp/oneliner/user/UserFactory.java
// public class UserFactory {
// @Resource
// HashedPasswordFactory hashedPasswordFactory;
//
// public User createUser(String userName, String nickName, String password) {
// return createUser(userName, nickName, hashedPasswordFactory.createHashedPassword(password));
// }
//
// public User createUser(String userName, String nickName, HashedPassword hashedPassword) {
// return new User(userName, nickName, hashedPassword);
// }
// }
// Path: src/main/java/org/owasp/oneliner/rest/UserResource.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.oneliner.authentication.UserDataBase;
import org.owasp.oneliner.exceptions.NoSuchUserException;
import org.owasp.oneliner.user.User;
import org.owasp.oneliner.user.UserFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
package org.owasp.oneliner.rest;
/**
* Author: @johnwilander
* Date: 2010-nov-06
*/
@Path("/user")
@Component
public class UserResource {
private static final Log logger = LogFactory.getLog(UserResource.class);
@Resource
private UserDataBase userDataBase;
@Resource
private UserFactory userFactory;
@GET
@Path("/{userName}")
@Produces({MediaType.APPLICATION_JSON})
public Response getUser(@PathParam("userName") String userName) throws NoSuchUserException { | User user = userDataBase.getUserByUserName(userName); |
bmbouter/Opus | gwt/src/opus/gwt/management/console/client/dashboard/ProjectManagerController.java | // Path: gwt/src/opus/gwt/management/console/client/event/BreadCrumbEvent.java
// public class BreadCrumbEvent extends GwtEvent<BreadCrumbEventHandler> {
//
// public static Type<BreadCrumbEventHandler> TYPE = new Type<BreadCrumbEventHandler>();
// public enum Action{SET_CRUMBS, SET_ACTIVE, ADD_CRUMB, REMOVE_CRUMB};
// private Action actionType;
// private String[] names;
// private String crumb;
//
// public BreadCrumbEvent(Action actionType, String[] names){
// this.actionType = actionType;
// this.names = names;
// }
//
// public BreadCrumbEvent(Action actionType, String crumb){
// this.actionType = actionType;
// this.crumb = crumb;
// }
//
// public Action getAction(){
// return actionType;
// }
//
// public String getCrumb(){
// return crumb;
// }
//
// public String[] getCrumbNames(){
// return names;
// }
//
// @Override
// public Type<BreadCrumbEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(BreadCrumbEventHandler handler) {
// handler.onBreadCrumb(this);
// }
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
| import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.event.BreadCrumbEvent;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import opus.gwt.management.console.client.event.PanelTransitionEventHandler;
import opus.gwt.management.console.client.resources.ProjectManagerCss.ProjectManagerStyle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.Widget; | /*############################################################################
# Copyright 2010 North Carolina State University #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
############################################################################*/
package opus.gwt.management.console.client.dashboard;
public class ProjectManagerController extends Composite {
private static ProjectDashboardUiBinder uiBinder = GWT.create(ProjectDashboardUiBinder.class);
interface ProjectDashboardUiBinder extends UiBinder<Widget, ProjectManagerController> {}
private DashboardPanel dashboardPanel;
// private DeleteProjectPanel deleteProjectPanel;
private AppSettingsPanel appSettingsPanel;
private EventBus eventBus;
private String projectName;
private ClientFactory clientFactory;
@UiField ProjectManagerStyle style;
@UiField DeckPanel managerDeckPanel;
public ProjectManagerController(ClientFactory clientFactory){
initWidget(uiBinder.createAndBindUi(this));
this.clientFactory = clientFactory;
this.eventBus = clientFactory.getEventBus();
this.dashboardPanel = new DashboardPanel(clientFactory);
this.appSettingsPanel = new AppSettingsPanel(clientFactory);
setupBreadCrumbs();
setupmanagerDeckPanel();
registerHandlers();
}
private void setupBreadCrumbs(){
String[] crumbs = {"Projects", projectName, dashboardPanel.getTitle()}; | // Path: gwt/src/opus/gwt/management/console/client/event/BreadCrumbEvent.java
// public class BreadCrumbEvent extends GwtEvent<BreadCrumbEventHandler> {
//
// public static Type<BreadCrumbEventHandler> TYPE = new Type<BreadCrumbEventHandler>();
// public enum Action{SET_CRUMBS, SET_ACTIVE, ADD_CRUMB, REMOVE_CRUMB};
// private Action actionType;
// private String[] names;
// private String crumb;
//
// public BreadCrumbEvent(Action actionType, String[] names){
// this.actionType = actionType;
// this.names = names;
// }
//
// public BreadCrumbEvent(Action actionType, String crumb){
// this.actionType = actionType;
// this.crumb = crumb;
// }
//
// public Action getAction(){
// return actionType;
// }
//
// public String getCrumb(){
// return crumb;
// }
//
// public String[] getCrumbNames(){
// return names;
// }
//
// @Override
// public Type<BreadCrumbEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(BreadCrumbEventHandler handler) {
// handler.onBreadCrumb(this);
// }
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
// Path: gwt/src/opus/gwt/management/console/client/dashboard/ProjectManagerController.java
import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.event.BreadCrumbEvent;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import opus.gwt.management.console.client.event.PanelTransitionEventHandler;
import opus.gwt.management.console.client.resources.ProjectManagerCss.ProjectManagerStyle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.Widget;
/*############################################################################
# Copyright 2010 North Carolina State University #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
############################################################################*/
package opus.gwt.management.console.client.dashboard;
public class ProjectManagerController extends Composite {
private static ProjectDashboardUiBinder uiBinder = GWT.create(ProjectDashboardUiBinder.class);
interface ProjectDashboardUiBinder extends UiBinder<Widget, ProjectManagerController> {}
private DashboardPanel dashboardPanel;
// private DeleteProjectPanel deleteProjectPanel;
private AppSettingsPanel appSettingsPanel;
private EventBus eventBus;
private String projectName;
private ClientFactory clientFactory;
@UiField ProjectManagerStyle style;
@UiField DeckPanel managerDeckPanel;
public ProjectManagerController(ClientFactory clientFactory){
initWidget(uiBinder.createAndBindUi(this));
this.clientFactory = clientFactory;
this.eventBus = clientFactory.getEventBus();
this.dashboardPanel = new DashboardPanel(clientFactory);
this.appSettingsPanel = new AppSettingsPanel(clientFactory);
setupBreadCrumbs();
setupmanagerDeckPanel();
registerHandlers();
}
private void setupBreadCrumbs(){
String[] crumbs = {"Projects", projectName, dashboardPanel.getTitle()}; | eventBus.fireEvent(new BreadCrumbEvent(BreadCrumbEvent.Action.SET_CRUMBS, crumbs)); |
bmbouter/Opus | gwt/src/opus/gwt/management/console/client/dashboard/ProjectManagerController.java | // Path: gwt/src/opus/gwt/management/console/client/event/BreadCrumbEvent.java
// public class BreadCrumbEvent extends GwtEvent<BreadCrumbEventHandler> {
//
// public static Type<BreadCrumbEventHandler> TYPE = new Type<BreadCrumbEventHandler>();
// public enum Action{SET_CRUMBS, SET_ACTIVE, ADD_CRUMB, REMOVE_CRUMB};
// private Action actionType;
// private String[] names;
// private String crumb;
//
// public BreadCrumbEvent(Action actionType, String[] names){
// this.actionType = actionType;
// this.names = names;
// }
//
// public BreadCrumbEvent(Action actionType, String crumb){
// this.actionType = actionType;
// this.crumb = crumb;
// }
//
// public Action getAction(){
// return actionType;
// }
//
// public String getCrumb(){
// return crumb;
// }
//
// public String[] getCrumbNames(){
// return names;
// }
//
// @Override
// public Type<BreadCrumbEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(BreadCrumbEventHandler handler) {
// handler.onBreadCrumb(this);
// }
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
| import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.event.BreadCrumbEvent;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import opus.gwt.management.console.client.event.PanelTransitionEventHandler;
import opus.gwt.management.console.client.resources.ProjectManagerCss.ProjectManagerStyle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.Widget; | /*############################################################################
# Copyright 2010 North Carolina State University #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
############################################################################*/
package opus.gwt.management.console.client.dashboard;
public class ProjectManagerController extends Composite {
private static ProjectDashboardUiBinder uiBinder = GWT.create(ProjectDashboardUiBinder.class);
interface ProjectDashboardUiBinder extends UiBinder<Widget, ProjectManagerController> {}
private DashboardPanel dashboardPanel;
// private DeleteProjectPanel deleteProjectPanel;
private AppSettingsPanel appSettingsPanel;
private EventBus eventBus;
private String projectName;
private ClientFactory clientFactory;
@UiField ProjectManagerStyle style;
@UiField DeckPanel managerDeckPanel;
public ProjectManagerController(ClientFactory clientFactory){
initWidget(uiBinder.createAndBindUi(this));
this.clientFactory = clientFactory;
this.eventBus = clientFactory.getEventBus();
this.dashboardPanel = new DashboardPanel(clientFactory);
this.appSettingsPanel = new AppSettingsPanel(clientFactory);
setupBreadCrumbs();
setupmanagerDeckPanel();
registerHandlers();
}
private void setupBreadCrumbs(){
String[] crumbs = {"Projects", projectName, dashboardPanel.getTitle()};
eventBus.fireEvent(new BreadCrumbEvent(BreadCrumbEvent.Action.SET_CRUMBS, crumbs));
eventBus.fireEvent(new BreadCrumbEvent(BreadCrumbEvent.Action.SET_ACTIVE, projectName));
}
private void registerHandlers(){ | // Path: gwt/src/opus/gwt/management/console/client/event/BreadCrumbEvent.java
// public class BreadCrumbEvent extends GwtEvent<BreadCrumbEventHandler> {
//
// public static Type<BreadCrumbEventHandler> TYPE = new Type<BreadCrumbEventHandler>();
// public enum Action{SET_CRUMBS, SET_ACTIVE, ADD_CRUMB, REMOVE_CRUMB};
// private Action actionType;
// private String[] names;
// private String crumb;
//
// public BreadCrumbEvent(Action actionType, String[] names){
// this.actionType = actionType;
// this.names = names;
// }
//
// public BreadCrumbEvent(Action actionType, String crumb){
// this.actionType = actionType;
// this.crumb = crumb;
// }
//
// public Action getAction(){
// return actionType;
// }
//
// public String getCrumb(){
// return crumb;
// }
//
// public String[] getCrumbNames(){
// return names;
// }
//
// @Override
// public Type<BreadCrumbEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(BreadCrumbEventHandler handler) {
// handler.onBreadCrumb(this);
// }
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
// Path: gwt/src/opus/gwt/management/console/client/dashboard/ProjectManagerController.java
import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.event.BreadCrumbEvent;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import opus.gwt.management.console.client.event.PanelTransitionEventHandler;
import opus.gwt.management.console.client.resources.ProjectManagerCss.ProjectManagerStyle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.Widget;
/*############################################################################
# Copyright 2010 North Carolina State University #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
############################################################################*/
package opus.gwt.management.console.client.dashboard;
public class ProjectManagerController extends Composite {
private static ProjectDashboardUiBinder uiBinder = GWT.create(ProjectDashboardUiBinder.class);
interface ProjectDashboardUiBinder extends UiBinder<Widget, ProjectManagerController> {}
private DashboardPanel dashboardPanel;
// private DeleteProjectPanel deleteProjectPanel;
private AppSettingsPanel appSettingsPanel;
private EventBus eventBus;
private String projectName;
private ClientFactory clientFactory;
@UiField ProjectManagerStyle style;
@UiField DeckPanel managerDeckPanel;
public ProjectManagerController(ClientFactory clientFactory){
initWidget(uiBinder.createAndBindUi(this));
this.clientFactory = clientFactory;
this.eventBus = clientFactory.getEventBus();
this.dashboardPanel = new DashboardPanel(clientFactory);
this.appSettingsPanel = new AppSettingsPanel(clientFactory);
setupBreadCrumbs();
setupmanagerDeckPanel();
registerHandlers();
}
private void setupBreadCrumbs(){
String[] crumbs = {"Projects", projectName, dashboardPanel.getTitle()};
eventBus.fireEvent(new BreadCrumbEvent(BreadCrumbEvent.Action.SET_CRUMBS, crumbs));
eventBus.fireEvent(new BreadCrumbEvent(BreadCrumbEvent.Action.SET_ACTIVE, projectName));
}
private void registerHandlers(){ | eventBus.addHandler(PanelTransitionEvent.TYPE, |
bmbouter/Opus | gwt/src/opus/gwt/management/console/client/deployer/ProjectOptionsPanel.java | // Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
//
// Path: gwt/src/opus/gwt/management/console/client/resources/ProjectDeployerCss.java
// public interface ProjectDeployerStyle extends CssResource {
// String redBorder();
// String greyBorder();
// String loadingPopup();
// String loadingImage();
// String loadingGlass();
// String loadingLabel();
// }
//
// Path: gwt/src/opus/gwt/management/console/client/tools/TooltipPanel.java
// public class TooltipPanel extends PopupPanel {
// private static TooltipPanelUiBinder uiBinder = GWT.create(TooltipPanelUiBinder.class);
// interface TooltipPanelUiBinder extends UiBinder<Widget, TooltipPanel> {}
//
// @UiField HTML text;
// @UiField HTMLPanel content;
// @UiField HTMLPanel arrow;
// @UiField TooltipPanelStyle style;
//
// public TooltipPanel() {
// super();
// setWidget(uiBinder.createAndBindUi(this));
// setAutoHideEnabled(true);
// }
//
// /**
// * Set the text to a certain String
// * @param html the String to use; can contain HTML
// */
// public void setText(String html) {
// text.setHTML(html);
// }
//
// /**
// * Set the tooltip to a red color; typically used for errors
// */
// public void setRed() {
// content.setStyleName(style.tooltip_right_red());
// arrow.setStyleName(style.tooltip_left_red());
// }
//
// /**
// * Set the tooltip to a gray color; default color
// */
// public void setGray() {
// content.setStyleName(style.tooltip_right());
// arrow.setStyleName(style.tooltip_left());
// }
// }
| import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import opus.gwt.management.console.client.event.UpdateDBOptionsEvent;
import opus.gwt.management.console.client.event.UpdateDBOptionsEventHandler;
import opus.gwt.management.console.client.resources.ProjectDeployerCss.ProjectDeployerStyle;
import opus.gwt.management.console.client.tools.TooltipPanel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.URL;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget; | /*############################################################################
# Copyright 2010 North Carolina State University #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
############################################################################*/
package opus.gwt.management.console.client.deployer;
public class ProjectOptionsPanel extends Composite {
private static BuildProjectPage2UiBinder uiBinder = GWT.create(BuildProjectPage2UiBinder.class);
interface BuildProjectPage2UiBinder extends UiBinder<Widget, ProjectOptionsPanel> {}
private EventBus eventBus;
@UiField TextBox usernameTextBox;
@UiField TextBox emailTextBox;
@UiField PasswordTextBox passwordTextBox;
@UiField PasswordTextBox passwordConfirmTextBox;
@UiField Button nextButton;
@UiField Button previousButton;
@UiField HTMLPanel projectOptionsPanel;
@UiField ListBox idProvider; | // Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
//
// Path: gwt/src/opus/gwt/management/console/client/resources/ProjectDeployerCss.java
// public interface ProjectDeployerStyle extends CssResource {
// String redBorder();
// String greyBorder();
// String loadingPopup();
// String loadingImage();
// String loadingGlass();
// String loadingLabel();
// }
//
// Path: gwt/src/opus/gwt/management/console/client/tools/TooltipPanel.java
// public class TooltipPanel extends PopupPanel {
// private static TooltipPanelUiBinder uiBinder = GWT.create(TooltipPanelUiBinder.class);
// interface TooltipPanelUiBinder extends UiBinder<Widget, TooltipPanel> {}
//
// @UiField HTML text;
// @UiField HTMLPanel content;
// @UiField HTMLPanel arrow;
// @UiField TooltipPanelStyle style;
//
// public TooltipPanel() {
// super();
// setWidget(uiBinder.createAndBindUi(this));
// setAutoHideEnabled(true);
// }
//
// /**
// * Set the text to a certain String
// * @param html the String to use; can contain HTML
// */
// public void setText(String html) {
// text.setHTML(html);
// }
//
// /**
// * Set the tooltip to a red color; typically used for errors
// */
// public void setRed() {
// content.setStyleName(style.tooltip_right_red());
// arrow.setStyleName(style.tooltip_left_red());
// }
//
// /**
// * Set the tooltip to a gray color; default color
// */
// public void setGray() {
// content.setStyleName(style.tooltip_right());
// arrow.setStyleName(style.tooltip_left());
// }
// }
// Path: gwt/src/opus/gwt/management/console/client/deployer/ProjectOptionsPanel.java
import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import opus.gwt.management.console.client.event.UpdateDBOptionsEvent;
import opus.gwt.management.console.client.event.UpdateDBOptionsEventHandler;
import opus.gwt.management.console.client.resources.ProjectDeployerCss.ProjectDeployerStyle;
import opus.gwt.management.console.client.tools.TooltipPanel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.URL;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
/*############################################################################
# Copyright 2010 North Carolina State University #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
############################################################################*/
package opus.gwt.management.console.client.deployer;
public class ProjectOptionsPanel extends Composite {
private static BuildProjectPage2UiBinder uiBinder = GWT.create(BuildProjectPage2UiBinder.class);
interface BuildProjectPage2UiBinder extends UiBinder<Widget, ProjectOptionsPanel> {}
private EventBus eventBus;
@UiField TextBox usernameTextBox;
@UiField TextBox emailTextBox;
@UiField PasswordTextBox passwordTextBox;
@UiField PasswordTextBox passwordConfirmTextBox;
@UiField Button nextButton;
@UiField Button previousButton;
@UiField HTMLPanel projectOptionsPanel;
@UiField ListBox idProvider; | @UiField TooltipPanel active; |
bmbouter/Opus | gwt/src/opus/gwt/management/console/client/deployer/ProjectOptionsPanel.java | // Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
//
// Path: gwt/src/opus/gwt/management/console/client/resources/ProjectDeployerCss.java
// public interface ProjectDeployerStyle extends CssResource {
// String redBorder();
// String greyBorder();
// String loadingPopup();
// String loadingImage();
// String loadingGlass();
// String loadingLabel();
// }
//
// Path: gwt/src/opus/gwt/management/console/client/tools/TooltipPanel.java
// public class TooltipPanel extends PopupPanel {
// private static TooltipPanelUiBinder uiBinder = GWT.create(TooltipPanelUiBinder.class);
// interface TooltipPanelUiBinder extends UiBinder<Widget, TooltipPanel> {}
//
// @UiField HTML text;
// @UiField HTMLPanel content;
// @UiField HTMLPanel arrow;
// @UiField TooltipPanelStyle style;
//
// public TooltipPanel() {
// super();
// setWidget(uiBinder.createAndBindUi(this));
// setAutoHideEnabled(true);
// }
//
// /**
// * Set the text to a certain String
// * @param html the String to use; can contain HTML
// */
// public void setText(String html) {
// text.setHTML(html);
// }
//
// /**
// * Set the tooltip to a red color; typically used for errors
// */
// public void setRed() {
// content.setStyleName(style.tooltip_right_red());
// arrow.setStyleName(style.tooltip_left_red());
// }
//
// /**
// * Set the tooltip to a gray color; default color
// */
// public void setGray() {
// content.setStyleName(style.tooltip_right());
// arrow.setStyleName(style.tooltip_left());
// }
// }
| import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import opus.gwt.management.console.client.event.UpdateDBOptionsEvent;
import opus.gwt.management.console.client.event.UpdateDBOptionsEventHandler;
import opus.gwt.management.console.client.resources.ProjectDeployerCss.ProjectDeployerStyle;
import opus.gwt.management.console.client.tools.TooltipPanel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.URL;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget; | passwordConfirmTextBox.setStyleName(deployer.redBorder());
} else {
passwordError.setText("");
passwordTextBox.setStyleName(deployer.greyBorder());
passwordConfirmTextBox.setStyleName(deployer.greyBorder());
}
} else {
}
}
@UiHandler("emailTextBox")
void emailTextBoxOnChange(KeyUpEvent event) {
if(!usernameTextBox.getText().isEmpty()) {
if(!isEmailValid()) {
active.hide();
emailError.setText("Enter a valid email address");
emailTextBox.setStyleName(deployer.redBorder());
} else {
emailError.setText("");
emailTextBox.setStyleName(deployer.greyBorder());
}
} else {
}
}
@UiHandler("nextButton")
void handleNextButton(ClickEvent event){
if( validateFields() ){ | // Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
//
// Path: gwt/src/opus/gwt/management/console/client/resources/ProjectDeployerCss.java
// public interface ProjectDeployerStyle extends CssResource {
// String redBorder();
// String greyBorder();
// String loadingPopup();
// String loadingImage();
// String loadingGlass();
// String loadingLabel();
// }
//
// Path: gwt/src/opus/gwt/management/console/client/tools/TooltipPanel.java
// public class TooltipPanel extends PopupPanel {
// private static TooltipPanelUiBinder uiBinder = GWT.create(TooltipPanelUiBinder.class);
// interface TooltipPanelUiBinder extends UiBinder<Widget, TooltipPanel> {}
//
// @UiField HTML text;
// @UiField HTMLPanel content;
// @UiField HTMLPanel arrow;
// @UiField TooltipPanelStyle style;
//
// public TooltipPanel() {
// super();
// setWidget(uiBinder.createAndBindUi(this));
// setAutoHideEnabled(true);
// }
//
// /**
// * Set the text to a certain String
// * @param html the String to use; can contain HTML
// */
// public void setText(String html) {
// text.setHTML(html);
// }
//
// /**
// * Set the tooltip to a red color; typically used for errors
// */
// public void setRed() {
// content.setStyleName(style.tooltip_right_red());
// arrow.setStyleName(style.tooltip_left_red());
// }
//
// /**
// * Set the tooltip to a gray color; default color
// */
// public void setGray() {
// content.setStyleName(style.tooltip_right());
// arrow.setStyleName(style.tooltip_left());
// }
// }
// Path: gwt/src/opus/gwt/management/console/client/deployer/ProjectOptionsPanel.java
import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import opus.gwt.management.console.client.event.UpdateDBOptionsEvent;
import opus.gwt.management.console.client.event.UpdateDBOptionsEventHandler;
import opus.gwt.management.console.client.resources.ProjectDeployerCss.ProjectDeployerStyle;
import opus.gwt.management.console.client.tools.TooltipPanel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.URL;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
passwordConfirmTextBox.setStyleName(deployer.redBorder());
} else {
passwordError.setText("");
passwordTextBox.setStyleName(deployer.greyBorder());
passwordConfirmTextBox.setStyleName(deployer.greyBorder());
}
} else {
}
}
@UiHandler("emailTextBox")
void emailTextBoxOnChange(KeyUpEvent event) {
if(!usernameTextBox.getText().isEmpty()) {
if(!isEmailValid()) {
active.hide();
emailError.setText("Enter a valid email address");
emailTextBox.setStyleName(deployer.redBorder());
} else {
emailError.setText("");
emailTextBox.setStyleName(deployer.greyBorder());
}
} else {
}
}
@UiHandler("nextButton")
void handleNextButton(ClickEvent event){
if( validateFields() ){ | eventBus.fireEvent(new PanelTransitionEvent(PanelTransitionEvent.TransitionTypes.NEXT, this)); |
bmbouter/Opus | gwt/src/opus/gwt/management/console/client/ManagementConsoleController.java | // Path: gwt/src/opus/gwt/management/console/client/event/GetDjangoPackagesEvent.java
// public class GetDjangoPackagesEvent extends GwtEvent<GetDjangoPackagesEventHandler> {
//
// public static Type<GetDjangoPackagesEventHandler> TYPE = new Type<GetDjangoPackagesEventHandler>();
// private JsArray<DjangoPackage> djangoPackagesArray;
// private List<DjangoPackage> djangoPackagesMap = new ArrayList<DjangoPackage>();
//
// public GetDjangoPackagesEvent(JavaScriptObject djangoPackages){
// this.djangoPackagesArray = ConvertDjangoPackages(djangoPackages);
// processDjangoPackages();
// }
//
// private void processDjangoPackages() {
// for(int i = 0; i < djangoPackagesArray.length(); i++) {
// DjangoPackage dp = djangoPackagesArray.get(i);
// djangoPackagesMap.add(dp.getPk() - 1, dp);
// }
// }
//
// public List<DjangoPackage> getDjangoPackages(){
// return djangoPackagesMap;
// }
//
// @Override
// public Type<GetDjangoPackagesEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(GetDjangoPackagesEventHandler handler) {
// handler.onGetDjangoPackages(this);
// }
//
// public final native JsArray<DjangoPackage> ConvertDjangoPackages(JavaScriptObject jso) /*-{
// return jso;
// }-*/;
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/GetUserEventHandler.java
// public interface GetUserEventHandler extends EventHandler {
// void onGetUser(GetUserEvent event);
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
| import opus.gwt.management.console.client.event.AddProjectEvent;
import opus.gwt.management.console.client.event.AddProjectEventHandler;
import opus.gwt.management.console.client.event.AsyncRequestEvent;
import opus.gwt.management.console.client.event.DeleteProjectEvent;
import opus.gwt.management.console.client.event.DeleteProjectEventHandler;
import opus.gwt.management.console.client.event.GetApplicationsEvent;
import opus.gwt.management.console.client.event.GetApplicationsEventHandler;
import opus.gwt.management.console.client.event.GetDjangoPackagesEvent;
import opus.gwt.management.console.client.event.GetDjangoPackagesEventHandler;
import opus.gwt.management.console.client.event.GetProjectsEvent;
import opus.gwt.management.console.client.event.GetProjectsEventHandler;
import opus.gwt.management.console.client.event.GetUserEvent;
import opus.gwt.management.console.client.event.GetUserEventHandler;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
| package opus.gwt.management.console.client;
public class ManagementConsoleController {
private boolean projectsReady;
private boolean userReady;
private boolean djangoPackagesReady;
private boolean applicationsReady;
private ClientFactory clientFactory;
private EventBus eventBus;
public ManagementConsoleController(ClientFactory clientFactory){
this.clientFactory = clientFactory;
this.eventBus = clientFactory.getEventBus();
registerHandlers();
eventBus.fireEvent(new AsyncRequestEvent("getProjects"));
eventBus.fireEvent(new AsyncRequestEvent("getApplications"));
eventBus.fireEvent(new AsyncRequestEvent("getUser"));
eventBus.fireEvent(new AsyncRequestEvent("getDjangoPackages"));
}
private void registerHandlers(){
eventBus.addHandler(GetApplicationsEvent.TYPE,
new GetApplicationsEventHandler() {
public void onGetApplications(GetApplicationsEvent event) {
clientFactory.setApplications(event.getApplications());
applicationsReady = true;
start();
}
});
| // Path: gwt/src/opus/gwt/management/console/client/event/GetDjangoPackagesEvent.java
// public class GetDjangoPackagesEvent extends GwtEvent<GetDjangoPackagesEventHandler> {
//
// public static Type<GetDjangoPackagesEventHandler> TYPE = new Type<GetDjangoPackagesEventHandler>();
// private JsArray<DjangoPackage> djangoPackagesArray;
// private List<DjangoPackage> djangoPackagesMap = new ArrayList<DjangoPackage>();
//
// public GetDjangoPackagesEvent(JavaScriptObject djangoPackages){
// this.djangoPackagesArray = ConvertDjangoPackages(djangoPackages);
// processDjangoPackages();
// }
//
// private void processDjangoPackages() {
// for(int i = 0; i < djangoPackagesArray.length(); i++) {
// DjangoPackage dp = djangoPackagesArray.get(i);
// djangoPackagesMap.add(dp.getPk() - 1, dp);
// }
// }
//
// public List<DjangoPackage> getDjangoPackages(){
// return djangoPackagesMap;
// }
//
// @Override
// public Type<GetDjangoPackagesEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(GetDjangoPackagesEventHandler handler) {
// handler.onGetDjangoPackages(this);
// }
//
// public final native JsArray<DjangoPackage> ConvertDjangoPackages(JavaScriptObject jso) /*-{
// return jso;
// }-*/;
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/GetUserEventHandler.java
// public interface GetUserEventHandler extends EventHandler {
// void onGetUser(GetUserEvent event);
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
// Path: gwt/src/opus/gwt/management/console/client/ManagementConsoleController.java
import opus.gwt.management.console.client.event.AddProjectEvent;
import opus.gwt.management.console.client.event.AddProjectEventHandler;
import opus.gwt.management.console.client.event.AsyncRequestEvent;
import opus.gwt.management.console.client.event.DeleteProjectEvent;
import opus.gwt.management.console.client.event.DeleteProjectEventHandler;
import opus.gwt.management.console.client.event.GetApplicationsEvent;
import opus.gwt.management.console.client.event.GetApplicationsEventHandler;
import opus.gwt.management.console.client.event.GetDjangoPackagesEvent;
import opus.gwt.management.console.client.event.GetDjangoPackagesEventHandler;
import opus.gwt.management.console.client.event.GetProjectsEvent;
import opus.gwt.management.console.client.event.GetProjectsEventHandler;
import opus.gwt.management.console.client.event.GetUserEvent;
import opus.gwt.management.console.client.event.GetUserEventHandler;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
package opus.gwt.management.console.client;
public class ManagementConsoleController {
private boolean projectsReady;
private boolean userReady;
private boolean djangoPackagesReady;
private boolean applicationsReady;
private ClientFactory clientFactory;
private EventBus eventBus;
public ManagementConsoleController(ClientFactory clientFactory){
this.clientFactory = clientFactory;
this.eventBus = clientFactory.getEventBus();
registerHandlers();
eventBus.fireEvent(new AsyncRequestEvent("getProjects"));
eventBus.fireEvent(new AsyncRequestEvent("getApplications"));
eventBus.fireEvent(new AsyncRequestEvent("getUser"));
eventBus.fireEvent(new AsyncRequestEvent("getDjangoPackages"));
}
private void registerHandlers(){
eventBus.addHandler(GetApplicationsEvent.TYPE,
new GetApplicationsEventHandler() {
public void onGetApplications(GetApplicationsEvent event) {
clientFactory.setApplications(event.getApplications());
applicationsReady = true;
start();
}
});
| eventBus.addHandler(GetDjangoPackagesEvent.TYPE,
|
bmbouter/Opus | gwt/src/opus/gwt/management/console/client/ManagementConsoleController.java | // Path: gwt/src/opus/gwt/management/console/client/event/GetDjangoPackagesEvent.java
// public class GetDjangoPackagesEvent extends GwtEvent<GetDjangoPackagesEventHandler> {
//
// public static Type<GetDjangoPackagesEventHandler> TYPE = new Type<GetDjangoPackagesEventHandler>();
// private JsArray<DjangoPackage> djangoPackagesArray;
// private List<DjangoPackage> djangoPackagesMap = new ArrayList<DjangoPackage>();
//
// public GetDjangoPackagesEvent(JavaScriptObject djangoPackages){
// this.djangoPackagesArray = ConvertDjangoPackages(djangoPackages);
// processDjangoPackages();
// }
//
// private void processDjangoPackages() {
// for(int i = 0; i < djangoPackagesArray.length(); i++) {
// DjangoPackage dp = djangoPackagesArray.get(i);
// djangoPackagesMap.add(dp.getPk() - 1, dp);
// }
// }
//
// public List<DjangoPackage> getDjangoPackages(){
// return djangoPackagesMap;
// }
//
// @Override
// public Type<GetDjangoPackagesEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(GetDjangoPackagesEventHandler handler) {
// handler.onGetDjangoPackages(this);
// }
//
// public final native JsArray<DjangoPackage> ConvertDjangoPackages(JavaScriptObject jso) /*-{
// return jso;
// }-*/;
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/GetUserEventHandler.java
// public interface GetUserEventHandler extends EventHandler {
// void onGetUser(GetUserEvent event);
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
| import opus.gwt.management.console.client.event.AddProjectEvent;
import opus.gwt.management.console.client.event.AddProjectEventHandler;
import opus.gwt.management.console.client.event.AsyncRequestEvent;
import opus.gwt.management.console.client.event.DeleteProjectEvent;
import opus.gwt.management.console.client.event.DeleteProjectEventHandler;
import opus.gwt.management.console.client.event.GetApplicationsEvent;
import opus.gwt.management.console.client.event.GetApplicationsEventHandler;
import opus.gwt.management.console.client.event.GetDjangoPackagesEvent;
import opus.gwt.management.console.client.event.GetDjangoPackagesEventHandler;
import opus.gwt.management.console.client.event.GetProjectsEvent;
import opus.gwt.management.console.client.event.GetProjectsEventHandler;
import opus.gwt.management.console.client.event.GetUserEvent;
import opus.gwt.management.console.client.event.GetUserEventHandler;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
| private EventBus eventBus;
public ManagementConsoleController(ClientFactory clientFactory){
this.clientFactory = clientFactory;
this.eventBus = clientFactory.getEventBus();
registerHandlers();
eventBus.fireEvent(new AsyncRequestEvent("getProjects"));
eventBus.fireEvent(new AsyncRequestEvent("getApplications"));
eventBus.fireEvent(new AsyncRequestEvent("getUser"));
eventBus.fireEvent(new AsyncRequestEvent("getDjangoPackages"));
}
private void registerHandlers(){
eventBus.addHandler(GetApplicationsEvent.TYPE,
new GetApplicationsEventHandler() {
public void onGetApplications(GetApplicationsEvent event) {
clientFactory.setApplications(event.getApplications());
applicationsReady = true;
start();
}
});
eventBus.addHandler(GetDjangoPackagesEvent.TYPE,
new GetDjangoPackagesEventHandler() {
public void onGetDjangoPackages(GetDjangoPackagesEvent event) {
clientFactory.setDjangoPackages(event.getDjangoPackages());
djangoPackagesReady = true;
start();
}
});
eventBus.addHandler(GetUserEvent.TYPE,
| // Path: gwt/src/opus/gwt/management/console/client/event/GetDjangoPackagesEvent.java
// public class GetDjangoPackagesEvent extends GwtEvent<GetDjangoPackagesEventHandler> {
//
// public static Type<GetDjangoPackagesEventHandler> TYPE = new Type<GetDjangoPackagesEventHandler>();
// private JsArray<DjangoPackage> djangoPackagesArray;
// private List<DjangoPackage> djangoPackagesMap = new ArrayList<DjangoPackage>();
//
// public GetDjangoPackagesEvent(JavaScriptObject djangoPackages){
// this.djangoPackagesArray = ConvertDjangoPackages(djangoPackages);
// processDjangoPackages();
// }
//
// private void processDjangoPackages() {
// for(int i = 0; i < djangoPackagesArray.length(); i++) {
// DjangoPackage dp = djangoPackagesArray.get(i);
// djangoPackagesMap.add(dp.getPk() - 1, dp);
// }
// }
//
// public List<DjangoPackage> getDjangoPackages(){
// return djangoPackagesMap;
// }
//
// @Override
// public Type<GetDjangoPackagesEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(GetDjangoPackagesEventHandler handler) {
// handler.onGetDjangoPackages(this);
// }
//
// public final native JsArray<DjangoPackage> ConvertDjangoPackages(JavaScriptObject jso) /*-{
// return jso;
// }-*/;
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/GetUserEventHandler.java
// public interface GetUserEventHandler extends EventHandler {
// void onGetUser(GetUserEvent event);
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
// Path: gwt/src/opus/gwt/management/console/client/ManagementConsoleController.java
import opus.gwt.management.console.client.event.AddProjectEvent;
import opus.gwt.management.console.client.event.AddProjectEventHandler;
import opus.gwt.management.console.client.event.AsyncRequestEvent;
import opus.gwt.management.console.client.event.DeleteProjectEvent;
import opus.gwt.management.console.client.event.DeleteProjectEventHandler;
import opus.gwt.management.console.client.event.GetApplicationsEvent;
import opus.gwt.management.console.client.event.GetApplicationsEventHandler;
import opus.gwt.management.console.client.event.GetDjangoPackagesEvent;
import opus.gwt.management.console.client.event.GetDjangoPackagesEventHandler;
import opus.gwt.management.console.client.event.GetProjectsEvent;
import opus.gwt.management.console.client.event.GetProjectsEventHandler;
import opus.gwt.management.console.client.event.GetUserEvent;
import opus.gwt.management.console.client.event.GetUserEventHandler;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
private EventBus eventBus;
public ManagementConsoleController(ClientFactory clientFactory){
this.clientFactory = clientFactory;
this.eventBus = clientFactory.getEventBus();
registerHandlers();
eventBus.fireEvent(new AsyncRequestEvent("getProjects"));
eventBus.fireEvent(new AsyncRequestEvent("getApplications"));
eventBus.fireEvent(new AsyncRequestEvent("getUser"));
eventBus.fireEvent(new AsyncRequestEvent("getDjangoPackages"));
}
private void registerHandlers(){
eventBus.addHandler(GetApplicationsEvent.TYPE,
new GetApplicationsEventHandler() {
public void onGetApplications(GetApplicationsEvent event) {
clientFactory.setApplications(event.getApplications());
applicationsReady = true;
start();
}
});
eventBus.addHandler(GetDjangoPackagesEvent.TYPE,
new GetDjangoPackagesEventHandler() {
public void onGetDjangoPackages(GetDjangoPackagesEvent event) {
clientFactory.setDjangoPackages(event.getDjangoPackages());
djangoPackagesReady = true;
start();
}
});
eventBus.addHandler(GetUserEvent.TYPE,
| new GetUserEventHandler() {
|
bmbouter/Opus | gwt/src/opus/gwt/management/console/client/ManagementConsoleController.java | // Path: gwt/src/opus/gwt/management/console/client/event/GetDjangoPackagesEvent.java
// public class GetDjangoPackagesEvent extends GwtEvent<GetDjangoPackagesEventHandler> {
//
// public static Type<GetDjangoPackagesEventHandler> TYPE = new Type<GetDjangoPackagesEventHandler>();
// private JsArray<DjangoPackage> djangoPackagesArray;
// private List<DjangoPackage> djangoPackagesMap = new ArrayList<DjangoPackage>();
//
// public GetDjangoPackagesEvent(JavaScriptObject djangoPackages){
// this.djangoPackagesArray = ConvertDjangoPackages(djangoPackages);
// processDjangoPackages();
// }
//
// private void processDjangoPackages() {
// for(int i = 0; i < djangoPackagesArray.length(); i++) {
// DjangoPackage dp = djangoPackagesArray.get(i);
// djangoPackagesMap.add(dp.getPk() - 1, dp);
// }
// }
//
// public List<DjangoPackage> getDjangoPackages(){
// return djangoPackagesMap;
// }
//
// @Override
// public Type<GetDjangoPackagesEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(GetDjangoPackagesEventHandler handler) {
// handler.onGetDjangoPackages(this);
// }
//
// public final native JsArray<DjangoPackage> ConvertDjangoPackages(JavaScriptObject jso) /*-{
// return jso;
// }-*/;
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/GetUserEventHandler.java
// public interface GetUserEventHandler extends EventHandler {
// void onGetUser(GetUserEvent event);
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
| import opus.gwt.management.console.client.event.AddProjectEvent;
import opus.gwt.management.console.client.event.AddProjectEventHandler;
import opus.gwt.management.console.client.event.AsyncRequestEvent;
import opus.gwt.management.console.client.event.DeleteProjectEvent;
import opus.gwt.management.console.client.event.DeleteProjectEventHandler;
import opus.gwt.management.console.client.event.GetApplicationsEvent;
import opus.gwt.management.console.client.event.GetApplicationsEventHandler;
import opus.gwt.management.console.client.event.GetDjangoPackagesEvent;
import opus.gwt.management.console.client.event.GetDjangoPackagesEventHandler;
import opus.gwt.management.console.client.event.GetProjectsEvent;
import opus.gwt.management.console.client.event.GetProjectsEventHandler;
import opus.gwt.management.console.client.event.GetUserEvent;
import opus.gwt.management.console.client.event.GetUserEventHandler;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
| }
});
eventBus.addHandler(GetDjangoPackagesEvent.TYPE,
new GetDjangoPackagesEventHandler() {
public void onGetDjangoPackages(GetDjangoPackagesEvent event) {
clientFactory.setDjangoPackages(event.getDjangoPackages());
djangoPackagesReady = true;
start();
}
});
eventBus.addHandler(GetUserEvent.TYPE,
new GetUserEventHandler() {
public void onGetUser(GetUserEvent event) {
clientFactory.setUser(event.getUser());
userReady = true;
start();
}
});
eventBus.addHandler(GetProjectsEvent.TYPE,
new GetProjectsEventHandler(){
public void onGetProjects(GetProjectsEvent event) {
clientFactory.setProjects(event.getProjects());
projectsReady = true;
start();
}
});
eventBus.addHandler(AddProjectEvent.TYPE,
new AddProjectEventHandler(){
public void onAddProject(AddProjectEvent event) {
clientFactory.getProjects().put(event.getProject().getName(), event.getProject());
| // Path: gwt/src/opus/gwt/management/console/client/event/GetDjangoPackagesEvent.java
// public class GetDjangoPackagesEvent extends GwtEvent<GetDjangoPackagesEventHandler> {
//
// public static Type<GetDjangoPackagesEventHandler> TYPE = new Type<GetDjangoPackagesEventHandler>();
// private JsArray<DjangoPackage> djangoPackagesArray;
// private List<DjangoPackage> djangoPackagesMap = new ArrayList<DjangoPackage>();
//
// public GetDjangoPackagesEvent(JavaScriptObject djangoPackages){
// this.djangoPackagesArray = ConvertDjangoPackages(djangoPackages);
// processDjangoPackages();
// }
//
// private void processDjangoPackages() {
// for(int i = 0; i < djangoPackagesArray.length(); i++) {
// DjangoPackage dp = djangoPackagesArray.get(i);
// djangoPackagesMap.add(dp.getPk() - 1, dp);
// }
// }
//
// public List<DjangoPackage> getDjangoPackages(){
// return djangoPackagesMap;
// }
//
// @Override
// public Type<GetDjangoPackagesEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(GetDjangoPackagesEventHandler handler) {
// handler.onGetDjangoPackages(this);
// }
//
// public final native JsArray<DjangoPackage> ConvertDjangoPackages(JavaScriptObject jso) /*-{
// return jso;
// }-*/;
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/GetUserEventHandler.java
// public interface GetUserEventHandler extends EventHandler {
// void onGetUser(GetUserEvent event);
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
// Path: gwt/src/opus/gwt/management/console/client/ManagementConsoleController.java
import opus.gwt.management.console.client.event.AddProjectEvent;
import opus.gwt.management.console.client.event.AddProjectEventHandler;
import opus.gwt.management.console.client.event.AsyncRequestEvent;
import opus.gwt.management.console.client.event.DeleteProjectEvent;
import opus.gwt.management.console.client.event.DeleteProjectEventHandler;
import opus.gwt.management.console.client.event.GetApplicationsEvent;
import opus.gwt.management.console.client.event.GetApplicationsEventHandler;
import opus.gwt.management.console.client.event.GetDjangoPackagesEvent;
import opus.gwt.management.console.client.event.GetDjangoPackagesEventHandler;
import opus.gwt.management.console.client.event.GetProjectsEvent;
import opus.gwt.management.console.client.event.GetProjectsEventHandler;
import opus.gwt.management.console.client.event.GetUserEvent;
import opus.gwt.management.console.client.event.GetUserEventHandler;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
}
});
eventBus.addHandler(GetDjangoPackagesEvent.TYPE,
new GetDjangoPackagesEventHandler() {
public void onGetDjangoPackages(GetDjangoPackagesEvent event) {
clientFactory.setDjangoPackages(event.getDjangoPackages());
djangoPackagesReady = true;
start();
}
});
eventBus.addHandler(GetUserEvent.TYPE,
new GetUserEventHandler() {
public void onGetUser(GetUserEvent event) {
clientFactory.setUser(event.getUser());
userReady = true;
start();
}
});
eventBus.addHandler(GetProjectsEvent.TYPE,
new GetProjectsEventHandler(){
public void onGetProjects(GetProjectsEvent event) {
clientFactory.setProjects(event.getProjects());
projectsReady = true;
start();
}
});
eventBus.addHandler(AddProjectEvent.TYPE,
new AddProjectEventHandler(){
public void onAddProject(AddProjectEvent event) {
clientFactory.getProjects().put(event.getProject().getName(), event.getProject());
| eventBus.fireEvent(new PanelTransitionEvent(PanelTransitionEvent.TransitionTypes.DASHBOARD, event.getProject().getName()));
|
bmbouter/Opus | gwt/src/opus/gwt/management/console/client/tools/TooltipPanel.java | // Path: gwt/src/opus/gwt/management/console/client/resources/TooltipPanelCss.java
// public interface TooltipPanelStyle extends CssResource {
// String tooltip_right();
// String tooltip_right_red();
// String tooltip_left();
// String tooltip_left_red();
// }
| import opus.gwt.management.console.client.resources.TooltipPanelCss.TooltipPanelStyle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget; | package opus.gwt.management.console.client.tools;
public class TooltipPanel extends PopupPanel {
private static TooltipPanelUiBinder uiBinder = GWT.create(TooltipPanelUiBinder.class);
interface TooltipPanelUiBinder extends UiBinder<Widget, TooltipPanel> {}
@UiField HTML text;
@UiField HTMLPanel content;
@UiField HTMLPanel arrow; | // Path: gwt/src/opus/gwt/management/console/client/resources/TooltipPanelCss.java
// public interface TooltipPanelStyle extends CssResource {
// String tooltip_right();
// String tooltip_right_red();
// String tooltip_left();
// String tooltip_left_red();
// }
// Path: gwt/src/opus/gwt/management/console/client/tools/TooltipPanel.java
import opus.gwt.management.console.client.resources.TooltipPanelCss.TooltipPanelStyle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
package opus.gwt.management.console.client.tools;
public class TooltipPanel extends PopupPanel {
private static TooltipPanelUiBinder uiBinder = GWT.create(TooltipPanelUiBinder.class);
interface TooltipPanelUiBinder extends UiBinder<Widget, TooltipPanel> {}
@UiField HTML text;
@UiField HTMLPanel content;
@UiField HTMLPanel arrow; | @UiField TooltipPanelStyle style; |
bmbouter/Opus | gwt/src/opus/gwt/management/console/client/event/UpdateVersionEvent.java | // Path: gwt/src/opus/gwt/management/console/client/overlays/VersionData.java
// public class VersionData extends JavaScriptObject { // [1]
// // Overlay types always have protected, zero argument constructors.
// protected VersionData() {} // [2]
//
// // JSNI methods to get stock data.
// public final native String getVersion() /*-{ return this.version; }-*/; // [3]
// public final native JsArray<DependencyData> getDependencies() /*-{ return this.dependencies; }-*/;
// public final native String getPath() /*-{ return this.path }-*/;
// public final native String getType() /*-{ return this.type }-*/;
// public final native String getVersionPk() /*-{ return this.pk; }-*/;
// public final native String getTag() /*-{ return this.tag; }-*/;
// public final native String getAppPk() /*-{ return this.app_pk }-*/;
//
// }
| import opus.gwt.management.console.client.overlays.VersionData;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.shared.GwtEvent;
| package opus.gwt.management.console.client.event;
public class UpdateVersionEvent extends GwtEvent<UpdateVersionEventHandler> {
public static Type<UpdateVersionEventHandler> TYPE = new Type<UpdateVersionEventHandler>();
| // Path: gwt/src/opus/gwt/management/console/client/overlays/VersionData.java
// public class VersionData extends JavaScriptObject { // [1]
// // Overlay types always have protected, zero argument constructors.
// protected VersionData() {} // [2]
//
// // JSNI methods to get stock data.
// public final native String getVersion() /*-{ return this.version; }-*/; // [3]
// public final native JsArray<DependencyData> getDependencies() /*-{ return this.dependencies; }-*/;
// public final native String getPath() /*-{ return this.path }-*/;
// public final native String getType() /*-{ return this.type }-*/;
// public final native String getVersionPk() /*-{ return this.pk; }-*/;
// public final native String getTag() /*-{ return this.tag; }-*/;
// public final native String getAppPk() /*-{ return this.app_pk }-*/;
//
// }
// Path: gwt/src/opus/gwt/management/console/client/event/UpdateVersionEvent.java
import opus.gwt.management.console.client.overlays.VersionData;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.shared.GwtEvent;
package opus.gwt.management.console.client.event;
public class UpdateVersionEvent extends GwtEvent<UpdateVersionEventHandler> {
public static Type<UpdateVersionEventHandler> TYPE = new Type<UpdateVersionEventHandler>();
| private JsArray<VersionData> versionInfo;
|
bmbouter/Opus | gwt/src/opus/gwt/management/console/client/navigation/BreadCrumbsPanel.java | // Path: gwt/src/opus/gwt/management/console/client/event/BreadCrumbEvent.java
// public class BreadCrumbEvent extends GwtEvent<BreadCrumbEventHandler> {
//
// public static Type<BreadCrumbEventHandler> TYPE = new Type<BreadCrumbEventHandler>();
// public enum Action{SET_CRUMBS, SET_ACTIVE, ADD_CRUMB, REMOVE_CRUMB};
// private Action actionType;
// private String[] names;
// private String crumb;
//
// public BreadCrumbEvent(Action actionType, String[] names){
// this.actionType = actionType;
// this.names = names;
// }
//
// public BreadCrumbEvent(Action actionType, String crumb){
// this.actionType = actionType;
// this.crumb = crumb;
// }
//
// public Action getAction(){
// return actionType;
// }
//
// public String getCrumb(){
// return crumb;
// }
//
// public String[] getCrumbNames(){
// return names;
// }
//
// @Override
// public Type<BreadCrumbEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(BreadCrumbEventHandler handler) {
// handler.onBreadCrumb(this);
// }
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/BreadCrumbEventHandler.java
// public interface BreadCrumbEventHandler extends EventHandler {
// void onBreadCrumb(BreadCrumbEvent event);
// }
| import java.util.HashMap;
import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.event.BreadCrumbEvent;
import opus.gwt.management.console.client.event.BreadCrumbEventHandler;
import opus.gwt.management.console.client.resources.BreadCrumbsPanelCss.BreadCrumbsPanelStyle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
| package opus.gwt.management.console.client.navigation;
public class BreadCrumbsPanel extends Composite {
private static BreadCrumbsUiBinder uiBinder = GWT.create(BreadCrumbsUiBinder.class);
interface BreadCrumbsUiBinder extends UiBinder<Widget, BreadCrumbsPanel> {}
private EventBus eventBus;
private HTML activeCrumb;
private HashMap<String, HTML> breadCrumbLabels;
@UiField FlowPanel breadCrumbsContainer;
@UiField BreadCrumbsPanelStyle style;
public BreadCrumbsPanel(ClientFactory clientFactory) {
initWidget(uiBinder.createAndBindUi(this));
this.eventBus = clientFactory.getEventBus();
registerHandlers();
activeCrumb = new HTML();
breadCrumbLabels = new HashMap<String, HTML>();
}
private void registerHandlers(){
| // Path: gwt/src/opus/gwt/management/console/client/event/BreadCrumbEvent.java
// public class BreadCrumbEvent extends GwtEvent<BreadCrumbEventHandler> {
//
// public static Type<BreadCrumbEventHandler> TYPE = new Type<BreadCrumbEventHandler>();
// public enum Action{SET_CRUMBS, SET_ACTIVE, ADD_CRUMB, REMOVE_CRUMB};
// private Action actionType;
// private String[] names;
// private String crumb;
//
// public BreadCrumbEvent(Action actionType, String[] names){
// this.actionType = actionType;
// this.names = names;
// }
//
// public BreadCrumbEvent(Action actionType, String crumb){
// this.actionType = actionType;
// this.crumb = crumb;
// }
//
// public Action getAction(){
// return actionType;
// }
//
// public String getCrumb(){
// return crumb;
// }
//
// public String[] getCrumbNames(){
// return names;
// }
//
// @Override
// public Type<BreadCrumbEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(BreadCrumbEventHandler handler) {
// handler.onBreadCrumb(this);
// }
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/BreadCrumbEventHandler.java
// public interface BreadCrumbEventHandler extends EventHandler {
// void onBreadCrumb(BreadCrumbEvent event);
// }
// Path: gwt/src/opus/gwt/management/console/client/navigation/BreadCrumbsPanel.java
import java.util.HashMap;
import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.event.BreadCrumbEvent;
import opus.gwt.management.console.client.event.BreadCrumbEventHandler;
import opus.gwt.management.console.client.resources.BreadCrumbsPanelCss.BreadCrumbsPanelStyle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
package opus.gwt.management.console.client.navigation;
public class BreadCrumbsPanel extends Composite {
private static BreadCrumbsUiBinder uiBinder = GWT.create(BreadCrumbsUiBinder.class);
interface BreadCrumbsUiBinder extends UiBinder<Widget, BreadCrumbsPanel> {}
private EventBus eventBus;
private HTML activeCrumb;
private HashMap<String, HTML> breadCrumbLabels;
@UiField FlowPanel breadCrumbsContainer;
@UiField BreadCrumbsPanelStyle style;
public BreadCrumbsPanel(ClientFactory clientFactory) {
initWidget(uiBinder.createAndBindUi(this));
this.eventBus = clientFactory.getEventBus();
registerHandlers();
activeCrumb = new HTML();
breadCrumbLabels = new HashMap<String, HTML>();
}
private void registerHandlers(){
| eventBus.addHandler(BreadCrumbEvent.TYPE,
|
bmbouter/Opus | gwt/src/opus/gwt/management/console/client/navigation/BreadCrumbsPanel.java | // Path: gwt/src/opus/gwt/management/console/client/event/BreadCrumbEvent.java
// public class BreadCrumbEvent extends GwtEvent<BreadCrumbEventHandler> {
//
// public static Type<BreadCrumbEventHandler> TYPE = new Type<BreadCrumbEventHandler>();
// public enum Action{SET_CRUMBS, SET_ACTIVE, ADD_CRUMB, REMOVE_CRUMB};
// private Action actionType;
// private String[] names;
// private String crumb;
//
// public BreadCrumbEvent(Action actionType, String[] names){
// this.actionType = actionType;
// this.names = names;
// }
//
// public BreadCrumbEvent(Action actionType, String crumb){
// this.actionType = actionType;
// this.crumb = crumb;
// }
//
// public Action getAction(){
// return actionType;
// }
//
// public String getCrumb(){
// return crumb;
// }
//
// public String[] getCrumbNames(){
// return names;
// }
//
// @Override
// public Type<BreadCrumbEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(BreadCrumbEventHandler handler) {
// handler.onBreadCrumb(this);
// }
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/BreadCrumbEventHandler.java
// public interface BreadCrumbEventHandler extends EventHandler {
// void onBreadCrumb(BreadCrumbEvent event);
// }
| import java.util.HashMap;
import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.event.BreadCrumbEvent;
import opus.gwt.management.console.client.event.BreadCrumbEventHandler;
import opus.gwt.management.console.client.resources.BreadCrumbsPanelCss.BreadCrumbsPanelStyle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
| package opus.gwt.management.console.client.navigation;
public class BreadCrumbsPanel extends Composite {
private static BreadCrumbsUiBinder uiBinder = GWT.create(BreadCrumbsUiBinder.class);
interface BreadCrumbsUiBinder extends UiBinder<Widget, BreadCrumbsPanel> {}
private EventBus eventBus;
private HTML activeCrumb;
private HashMap<String, HTML> breadCrumbLabels;
@UiField FlowPanel breadCrumbsContainer;
@UiField BreadCrumbsPanelStyle style;
public BreadCrumbsPanel(ClientFactory clientFactory) {
initWidget(uiBinder.createAndBindUi(this));
this.eventBus = clientFactory.getEventBus();
registerHandlers();
activeCrumb = new HTML();
breadCrumbLabels = new HashMap<String, HTML>();
}
private void registerHandlers(){
eventBus.addHandler(BreadCrumbEvent.TYPE,
| // Path: gwt/src/opus/gwt/management/console/client/event/BreadCrumbEvent.java
// public class BreadCrumbEvent extends GwtEvent<BreadCrumbEventHandler> {
//
// public static Type<BreadCrumbEventHandler> TYPE = new Type<BreadCrumbEventHandler>();
// public enum Action{SET_CRUMBS, SET_ACTIVE, ADD_CRUMB, REMOVE_CRUMB};
// private Action actionType;
// private String[] names;
// private String crumb;
//
// public BreadCrumbEvent(Action actionType, String[] names){
// this.actionType = actionType;
// this.names = names;
// }
//
// public BreadCrumbEvent(Action actionType, String crumb){
// this.actionType = actionType;
// this.crumb = crumb;
// }
//
// public Action getAction(){
// return actionType;
// }
//
// public String getCrumb(){
// return crumb;
// }
//
// public String[] getCrumbNames(){
// return names;
// }
//
// @Override
// public Type<BreadCrumbEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(BreadCrumbEventHandler handler) {
// handler.onBreadCrumb(this);
// }
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/BreadCrumbEventHandler.java
// public interface BreadCrumbEventHandler extends EventHandler {
// void onBreadCrumb(BreadCrumbEvent event);
// }
// Path: gwt/src/opus/gwt/management/console/client/navigation/BreadCrumbsPanel.java
import java.util.HashMap;
import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.event.BreadCrumbEvent;
import opus.gwt.management.console.client.event.BreadCrumbEventHandler;
import opus.gwt.management.console.client.resources.BreadCrumbsPanelCss.BreadCrumbsPanelStyle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
package opus.gwt.management.console.client.navigation;
public class BreadCrumbsPanel extends Composite {
private static BreadCrumbsUiBinder uiBinder = GWT.create(BreadCrumbsUiBinder.class);
interface BreadCrumbsUiBinder extends UiBinder<Widget, BreadCrumbsPanel> {}
private EventBus eventBus;
private HTML activeCrumb;
private HashMap<String, HTML> breadCrumbLabels;
@UiField FlowPanel breadCrumbsContainer;
@UiField BreadCrumbsPanelStyle style;
public BreadCrumbsPanel(ClientFactory clientFactory) {
initWidget(uiBinder.createAndBindUi(this));
this.eventBus = clientFactory.getEventBus();
registerHandlers();
activeCrumb = new HTML();
breadCrumbLabels = new HashMap<String, HTML>();
}
private void registerHandlers(){
eventBus.addHandler(BreadCrumbEvent.TYPE,
| new BreadCrumbEventHandler(){
|
bmbouter/Opus | gwt/src/opus/gwt/management/console/client/dashboard/DashboardPanel.java | // Path: gwt/src/opus/gwt/management/console/client/JSVariableHandler.java
// public class JSVariableHandler {
//
// public JSVariableHandler(){}
//
// public native String getRepoBaseURL()/*-{
// return $wnd.repoBaseURL;
// }-*/;
//
// public native String getDeployerBaseURL()/*-{
// return $wnd.deployerBaseURL;
// }-*/;
//
// public native String getCommunityBaseURL()/*-{
// return $wnd.communityBaseURL;
// }-*/;
//
// public native String getProjectToken()/*-{
// return $wnd.projectToken;
// }-*/;
//
// public native String getBuildProjectURL()/*-{
// return $wnd.buildProjectURL;
// }-*/;
//
// public native String getCSRFTokenURL()/*-{
// return $wnd.csrftoken;
// }-*/;
//
// public native String getUser()/*-{
// return $wnd.user;
// }-*/;
//
//
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
| import java.util.HashMap;
import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.JSVariableHandler;
import opus.gwt.management.console.client.event.DeleteProjectEvent;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import opus.gwt.management.console.client.event.PanelTransitionEventHandler;
import opus.gwt.management.console.client.overlays.Application;
import opus.gwt.management.console.client.overlays.Project;
import opus.gwt.management.console.client.resources.ManagementConsoleControllerResources.ManagementConsoleControllerStyle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent; | private String projectName;
private boolean active;
private FormPanel deleteForm;
@UiField FlowPanel applicationsFlowPanel;
@UiField Button settingsButton;
@UiField ManagementConsoleControllerStyle manager;
@UiField Label projectLabel;
@UiField Button activeButton;
@UiField Button deleteButton;
@UiField FlexTable formContainer;
@UiField FormPanel optionsForm;
@UiField PopupPanel deletePopupPanel;
@UiField Button destroyButton;
@UiField Button noThanksButton;
@UiField FlowPanel deleteTitlePanel;
public DashboardPanel(ClientFactory clientFactory) {
initWidget(uiBinder.createAndBindUi(this));
this.eventBus = clientFactory.getEventBus();
this.clientFactory = clientFactory;
this.JSVarHandler = clientFactory.getJSVariableHandler();
this.applications = clientFactory.getApplications();
activeButton.setText("");
deleteForm = new FormPanel();
registerHandlers();
setDeletePopupPanelInitialState();
}
private void registerHandlers() { | // Path: gwt/src/opus/gwt/management/console/client/JSVariableHandler.java
// public class JSVariableHandler {
//
// public JSVariableHandler(){}
//
// public native String getRepoBaseURL()/*-{
// return $wnd.repoBaseURL;
// }-*/;
//
// public native String getDeployerBaseURL()/*-{
// return $wnd.deployerBaseURL;
// }-*/;
//
// public native String getCommunityBaseURL()/*-{
// return $wnd.communityBaseURL;
// }-*/;
//
// public native String getProjectToken()/*-{
// return $wnd.projectToken;
// }-*/;
//
// public native String getBuildProjectURL()/*-{
// return $wnd.buildProjectURL;
// }-*/;
//
// public native String getCSRFTokenURL()/*-{
// return $wnd.csrftoken;
// }-*/;
//
// public native String getUser()/*-{
// return $wnd.user;
// }-*/;
//
//
// }
//
// Path: gwt/src/opus/gwt/management/console/client/event/PanelTransitionEvent.java
// public class PanelTransitionEvent extends GwtEvent<PanelTransitionEventHandler> {
//
// public static Type<PanelTransitionEventHandler> TYPE = new Type<PanelTransitionEventHandler>();
// //private String transitionType;
// private Widget panel;
// public enum TransitionTypes{PREVIOUS, NEXT, DELETE, SETTINGS, DEPLOY, PROJECTS, DASHBOARD};
// private TransitionTypes transitionType;
// public String name;
//
// public PanelTransitionEvent(TransitionTypes transitionType, Widget panel){
// this.transitionType = transitionType;
// this.panel = panel;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType){
// this.transitionType = transitionType;
// }
//
// public PanelTransitionEvent(TransitionTypes transitionType, String name){
// this.name = name;
// this.transitionType = transitionType;
// }
//
// public TransitionTypes getTransitionType(){
// return transitionType;
// }
//
// public Widget getPanel(){
// return panel;
// }
//
// public String getName(){
// return name;
// }
//
// @Override
// public Type<PanelTransitionEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(PanelTransitionEventHandler handler) {
// handler.onPanelTransition(this);
// }
// }
// Path: gwt/src/opus/gwt/management/console/client/dashboard/DashboardPanel.java
import java.util.HashMap;
import opus.gwt.management.console.client.ClientFactory;
import opus.gwt.management.console.client.JSVariableHandler;
import opus.gwt.management.console.client.event.DeleteProjectEvent;
import opus.gwt.management.console.client.event.PanelTransitionEvent;
import opus.gwt.management.console.client.event.PanelTransitionEventHandler;
import opus.gwt.management.console.client.overlays.Application;
import opus.gwt.management.console.client.overlays.Project;
import opus.gwt.management.console.client.resources.ManagementConsoleControllerResources.ManagementConsoleControllerStyle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
private String projectName;
private boolean active;
private FormPanel deleteForm;
@UiField FlowPanel applicationsFlowPanel;
@UiField Button settingsButton;
@UiField ManagementConsoleControllerStyle manager;
@UiField Label projectLabel;
@UiField Button activeButton;
@UiField Button deleteButton;
@UiField FlexTable formContainer;
@UiField FormPanel optionsForm;
@UiField PopupPanel deletePopupPanel;
@UiField Button destroyButton;
@UiField Button noThanksButton;
@UiField FlowPanel deleteTitlePanel;
public DashboardPanel(ClientFactory clientFactory) {
initWidget(uiBinder.createAndBindUi(this));
this.eventBus = clientFactory.getEventBus();
this.clientFactory = clientFactory;
this.JSVarHandler = clientFactory.getJSVariableHandler();
this.applications = clientFactory.getApplications();
activeButton.setText("");
deleteForm = new FormPanel();
registerHandlers();
setDeletePopupPanelInitialState();
}
private void registerHandlers() { | eventBus.addHandler(PanelTransitionEvent.TYPE, |
melistik/vaadin-grid-util | vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/FieldFactory.java | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/GridCellFilter.java
// public static String STYLENAME_GRIDCELLFILTER = "gridcellfilter";
| import com.vaadin.data.Binder;
import com.vaadin.data.Converter;
import com.vaadin.shared.ui.datefield.DateResolution;
import com.vaadin.ui.DateField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.themes.ValoTheme;
import static org.vaadin.gridutil.cell.GridCellFilter.STYLENAME_GRIDCELLFILTER; | package org.vaadin.gridutil.cell;
/**
* Created by georg.hicker on 03.08.2017.
*/
public class FieldFactory {
public static <T> TextField genNumberField(Binder<T> binder, String propertyId, Converter converter, String inputPrompt) {
final TextField field = new TextField();
field.setWidth("100%"); | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/GridCellFilter.java
// public static String STYLENAME_GRIDCELLFILTER = "gridcellfilter";
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/FieldFactory.java
import com.vaadin.data.Binder;
import com.vaadin.data.Converter;
import com.vaadin.shared.ui.datefield.DateResolution;
import com.vaadin.ui.DateField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.themes.ValoTheme;
import static org.vaadin.gridutil.cell.GridCellFilter.STYLENAME_GRIDCELLFILTER;
package org.vaadin.gridutil.cell;
/**
* Created by georg.hicker on 03.08.2017.
*/
public class FieldFactory {
public static <T> TextField genNumberField(Binder<T> binder, String propertyId, Converter converter, String inputPrompt) {
final TextField field = new TextField();
field.setWidth("100%"); | field.addStyleName(STYLENAME_GRIDCELLFILTER); |
melistik/vaadin-grid-util | vaadin-grid-util/src/main/java/org/vaadin/gridutil/renderer/EditDeleteButtonValueRenderer.java | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/client/renderer/buttonvalue/VButtonValueRenderer.java
// public class VButtonValueRenderer extends ClickableRenderer<String, FlowPanel> {
//
// private static String STYLE_NAME = "v-button-value-cell";
//
// public static final int VIEW_BITM = 4;
// public static final int EDIT_BITM = 16;
// public static final int DELETE_BITM = 32;
//
// private int clickedBITM = 0;
// private final int buttonBITM;
//
// public VButtonValueRenderer(final int buttonBITM) {
// super();
// this.buttonBITM = buttonBITM;
// }
//
// private Button genButton(final int bitm) {
// Button btn = GWT.create(Button.class);
// btn.setStylePrimaryName("v-nativebutton");
// switch (bitm) {
// case VIEW_BITM:
// btn.addStyleName("v-view");
// break;
// case EDIT_BITM:
// btn.addStyleName("v-edit");
// break;
// case DELETE_BITM:
// btn.addStyleName("v-delete");
// break;
//
// }
// btn.setHTML("<span></span>");
// btn.addClickHandler(new ClickHandler() {
//
// @Override
// public void onClick(final ClickEvent event) {
// VButtonValueRenderer.this.clickedBITM = bitm;
// VButtonValueRenderer.super.onClick(event);
// }
// });
// return btn;
// }
//
// /**
// * dirty hack - before we fire onClick we keep last clicked button because of the lost of RelativeElement during converting and the
// * issue of different layouts
// */
// @Override
// public FlowPanel createWidget() {
// FlowPanel buttonBar = GWT.create(FlowPanel.class);
// buttonBar.setStylePrimaryName("v-button-bar");
//
// int buttonsAdded = 0;
// if ((this.buttonBITM & VIEW_BITM) != 0) {
// buttonBar.add(genButton(VIEW_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & EDIT_BITM) != 0) {
// buttonBar.add(genButton(EDIT_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & DELETE_BITM) != 0) {
// buttonBar.add(genButton(DELETE_BITM));
// buttonsAdded++;
// }
//
// FlowPanel panel = GWT.create(FlowPanel.class);
// panel.setStylePrimaryName(STYLE_NAME);
// if (buttonsAdded == 3) {
// panel.addStyleName("three-buttons");
// } else if (buttonsAdded == 2) {
// panel.addStyleName("two-buttons");
// } else {
// panel.addStyleName("one-button");
// }
// panel.add(buttonBar);
//
// HTML valueLabel = GWT.create(HTML.class);
// valueLabel.setStylePrimaryName("v-cell-value");
// panel.add(valueLabel);
// return panel;
// }
//
// public int getClickedBITM() {
// return this.clickedBITM;
// }
//
// @Override
// public void render(final RendererCellReference cell, final String text, final FlowPanel panel) {
// ((HTML) panel.getWidget(1)).setHTML(text);
// }
//
// }
| import com.vaadin.ui.renderers.ClickableRenderer;
import org.vaadin.gridutil.client.renderer.buttonvalue.VButtonValueRenderer; | package org.vaadin.gridutil.renderer;
/**
* Add an edit and delete buttons next to the value (value is rendered as HTML)
*
* @author Marten Prieß (http://www.rocketbase.io)
* @version 1.0
*/
public class EditDeleteButtonValueRenderer<T> extends ClickableRenderer<T, String> {
public EditDeleteButtonValueRenderer(final RendererClickListener<T> editListener, final RendererClickListener<T> deleteListener) {
super(String.class);
addClickListener(event -> { | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/client/renderer/buttonvalue/VButtonValueRenderer.java
// public class VButtonValueRenderer extends ClickableRenderer<String, FlowPanel> {
//
// private static String STYLE_NAME = "v-button-value-cell";
//
// public static final int VIEW_BITM = 4;
// public static final int EDIT_BITM = 16;
// public static final int DELETE_BITM = 32;
//
// private int clickedBITM = 0;
// private final int buttonBITM;
//
// public VButtonValueRenderer(final int buttonBITM) {
// super();
// this.buttonBITM = buttonBITM;
// }
//
// private Button genButton(final int bitm) {
// Button btn = GWT.create(Button.class);
// btn.setStylePrimaryName("v-nativebutton");
// switch (bitm) {
// case VIEW_BITM:
// btn.addStyleName("v-view");
// break;
// case EDIT_BITM:
// btn.addStyleName("v-edit");
// break;
// case DELETE_BITM:
// btn.addStyleName("v-delete");
// break;
//
// }
// btn.setHTML("<span></span>");
// btn.addClickHandler(new ClickHandler() {
//
// @Override
// public void onClick(final ClickEvent event) {
// VButtonValueRenderer.this.clickedBITM = bitm;
// VButtonValueRenderer.super.onClick(event);
// }
// });
// return btn;
// }
//
// /**
// * dirty hack - before we fire onClick we keep last clicked button because of the lost of RelativeElement during converting and the
// * issue of different layouts
// */
// @Override
// public FlowPanel createWidget() {
// FlowPanel buttonBar = GWT.create(FlowPanel.class);
// buttonBar.setStylePrimaryName("v-button-bar");
//
// int buttonsAdded = 0;
// if ((this.buttonBITM & VIEW_BITM) != 0) {
// buttonBar.add(genButton(VIEW_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & EDIT_BITM) != 0) {
// buttonBar.add(genButton(EDIT_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & DELETE_BITM) != 0) {
// buttonBar.add(genButton(DELETE_BITM));
// buttonsAdded++;
// }
//
// FlowPanel panel = GWT.create(FlowPanel.class);
// panel.setStylePrimaryName(STYLE_NAME);
// if (buttonsAdded == 3) {
// panel.addStyleName("three-buttons");
// } else if (buttonsAdded == 2) {
// panel.addStyleName("two-buttons");
// } else {
// panel.addStyleName("one-button");
// }
// panel.add(buttonBar);
//
// HTML valueLabel = GWT.create(HTML.class);
// valueLabel.setStylePrimaryName("v-cell-value");
// panel.add(valueLabel);
// return panel;
// }
//
// public int getClickedBITM() {
// return this.clickedBITM;
// }
//
// @Override
// public void render(final RendererCellReference cell, final String text, final FlowPanel panel) {
// ((HTML) panel.getWidget(1)).setHTML(text);
// }
//
// }
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/renderer/EditDeleteButtonValueRenderer.java
import com.vaadin.ui.renderers.ClickableRenderer;
import org.vaadin.gridutil.client.renderer.buttonvalue.VButtonValueRenderer;
package org.vaadin.gridutil.renderer;
/**
* Add an edit and delete buttons next to the value (value is rendered as HTML)
*
* @author Marten Prieß (http://www.rocketbase.io)
* @version 1.0
*/
public class EditDeleteButtonValueRenderer<T> extends ClickableRenderer<T, String> {
public EditDeleteButtonValueRenderer(final RendererClickListener<T> editListener, final RendererClickListener<T> deleteListener) {
super(String.class);
addClickListener(event -> { | if (event.getRelativeX() == VButtonValueRenderer.EDIT_BITM) { |
melistik/vaadin-grid-util | vaadin-grid-util/src/main/java/org/vaadin/gridutil/renderer/ViewEditButtonValueRenderer.java | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/client/renderer/buttonvalue/VButtonValueRenderer.java
// public class VButtonValueRenderer extends ClickableRenderer<String, FlowPanel> {
//
// private static String STYLE_NAME = "v-button-value-cell";
//
// public static final int VIEW_BITM = 4;
// public static final int EDIT_BITM = 16;
// public static final int DELETE_BITM = 32;
//
// private int clickedBITM = 0;
// private final int buttonBITM;
//
// public VButtonValueRenderer(final int buttonBITM) {
// super();
// this.buttonBITM = buttonBITM;
// }
//
// private Button genButton(final int bitm) {
// Button btn = GWT.create(Button.class);
// btn.setStylePrimaryName("v-nativebutton");
// switch (bitm) {
// case VIEW_BITM:
// btn.addStyleName("v-view");
// break;
// case EDIT_BITM:
// btn.addStyleName("v-edit");
// break;
// case DELETE_BITM:
// btn.addStyleName("v-delete");
// break;
//
// }
// btn.setHTML("<span></span>");
// btn.addClickHandler(new ClickHandler() {
//
// @Override
// public void onClick(final ClickEvent event) {
// VButtonValueRenderer.this.clickedBITM = bitm;
// VButtonValueRenderer.super.onClick(event);
// }
// });
// return btn;
// }
//
// /**
// * dirty hack - before we fire onClick we keep last clicked button because of the lost of RelativeElement during converting and the
// * issue of different layouts
// */
// @Override
// public FlowPanel createWidget() {
// FlowPanel buttonBar = GWT.create(FlowPanel.class);
// buttonBar.setStylePrimaryName("v-button-bar");
//
// int buttonsAdded = 0;
// if ((this.buttonBITM & VIEW_BITM) != 0) {
// buttonBar.add(genButton(VIEW_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & EDIT_BITM) != 0) {
// buttonBar.add(genButton(EDIT_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & DELETE_BITM) != 0) {
// buttonBar.add(genButton(DELETE_BITM));
// buttonsAdded++;
// }
//
// FlowPanel panel = GWT.create(FlowPanel.class);
// panel.setStylePrimaryName(STYLE_NAME);
// if (buttonsAdded == 3) {
// panel.addStyleName("three-buttons");
// } else if (buttonsAdded == 2) {
// panel.addStyleName("two-buttons");
// } else {
// panel.addStyleName("one-button");
// }
// panel.add(buttonBar);
//
// HTML valueLabel = GWT.create(HTML.class);
// valueLabel.setStylePrimaryName("v-cell-value");
// panel.add(valueLabel);
// return panel;
// }
//
// public int getClickedBITM() {
// return this.clickedBITM;
// }
//
// @Override
// public void render(final RendererCellReference cell, final String text, final FlowPanel panel) {
// ((HTML) panel.getWidget(1)).setHTML(text);
// }
//
// }
| import com.vaadin.ui.renderers.ClickableRenderer;
import org.vaadin.gridutil.client.renderer.buttonvalue.VButtonValueRenderer; | package org.vaadin.gridutil.renderer;
/**
* Add view, edit and delete buttons next to the value (value is rendered as HTML)
*
* @author Marten Prieß (http://www.rocketbase.io)
* @version 1.0
*/
public class ViewEditButtonValueRenderer<T> extends ClickableRenderer<T, String> {
public ViewEditButtonValueRenderer(final RendererClickListener<T> viewListener, final RendererClickListener<T> editListener) {
super(String.class);
addClickListener(event -> { | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/client/renderer/buttonvalue/VButtonValueRenderer.java
// public class VButtonValueRenderer extends ClickableRenderer<String, FlowPanel> {
//
// private static String STYLE_NAME = "v-button-value-cell";
//
// public static final int VIEW_BITM = 4;
// public static final int EDIT_BITM = 16;
// public static final int DELETE_BITM = 32;
//
// private int clickedBITM = 0;
// private final int buttonBITM;
//
// public VButtonValueRenderer(final int buttonBITM) {
// super();
// this.buttonBITM = buttonBITM;
// }
//
// private Button genButton(final int bitm) {
// Button btn = GWT.create(Button.class);
// btn.setStylePrimaryName("v-nativebutton");
// switch (bitm) {
// case VIEW_BITM:
// btn.addStyleName("v-view");
// break;
// case EDIT_BITM:
// btn.addStyleName("v-edit");
// break;
// case DELETE_BITM:
// btn.addStyleName("v-delete");
// break;
//
// }
// btn.setHTML("<span></span>");
// btn.addClickHandler(new ClickHandler() {
//
// @Override
// public void onClick(final ClickEvent event) {
// VButtonValueRenderer.this.clickedBITM = bitm;
// VButtonValueRenderer.super.onClick(event);
// }
// });
// return btn;
// }
//
// /**
// * dirty hack - before we fire onClick we keep last clicked button because of the lost of RelativeElement during converting and the
// * issue of different layouts
// */
// @Override
// public FlowPanel createWidget() {
// FlowPanel buttonBar = GWT.create(FlowPanel.class);
// buttonBar.setStylePrimaryName("v-button-bar");
//
// int buttonsAdded = 0;
// if ((this.buttonBITM & VIEW_BITM) != 0) {
// buttonBar.add(genButton(VIEW_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & EDIT_BITM) != 0) {
// buttonBar.add(genButton(EDIT_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & DELETE_BITM) != 0) {
// buttonBar.add(genButton(DELETE_BITM));
// buttonsAdded++;
// }
//
// FlowPanel panel = GWT.create(FlowPanel.class);
// panel.setStylePrimaryName(STYLE_NAME);
// if (buttonsAdded == 3) {
// panel.addStyleName("three-buttons");
// } else if (buttonsAdded == 2) {
// panel.addStyleName("two-buttons");
// } else {
// panel.addStyleName("one-button");
// }
// panel.add(buttonBar);
//
// HTML valueLabel = GWT.create(HTML.class);
// valueLabel.setStylePrimaryName("v-cell-value");
// panel.add(valueLabel);
// return panel;
// }
//
// public int getClickedBITM() {
// return this.clickedBITM;
// }
//
// @Override
// public void render(final RendererCellReference cell, final String text, final FlowPanel panel) {
// ((HTML) panel.getWidget(1)).setHTML(text);
// }
//
// }
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/renderer/ViewEditButtonValueRenderer.java
import com.vaadin.ui.renderers.ClickableRenderer;
import org.vaadin.gridutil.client.renderer.buttonvalue.VButtonValueRenderer;
package org.vaadin.gridutil.renderer;
/**
* Add view, edit and delete buttons next to the value (value is rendered as HTML)
*
* @author Marten Prieß (http://www.rocketbase.io)
* @version 1.0
*/
public class ViewEditButtonValueRenderer<T> extends ClickableRenderer<T, String> {
public ViewEditButtonValueRenderer(final RendererClickListener<T> viewListener, final RendererClickListener<T> editListener) {
super(String.class);
addClickListener(event -> { | if (event.getRelativeX() == VButtonValueRenderer.VIEW_BITM) { |
melistik/vaadin-grid-util | vaadin-grid-util/src/main/java/org/vaadin/gridutil/renderer/IndicatorRenderer.java | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/client/renderer/indicator/IndicatorRendererState.java
// public class IndicatorRendererState extends AbstractRendererState {
//
// public double startGreen = 1.3;
//
// public double startRed = 0.9;
// }
| import com.vaadin.shared.ui.grid.renderers.AbstractRendererState;
import com.vaadin.ui.renderers.AbstractRenderer;
import org.vaadin.gridutil.client.renderer.indicator.IndicatorRendererState; | package org.vaadin.gridutil.renderer;
public class IndicatorRenderer<T> extends AbstractRenderer<T, Double> {
public IndicatorRenderer(double startGreen, double startRed) {
super(Double.class);
getState().startGreen = startGreen;
getState().startRed = startRed;
}
@Override | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/client/renderer/indicator/IndicatorRendererState.java
// public class IndicatorRendererState extends AbstractRendererState {
//
// public double startGreen = 1.3;
//
// public double startRed = 0.9;
// }
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/renderer/IndicatorRenderer.java
import com.vaadin.shared.ui.grid.renderers.AbstractRendererState;
import com.vaadin.ui.renderers.AbstractRenderer;
import org.vaadin.gridutil.client.renderer.indicator.IndicatorRendererState;
package org.vaadin.gridutil.renderer;
public class IndicatorRenderer<T> extends AbstractRenderer<T, Double> {
public IndicatorRenderer(double startGreen, double startRed) {
super(Double.class);
getState().startGreen = startGreen;
getState().startRed = startRed;
}
@Override | protected IndicatorRendererState getState() { |
melistik/vaadin-grid-util | vaadin-grid-util/src/main/java/org/vaadin/gridutil/renderer/ViewDeleteButtonValueRenderer.java | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/client/renderer/buttonvalue/VButtonValueRenderer.java
// public class VButtonValueRenderer extends ClickableRenderer<String, FlowPanel> {
//
// private static String STYLE_NAME = "v-button-value-cell";
//
// public static final int VIEW_BITM = 4;
// public static final int EDIT_BITM = 16;
// public static final int DELETE_BITM = 32;
//
// private int clickedBITM = 0;
// private final int buttonBITM;
//
// public VButtonValueRenderer(final int buttonBITM) {
// super();
// this.buttonBITM = buttonBITM;
// }
//
// private Button genButton(final int bitm) {
// Button btn = GWT.create(Button.class);
// btn.setStylePrimaryName("v-nativebutton");
// switch (bitm) {
// case VIEW_BITM:
// btn.addStyleName("v-view");
// break;
// case EDIT_BITM:
// btn.addStyleName("v-edit");
// break;
// case DELETE_BITM:
// btn.addStyleName("v-delete");
// break;
//
// }
// btn.setHTML("<span></span>");
// btn.addClickHandler(new ClickHandler() {
//
// @Override
// public void onClick(final ClickEvent event) {
// VButtonValueRenderer.this.clickedBITM = bitm;
// VButtonValueRenderer.super.onClick(event);
// }
// });
// return btn;
// }
//
// /**
// * dirty hack - before we fire onClick we keep last clicked button because of the lost of RelativeElement during converting and the
// * issue of different layouts
// */
// @Override
// public FlowPanel createWidget() {
// FlowPanel buttonBar = GWT.create(FlowPanel.class);
// buttonBar.setStylePrimaryName("v-button-bar");
//
// int buttonsAdded = 0;
// if ((this.buttonBITM & VIEW_BITM) != 0) {
// buttonBar.add(genButton(VIEW_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & EDIT_BITM) != 0) {
// buttonBar.add(genButton(EDIT_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & DELETE_BITM) != 0) {
// buttonBar.add(genButton(DELETE_BITM));
// buttonsAdded++;
// }
//
// FlowPanel panel = GWT.create(FlowPanel.class);
// panel.setStylePrimaryName(STYLE_NAME);
// if (buttonsAdded == 3) {
// panel.addStyleName("three-buttons");
// } else if (buttonsAdded == 2) {
// panel.addStyleName("two-buttons");
// } else {
// panel.addStyleName("one-button");
// }
// panel.add(buttonBar);
//
// HTML valueLabel = GWT.create(HTML.class);
// valueLabel.setStylePrimaryName("v-cell-value");
// panel.add(valueLabel);
// return panel;
// }
//
// public int getClickedBITM() {
// return this.clickedBITM;
// }
//
// @Override
// public void render(final RendererCellReference cell, final String text, final FlowPanel panel) {
// ((HTML) panel.getWidget(1)).setHTML(text);
// }
//
// }
| import com.vaadin.ui.renderers.ClickableRenderer;
import org.vaadin.gridutil.client.renderer.buttonvalue.VButtonValueRenderer; | package org.vaadin.gridutil.renderer;
/**
* Add view, edit and delete buttons next to the value (value is rendered as HTML)
*
* @author Marten Prieß (http://www.rocketbase.io)
* @version 1.0
*/
public class ViewDeleteButtonValueRenderer<T> extends ClickableRenderer<T, String> {
public ViewDeleteButtonValueRenderer(final RendererClickListener<T> viewListener, final RendererClickListener<T> deleteListener) {
super(String.class);
addClickListener(event -> { | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/client/renderer/buttonvalue/VButtonValueRenderer.java
// public class VButtonValueRenderer extends ClickableRenderer<String, FlowPanel> {
//
// private static String STYLE_NAME = "v-button-value-cell";
//
// public static final int VIEW_BITM = 4;
// public static final int EDIT_BITM = 16;
// public static final int DELETE_BITM = 32;
//
// private int clickedBITM = 0;
// private final int buttonBITM;
//
// public VButtonValueRenderer(final int buttonBITM) {
// super();
// this.buttonBITM = buttonBITM;
// }
//
// private Button genButton(final int bitm) {
// Button btn = GWT.create(Button.class);
// btn.setStylePrimaryName("v-nativebutton");
// switch (bitm) {
// case VIEW_BITM:
// btn.addStyleName("v-view");
// break;
// case EDIT_BITM:
// btn.addStyleName("v-edit");
// break;
// case DELETE_BITM:
// btn.addStyleName("v-delete");
// break;
//
// }
// btn.setHTML("<span></span>");
// btn.addClickHandler(new ClickHandler() {
//
// @Override
// public void onClick(final ClickEvent event) {
// VButtonValueRenderer.this.clickedBITM = bitm;
// VButtonValueRenderer.super.onClick(event);
// }
// });
// return btn;
// }
//
// /**
// * dirty hack - before we fire onClick we keep last clicked button because of the lost of RelativeElement during converting and the
// * issue of different layouts
// */
// @Override
// public FlowPanel createWidget() {
// FlowPanel buttonBar = GWT.create(FlowPanel.class);
// buttonBar.setStylePrimaryName("v-button-bar");
//
// int buttonsAdded = 0;
// if ((this.buttonBITM & VIEW_BITM) != 0) {
// buttonBar.add(genButton(VIEW_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & EDIT_BITM) != 0) {
// buttonBar.add(genButton(EDIT_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & DELETE_BITM) != 0) {
// buttonBar.add(genButton(DELETE_BITM));
// buttonsAdded++;
// }
//
// FlowPanel panel = GWT.create(FlowPanel.class);
// panel.setStylePrimaryName(STYLE_NAME);
// if (buttonsAdded == 3) {
// panel.addStyleName("three-buttons");
// } else if (buttonsAdded == 2) {
// panel.addStyleName("two-buttons");
// } else {
// panel.addStyleName("one-button");
// }
// panel.add(buttonBar);
//
// HTML valueLabel = GWT.create(HTML.class);
// valueLabel.setStylePrimaryName("v-cell-value");
// panel.add(valueLabel);
// return panel;
// }
//
// public int getClickedBITM() {
// return this.clickedBITM;
// }
//
// @Override
// public void render(final RendererCellReference cell, final String text, final FlowPanel panel) {
// ((HTML) panel.getWidget(1)).setHTML(text);
// }
//
// }
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/renderer/ViewDeleteButtonValueRenderer.java
import com.vaadin.ui.renderers.ClickableRenderer;
import org.vaadin.gridutil.client.renderer.buttonvalue.VButtonValueRenderer;
package org.vaadin.gridutil.renderer;
/**
* Add view, edit and delete buttons next to the value (value is rendered as HTML)
*
* @author Marten Prieß (http://www.rocketbase.io)
* @version 1.0
*/
public class ViewDeleteButtonValueRenderer<T> extends ClickableRenderer<T, String> {
public ViewDeleteButtonValueRenderer(final RendererClickListener<T> viewListener, final RendererClickListener<T> deleteListener) {
super(String.class);
addClickListener(event -> { | if (event.getRelativeX() == VButtonValueRenderer.VIEW_BITM) { |
melistik/vaadin-grid-util | vaadin-grid-util/src/main/java/org/vaadin/gridutil/renderer/ViewEditDeleteButtonValueRenderer.java | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/client/renderer/buttonvalue/VButtonValueRenderer.java
// public class VButtonValueRenderer extends ClickableRenderer<String, FlowPanel> {
//
// private static String STYLE_NAME = "v-button-value-cell";
//
// public static final int VIEW_BITM = 4;
// public static final int EDIT_BITM = 16;
// public static final int DELETE_BITM = 32;
//
// private int clickedBITM = 0;
// private final int buttonBITM;
//
// public VButtonValueRenderer(final int buttonBITM) {
// super();
// this.buttonBITM = buttonBITM;
// }
//
// private Button genButton(final int bitm) {
// Button btn = GWT.create(Button.class);
// btn.setStylePrimaryName("v-nativebutton");
// switch (bitm) {
// case VIEW_BITM:
// btn.addStyleName("v-view");
// break;
// case EDIT_BITM:
// btn.addStyleName("v-edit");
// break;
// case DELETE_BITM:
// btn.addStyleName("v-delete");
// break;
//
// }
// btn.setHTML("<span></span>");
// btn.addClickHandler(new ClickHandler() {
//
// @Override
// public void onClick(final ClickEvent event) {
// VButtonValueRenderer.this.clickedBITM = bitm;
// VButtonValueRenderer.super.onClick(event);
// }
// });
// return btn;
// }
//
// /**
// * dirty hack - before we fire onClick we keep last clicked button because of the lost of RelativeElement during converting and the
// * issue of different layouts
// */
// @Override
// public FlowPanel createWidget() {
// FlowPanel buttonBar = GWT.create(FlowPanel.class);
// buttonBar.setStylePrimaryName("v-button-bar");
//
// int buttonsAdded = 0;
// if ((this.buttonBITM & VIEW_BITM) != 0) {
// buttonBar.add(genButton(VIEW_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & EDIT_BITM) != 0) {
// buttonBar.add(genButton(EDIT_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & DELETE_BITM) != 0) {
// buttonBar.add(genButton(DELETE_BITM));
// buttonsAdded++;
// }
//
// FlowPanel panel = GWT.create(FlowPanel.class);
// panel.setStylePrimaryName(STYLE_NAME);
// if (buttonsAdded == 3) {
// panel.addStyleName("three-buttons");
// } else if (buttonsAdded == 2) {
// panel.addStyleName("two-buttons");
// } else {
// panel.addStyleName("one-button");
// }
// panel.add(buttonBar);
//
// HTML valueLabel = GWT.create(HTML.class);
// valueLabel.setStylePrimaryName("v-cell-value");
// panel.add(valueLabel);
// return panel;
// }
//
// public int getClickedBITM() {
// return this.clickedBITM;
// }
//
// @Override
// public void render(final RendererCellReference cell, final String text, final FlowPanel panel) {
// ((HTML) panel.getWidget(1)).setHTML(text);
// }
//
// }
| import com.vaadin.ui.renderers.ClickableRenderer;
import org.vaadin.gridutil.client.renderer.buttonvalue.VButtonValueRenderer; | package org.vaadin.gridutil.renderer;
/**
* Add view, edit and delete buttons next to the value (value is rendered as HTML)
*
* @author Marten Prieß (http://www.rocketbase.io)
* @version 1.0
*/
public class ViewEditDeleteButtonValueRenderer<T> extends ClickableRenderer<T, String> {
public ViewEditDeleteButtonValueRenderer(final RendererClickListener<T> viewListener, final RendererClickListener<T> editListener, final RendererClickListener<T> deleteListener) {
super(String.class);
addClickListener(event -> { | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/client/renderer/buttonvalue/VButtonValueRenderer.java
// public class VButtonValueRenderer extends ClickableRenderer<String, FlowPanel> {
//
// private static String STYLE_NAME = "v-button-value-cell";
//
// public static final int VIEW_BITM = 4;
// public static final int EDIT_BITM = 16;
// public static final int DELETE_BITM = 32;
//
// private int clickedBITM = 0;
// private final int buttonBITM;
//
// public VButtonValueRenderer(final int buttonBITM) {
// super();
// this.buttonBITM = buttonBITM;
// }
//
// private Button genButton(final int bitm) {
// Button btn = GWT.create(Button.class);
// btn.setStylePrimaryName("v-nativebutton");
// switch (bitm) {
// case VIEW_BITM:
// btn.addStyleName("v-view");
// break;
// case EDIT_BITM:
// btn.addStyleName("v-edit");
// break;
// case DELETE_BITM:
// btn.addStyleName("v-delete");
// break;
//
// }
// btn.setHTML("<span></span>");
// btn.addClickHandler(new ClickHandler() {
//
// @Override
// public void onClick(final ClickEvent event) {
// VButtonValueRenderer.this.clickedBITM = bitm;
// VButtonValueRenderer.super.onClick(event);
// }
// });
// return btn;
// }
//
// /**
// * dirty hack - before we fire onClick we keep last clicked button because of the lost of RelativeElement during converting and the
// * issue of different layouts
// */
// @Override
// public FlowPanel createWidget() {
// FlowPanel buttonBar = GWT.create(FlowPanel.class);
// buttonBar.setStylePrimaryName("v-button-bar");
//
// int buttonsAdded = 0;
// if ((this.buttonBITM & VIEW_BITM) != 0) {
// buttonBar.add(genButton(VIEW_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & EDIT_BITM) != 0) {
// buttonBar.add(genButton(EDIT_BITM));
// buttonsAdded++;
// }
// if ((this.buttonBITM & DELETE_BITM) != 0) {
// buttonBar.add(genButton(DELETE_BITM));
// buttonsAdded++;
// }
//
// FlowPanel panel = GWT.create(FlowPanel.class);
// panel.setStylePrimaryName(STYLE_NAME);
// if (buttonsAdded == 3) {
// panel.addStyleName("three-buttons");
// } else if (buttonsAdded == 2) {
// panel.addStyleName("two-buttons");
// } else {
// panel.addStyleName("one-button");
// }
// panel.add(buttonBar);
//
// HTML valueLabel = GWT.create(HTML.class);
// valueLabel.setStylePrimaryName("v-cell-value");
// panel.add(valueLabel);
// return panel;
// }
//
// public int getClickedBITM() {
// return this.clickedBITM;
// }
//
// @Override
// public void render(final RendererCellReference cell, final String text, final FlowPanel panel) {
// ((HTML) panel.getWidget(1)).setHTML(text);
// }
//
// }
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/renderer/ViewEditDeleteButtonValueRenderer.java
import com.vaadin.ui.renderers.ClickableRenderer;
import org.vaadin.gridutil.client.renderer.buttonvalue.VButtonValueRenderer;
package org.vaadin.gridutil.renderer;
/**
* Add view, edit and delete buttons next to the value (value is rendered as HTML)
*
* @author Marten Prieß (http://www.rocketbase.io)
* @version 1.0
*/
public class ViewEditDeleteButtonValueRenderer<T> extends ClickableRenderer<T, String> {
public ViewEditDeleteButtonValueRenderer(final RendererClickListener<T> viewListener, final RendererClickListener<T> editListener, final RendererClickListener<T> deleteListener) {
super(String.class);
addClickListener(event -> { | if (event.getRelativeX() == VButtonValueRenderer.VIEW_BITM) { |
melistik/vaadin-grid-util | vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/GridCellFilter.java | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/BetweenFilter.java
// public class BetweenFilter<T extends Comparable<? super T>> implements SerializablePredicate<Comparable<T>> {
// private final T startValue;
// private final T endValue;
//
// public BetweenFilter(T startValue, T endValue) {
// this.startValue = startValue;
// this.endValue = endValue;
// }
//
// @Override
// public boolean test(Comparable<T> value) {
// if (value == null) {
// return startValue == null && endValue == null;
// }
// return isAfterStart(value) && isBeforeEnd(value);
// }
//
// private boolean isAfterStart(final Comparable<T> value) {
// return startValue == null || value.compareTo(startValue) >= 0;
// }
//
// private boolean isBeforeEnd(final Comparable<T> value) {
// return endValue == null || value.compareTo(endValue) <= 0;
// }
//
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/EqualFilter.java
// public class EqualFilter<T> implements SerializablePredicate<T> {
//
// final T toCompare;
//
// public EqualFilter(T toCompare) {
// this.toCompare = toCompare;
// }
//
// @Override
// public boolean test(T value) {
// if (value == null && toCompare == null) {
// return true;
// }
// if (value == null || toCompare == null) {
// return false;
// }
// return value.equals(toCompare);
// }
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/SimpleStringFilter.java
// public class SimpleStringFilter implements SerializablePredicate<String> {
//
// final String filterString;
// final boolean ignoreCase;
// final boolean onlyMatchPrefix;
//
// public SimpleStringFilter(String filterString, boolean ignoreCase, boolean onlyMatchPrefix) {
// this.ignoreCase = ignoreCase;
// // ignoreCase has to be applied to filterstring too, otherwise uppercase input won't work
// this.filterString = this.ignoreCase ? filterString.toLowerCase() : filterString;
// this.onlyMatchPrefix = onlyMatchPrefix;
// }
//
// @Override
// public boolean test(String value) {
// if (filterString == null || value == null) {
// return false;
// }
// final String v = ignoreCase ? value.toString()
// .toLowerCase()
// : value.toString();
//
// if (onlyMatchPrefix) {
// if (!v.startsWith(filterString)) {
// return false;
// }
// } else {
// if (!v.contains(filterString)) {
// return false;
// }
// }
// return true;
// }
// }
| import com.vaadin.data.BeanPropertySet;
import com.vaadin.data.PropertySet;
import com.vaadin.data.ValueProvider;
import com.vaadin.data.converter.LocalDateToDateConverter;
import com.vaadin.data.provider.InMemoryDataProviderHelpers;
import com.vaadin.data.provider.ListDataProvider;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.server.FontIcon;
import com.vaadin.server.SerializablePredicate;
import com.vaadin.server.Sizeable.Unit;
import com.vaadin.shared.ui.ValueChangeMode;
import com.vaadin.ui.*;
import com.vaadin.ui.components.grid.HeaderRow;
import com.vaadin.ui.themes.ValoTheme;
import org.vaadin.gridutil.cell.filter.BetweenFilter;
import org.vaadin.gridutil.cell.filter.EqualFilter;
import org.vaadin.gridutil.cell.filter.SimpleStringFilter;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.Map.Entry; | * @param columnId id of property
* @param ignoreCase property of SimpleStringFilter
* @param onlyMatchPrefix property of SimpleStringFilter
* @return CellFilterComponent that contains TextField
*/
public CellFilterComponent<TextField> setTextFilter(String columnId, boolean ignoreCase, boolean onlyMatchPrefix) {
return setTextFilter(columnId, ignoreCase, onlyMatchPrefix, null);
}
/**
* assign a <b>SimpleStringFilter</b> to grid for given columnId<br>
* could also be used for NumberField when you would like to do filter by startWith for example
*
* @param columnId id of property
* @param ignoreCase property of SimpleStringFilter
* @param onlyMatchPrefix property of SimpleStringFilter
* @param inputPrompt hint for user
* @return CellFilterComponent that contains TextField
*/
public CellFilterComponent<TextField> setTextFilter(String columnId, boolean ignoreCase, boolean onlyMatchPrefix, String inputPrompt) {
CellFilterComponent<TextField> filter = new CellFilterComponent<TextField>() {
TextField textField = new TextField();
String currentValue = "";
public void triggerUpdate() {
if (currentValue == null || currentValue.isEmpty()) {
removeFilter(columnId);
} else { | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/BetweenFilter.java
// public class BetweenFilter<T extends Comparable<? super T>> implements SerializablePredicate<Comparable<T>> {
// private final T startValue;
// private final T endValue;
//
// public BetweenFilter(T startValue, T endValue) {
// this.startValue = startValue;
// this.endValue = endValue;
// }
//
// @Override
// public boolean test(Comparable<T> value) {
// if (value == null) {
// return startValue == null && endValue == null;
// }
// return isAfterStart(value) && isBeforeEnd(value);
// }
//
// private boolean isAfterStart(final Comparable<T> value) {
// return startValue == null || value.compareTo(startValue) >= 0;
// }
//
// private boolean isBeforeEnd(final Comparable<T> value) {
// return endValue == null || value.compareTo(endValue) <= 0;
// }
//
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/EqualFilter.java
// public class EqualFilter<T> implements SerializablePredicate<T> {
//
// final T toCompare;
//
// public EqualFilter(T toCompare) {
// this.toCompare = toCompare;
// }
//
// @Override
// public boolean test(T value) {
// if (value == null && toCompare == null) {
// return true;
// }
// if (value == null || toCompare == null) {
// return false;
// }
// return value.equals(toCompare);
// }
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/SimpleStringFilter.java
// public class SimpleStringFilter implements SerializablePredicate<String> {
//
// final String filterString;
// final boolean ignoreCase;
// final boolean onlyMatchPrefix;
//
// public SimpleStringFilter(String filterString, boolean ignoreCase, boolean onlyMatchPrefix) {
// this.ignoreCase = ignoreCase;
// // ignoreCase has to be applied to filterstring too, otherwise uppercase input won't work
// this.filterString = this.ignoreCase ? filterString.toLowerCase() : filterString;
// this.onlyMatchPrefix = onlyMatchPrefix;
// }
//
// @Override
// public boolean test(String value) {
// if (filterString == null || value == null) {
// return false;
// }
// final String v = ignoreCase ? value.toString()
// .toLowerCase()
// : value.toString();
//
// if (onlyMatchPrefix) {
// if (!v.startsWith(filterString)) {
// return false;
// }
// } else {
// if (!v.contains(filterString)) {
// return false;
// }
// }
// return true;
// }
// }
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/GridCellFilter.java
import com.vaadin.data.BeanPropertySet;
import com.vaadin.data.PropertySet;
import com.vaadin.data.ValueProvider;
import com.vaadin.data.converter.LocalDateToDateConverter;
import com.vaadin.data.provider.InMemoryDataProviderHelpers;
import com.vaadin.data.provider.ListDataProvider;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.server.FontIcon;
import com.vaadin.server.SerializablePredicate;
import com.vaadin.server.Sizeable.Unit;
import com.vaadin.shared.ui.ValueChangeMode;
import com.vaadin.ui.*;
import com.vaadin.ui.components.grid.HeaderRow;
import com.vaadin.ui.themes.ValoTheme;
import org.vaadin.gridutil.cell.filter.BetweenFilter;
import org.vaadin.gridutil.cell.filter.EqualFilter;
import org.vaadin.gridutil.cell.filter.SimpleStringFilter;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.Map.Entry;
* @param columnId id of property
* @param ignoreCase property of SimpleStringFilter
* @param onlyMatchPrefix property of SimpleStringFilter
* @return CellFilterComponent that contains TextField
*/
public CellFilterComponent<TextField> setTextFilter(String columnId, boolean ignoreCase, boolean onlyMatchPrefix) {
return setTextFilter(columnId, ignoreCase, onlyMatchPrefix, null);
}
/**
* assign a <b>SimpleStringFilter</b> to grid for given columnId<br>
* could also be used for NumberField when you would like to do filter by startWith for example
*
* @param columnId id of property
* @param ignoreCase property of SimpleStringFilter
* @param onlyMatchPrefix property of SimpleStringFilter
* @param inputPrompt hint for user
* @return CellFilterComponent that contains TextField
*/
public CellFilterComponent<TextField> setTextFilter(String columnId, boolean ignoreCase, boolean onlyMatchPrefix, String inputPrompt) {
CellFilterComponent<TextField> filter = new CellFilterComponent<TextField>() {
TextField textField = new TextField();
String currentValue = "";
public void triggerUpdate() {
if (currentValue == null || currentValue.isEmpty()) {
removeFilter(columnId);
} else { | replaceFilter(new SimpleStringFilter(currentValue, ignoreCase, onlyMatchPrefix), columnId); |
melistik/vaadin-grid-util | vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/GridCellFilter.java | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/BetweenFilter.java
// public class BetweenFilter<T extends Comparable<? super T>> implements SerializablePredicate<Comparable<T>> {
// private final T startValue;
// private final T endValue;
//
// public BetweenFilter(T startValue, T endValue) {
// this.startValue = startValue;
// this.endValue = endValue;
// }
//
// @Override
// public boolean test(Comparable<T> value) {
// if (value == null) {
// return startValue == null && endValue == null;
// }
// return isAfterStart(value) && isBeforeEnd(value);
// }
//
// private boolean isAfterStart(final Comparable<T> value) {
// return startValue == null || value.compareTo(startValue) >= 0;
// }
//
// private boolean isBeforeEnd(final Comparable<T> value) {
// return endValue == null || value.compareTo(endValue) <= 0;
// }
//
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/EqualFilter.java
// public class EqualFilter<T> implements SerializablePredicate<T> {
//
// final T toCompare;
//
// public EqualFilter(T toCompare) {
// this.toCompare = toCompare;
// }
//
// @Override
// public boolean test(T value) {
// if (value == null && toCompare == null) {
// return true;
// }
// if (value == null || toCompare == null) {
// return false;
// }
// return value.equals(toCompare);
// }
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/SimpleStringFilter.java
// public class SimpleStringFilter implements SerializablePredicate<String> {
//
// final String filterString;
// final boolean ignoreCase;
// final boolean onlyMatchPrefix;
//
// public SimpleStringFilter(String filterString, boolean ignoreCase, boolean onlyMatchPrefix) {
// this.ignoreCase = ignoreCase;
// // ignoreCase has to be applied to filterstring too, otherwise uppercase input won't work
// this.filterString = this.ignoreCase ? filterString.toLowerCase() : filterString;
// this.onlyMatchPrefix = onlyMatchPrefix;
// }
//
// @Override
// public boolean test(String value) {
// if (filterString == null || value == null) {
// return false;
// }
// final String v = ignoreCase ? value.toString()
// .toLowerCase()
// : value.toString();
//
// if (onlyMatchPrefix) {
// if (!v.startsWith(filterString)) {
// return false;
// }
// } else {
// if (!v.contains(filterString)) {
// return false;
// }
// }
// return true;
// }
// }
| import com.vaadin.data.BeanPropertySet;
import com.vaadin.data.PropertySet;
import com.vaadin.data.ValueProvider;
import com.vaadin.data.converter.LocalDateToDateConverter;
import com.vaadin.data.provider.InMemoryDataProviderHelpers;
import com.vaadin.data.provider.ListDataProvider;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.server.FontIcon;
import com.vaadin.server.SerializablePredicate;
import com.vaadin.server.Sizeable.Unit;
import com.vaadin.shared.ui.ValueChangeMode;
import com.vaadin.ui.*;
import com.vaadin.ui.components.grid.HeaderRow;
import com.vaadin.ui.themes.ValoTheme;
import org.vaadin.gridutil.cell.filter.BetweenFilter;
import org.vaadin.gridutil.cell.filter.EqualFilter;
import org.vaadin.gridutil.cell.filter.SimpleStringFilter;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.Map.Entry; | currentValue = textField.getValue();
triggerUpdate();
});
return textField;
}
@Override
public void clearFilter() {
textField.clear();
}
};
handleFilterRow(columnId, filter);
return filter;
}
/**
* assign a <b>EqualFilter</b> to grid for given columnId
*
* @param columnId id of property
* @param beanType class of selection
* @param beans selection for ComboBox
* @return CellFilterComponent that contains ComboBox
*/
public <B> CellFilterComponent<ComboBox<B>> setComboBoxFilter(String columnId, Class<B> beanType, List<B> beans) {
CellFilterComponent<ComboBox<B>> filter = new CellFilterComponent<ComboBox<B>>() {
ComboBox<B> comboBox = new ComboBox();
public void triggerUpdate() {
if (comboBox.getValue() != null) { | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/BetweenFilter.java
// public class BetweenFilter<T extends Comparable<? super T>> implements SerializablePredicate<Comparable<T>> {
// private final T startValue;
// private final T endValue;
//
// public BetweenFilter(T startValue, T endValue) {
// this.startValue = startValue;
// this.endValue = endValue;
// }
//
// @Override
// public boolean test(Comparable<T> value) {
// if (value == null) {
// return startValue == null && endValue == null;
// }
// return isAfterStart(value) && isBeforeEnd(value);
// }
//
// private boolean isAfterStart(final Comparable<T> value) {
// return startValue == null || value.compareTo(startValue) >= 0;
// }
//
// private boolean isBeforeEnd(final Comparable<T> value) {
// return endValue == null || value.compareTo(endValue) <= 0;
// }
//
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/EqualFilter.java
// public class EqualFilter<T> implements SerializablePredicate<T> {
//
// final T toCompare;
//
// public EqualFilter(T toCompare) {
// this.toCompare = toCompare;
// }
//
// @Override
// public boolean test(T value) {
// if (value == null && toCompare == null) {
// return true;
// }
// if (value == null || toCompare == null) {
// return false;
// }
// return value.equals(toCompare);
// }
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/SimpleStringFilter.java
// public class SimpleStringFilter implements SerializablePredicate<String> {
//
// final String filterString;
// final boolean ignoreCase;
// final boolean onlyMatchPrefix;
//
// public SimpleStringFilter(String filterString, boolean ignoreCase, boolean onlyMatchPrefix) {
// this.ignoreCase = ignoreCase;
// // ignoreCase has to be applied to filterstring too, otherwise uppercase input won't work
// this.filterString = this.ignoreCase ? filterString.toLowerCase() : filterString;
// this.onlyMatchPrefix = onlyMatchPrefix;
// }
//
// @Override
// public boolean test(String value) {
// if (filterString == null || value == null) {
// return false;
// }
// final String v = ignoreCase ? value.toString()
// .toLowerCase()
// : value.toString();
//
// if (onlyMatchPrefix) {
// if (!v.startsWith(filterString)) {
// return false;
// }
// } else {
// if (!v.contains(filterString)) {
// return false;
// }
// }
// return true;
// }
// }
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/GridCellFilter.java
import com.vaadin.data.BeanPropertySet;
import com.vaadin.data.PropertySet;
import com.vaadin.data.ValueProvider;
import com.vaadin.data.converter.LocalDateToDateConverter;
import com.vaadin.data.provider.InMemoryDataProviderHelpers;
import com.vaadin.data.provider.ListDataProvider;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.server.FontIcon;
import com.vaadin.server.SerializablePredicate;
import com.vaadin.server.Sizeable.Unit;
import com.vaadin.shared.ui.ValueChangeMode;
import com.vaadin.ui.*;
import com.vaadin.ui.components.grid.HeaderRow;
import com.vaadin.ui.themes.ValoTheme;
import org.vaadin.gridutil.cell.filter.BetweenFilter;
import org.vaadin.gridutil.cell.filter.EqualFilter;
import org.vaadin.gridutil.cell.filter.SimpleStringFilter;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.Map.Entry;
currentValue = textField.getValue();
triggerUpdate();
});
return textField;
}
@Override
public void clearFilter() {
textField.clear();
}
};
handleFilterRow(columnId, filter);
return filter;
}
/**
* assign a <b>EqualFilter</b> to grid for given columnId
*
* @param columnId id of property
* @param beanType class of selection
* @param beans selection for ComboBox
* @return CellFilterComponent that contains ComboBox
*/
public <B> CellFilterComponent<ComboBox<B>> setComboBoxFilter(String columnId, Class<B> beanType, List<B> beans) {
CellFilterComponent<ComboBox<B>> filter = new CellFilterComponent<ComboBox<B>>() {
ComboBox<B> comboBox = new ComboBox();
public void triggerUpdate() {
if (comboBox.getValue() != null) { | replaceFilter(new EqualFilter(comboBox.getValue()), columnId); |
melistik/vaadin-grid-util | vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/GridCellFilter.java | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/BetweenFilter.java
// public class BetweenFilter<T extends Comparable<? super T>> implements SerializablePredicate<Comparable<T>> {
// private final T startValue;
// private final T endValue;
//
// public BetweenFilter(T startValue, T endValue) {
// this.startValue = startValue;
// this.endValue = endValue;
// }
//
// @Override
// public boolean test(Comparable<T> value) {
// if (value == null) {
// return startValue == null && endValue == null;
// }
// return isAfterStart(value) && isBeforeEnd(value);
// }
//
// private boolean isAfterStart(final Comparable<T> value) {
// return startValue == null || value.compareTo(startValue) >= 0;
// }
//
// private boolean isBeforeEnd(final Comparable<T> value) {
// return endValue == null || value.compareTo(endValue) <= 0;
// }
//
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/EqualFilter.java
// public class EqualFilter<T> implements SerializablePredicate<T> {
//
// final T toCompare;
//
// public EqualFilter(T toCompare) {
// this.toCompare = toCompare;
// }
//
// @Override
// public boolean test(T value) {
// if (value == null && toCompare == null) {
// return true;
// }
// if (value == null || toCompare == null) {
// return false;
// }
// return value.equals(toCompare);
// }
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/SimpleStringFilter.java
// public class SimpleStringFilter implements SerializablePredicate<String> {
//
// final String filterString;
// final boolean ignoreCase;
// final boolean onlyMatchPrefix;
//
// public SimpleStringFilter(String filterString, boolean ignoreCase, boolean onlyMatchPrefix) {
// this.ignoreCase = ignoreCase;
// // ignoreCase has to be applied to filterstring too, otherwise uppercase input won't work
// this.filterString = this.ignoreCase ? filterString.toLowerCase() : filterString;
// this.onlyMatchPrefix = onlyMatchPrefix;
// }
//
// @Override
// public boolean test(String value) {
// if (filterString == null || value == null) {
// return false;
// }
// final String v = ignoreCase ? value.toString()
// .toLowerCase()
// : value.toString();
//
// if (onlyMatchPrefix) {
// if (!v.startsWith(filterString)) {
// return false;
// }
// } else {
// if (!v.contains(filterString)) {
// return false;
// }
// }
// return true;
// }
// }
| import com.vaadin.data.BeanPropertySet;
import com.vaadin.data.PropertySet;
import com.vaadin.data.ValueProvider;
import com.vaadin.data.converter.LocalDateToDateConverter;
import com.vaadin.data.provider.InMemoryDataProviderHelpers;
import com.vaadin.data.provider.ListDataProvider;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.server.FontIcon;
import com.vaadin.server.SerializablePredicate;
import com.vaadin.server.Sizeable.Unit;
import com.vaadin.shared.ui.ValueChangeMode;
import com.vaadin.ui.*;
import com.vaadin.ui.components.grid.HeaderRow;
import com.vaadin.ui.themes.ValoTheme;
import org.vaadin.gridutil.cell.filter.BetweenFilter;
import org.vaadin.gridutil.cell.filter.EqualFilter;
import org.vaadin.gridutil.cell.filter.SimpleStringFilter;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.Map.Entry; | getHLayout().setExpandRatio(getSmallestField(), 1);
getHLayout().setExpandRatio(getBiggestField(), 1);
initBinderValueChangeHandler();
return getHLayout();
}
private Date fixTiming(Date date, boolean excludeEndOfDay) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, excludeEndOfDay ? 0 : 999);
calendar.set(Calendar.SECOND, excludeEndOfDay ? 0 : 59);
calendar.set(Calendar.MINUTE, excludeEndOfDay ? 0 : 59);
calendar.set(Calendar.HOUR, excludeEndOfDay ? 0 : 23);
return calendar.getTime();
}
private void initBinderValueChangeHandler() {
getBinder().addValueChangeListener(e -> {
Object smallest = getBinder().getBean()
.getSmallest();
Object biggest = getBinder().getBean()
.getBiggest();
Date smallestDate = checkObject(smallest);
Date biggestDate = checkObject(biggest);
if (this.smallest != null || biggest != null) {
if (this.smallest != null && biggest != null && this.smallest.equals(biggest)) {
replaceFilter(new EqualFilter(this.smallest), columnId);
} else { | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/BetweenFilter.java
// public class BetweenFilter<T extends Comparable<? super T>> implements SerializablePredicate<Comparable<T>> {
// private final T startValue;
// private final T endValue;
//
// public BetweenFilter(T startValue, T endValue) {
// this.startValue = startValue;
// this.endValue = endValue;
// }
//
// @Override
// public boolean test(Comparable<T> value) {
// if (value == null) {
// return startValue == null && endValue == null;
// }
// return isAfterStart(value) && isBeforeEnd(value);
// }
//
// private boolean isAfterStart(final Comparable<T> value) {
// return startValue == null || value.compareTo(startValue) >= 0;
// }
//
// private boolean isBeforeEnd(final Comparable<T> value) {
// return endValue == null || value.compareTo(endValue) <= 0;
// }
//
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/EqualFilter.java
// public class EqualFilter<T> implements SerializablePredicate<T> {
//
// final T toCompare;
//
// public EqualFilter(T toCompare) {
// this.toCompare = toCompare;
// }
//
// @Override
// public boolean test(T value) {
// if (value == null && toCompare == null) {
// return true;
// }
// if (value == null || toCompare == null) {
// return false;
// }
// return value.equals(toCompare);
// }
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/SimpleStringFilter.java
// public class SimpleStringFilter implements SerializablePredicate<String> {
//
// final String filterString;
// final boolean ignoreCase;
// final boolean onlyMatchPrefix;
//
// public SimpleStringFilter(String filterString, boolean ignoreCase, boolean onlyMatchPrefix) {
// this.ignoreCase = ignoreCase;
// // ignoreCase has to be applied to filterstring too, otherwise uppercase input won't work
// this.filterString = this.ignoreCase ? filterString.toLowerCase() : filterString;
// this.onlyMatchPrefix = onlyMatchPrefix;
// }
//
// @Override
// public boolean test(String value) {
// if (filterString == null || value == null) {
// return false;
// }
// final String v = ignoreCase ? value.toString()
// .toLowerCase()
// : value.toString();
//
// if (onlyMatchPrefix) {
// if (!v.startsWith(filterString)) {
// return false;
// }
// } else {
// if (!v.contains(filterString)) {
// return false;
// }
// }
// return true;
// }
// }
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/GridCellFilter.java
import com.vaadin.data.BeanPropertySet;
import com.vaadin.data.PropertySet;
import com.vaadin.data.ValueProvider;
import com.vaadin.data.converter.LocalDateToDateConverter;
import com.vaadin.data.provider.InMemoryDataProviderHelpers;
import com.vaadin.data.provider.ListDataProvider;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.server.FontIcon;
import com.vaadin.server.SerializablePredicate;
import com.vaadin.server.Sizeable.Unit;
import com.vaadin.shared.ui.ValueChangeMode;
import com.vaadin.ui.*;
import com.vaadin.ui.components.grid.HeaderRow;
import com.vaadin.ui.themes.ValoTheme;
import org.vaadin.gridutil.cell.filter.BetweenFilter;
import org.vaadin.gridutil.cell.filter.EqualFilter;
import org.vaadin.gridutil.cell.filter.SimpleStringFilter;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.Map.Entry;
getHLayout().setExpandRatio(getSmallestField(), 1);
getHLayout().setExpandRatio(getBiggestField(), 1);
initBinderValueChangeHandler();
return getHLayout();
}
private Date fixTiming(Date date, boolean excludeEndOfDay) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, excludeEndOfDay ? 0 : 999);
calendar.set(Calendar.SECOND, excludeEndOfDay ? 0 : 59);
calendar.set(Calendar.MINUTE, excludeEndOfDay ? 0 : 59);
calendar.set(Calendar.HOUR, excludeEndOfDay ? 0 : 23);
return calendar.getTime();
}
private void initBinderValueChangeHandler() {
getBinder().addValueChangeListener(e -> {
Object smallest = getBinder().getBean()
.getSmallest();
Object biggest = getBinder().getBean()
.getBiggest();
Date smallestDate = checkObject(smallest);
Date biggestDate = checkObject(biggest);
if (this.smallest != null || biggest != null) {
if (this.smallest != null && biggest != null && this.smallest.equals(biggest)) {
replaceFilter(new EqualFilter(this.smallest), columnId);
} else { | replaceFilter(new BetweenFilter(smallestDate != null ? fixTiming(smallestDate, true) : MIN_DATE_VALUE, |
melistik/vaadin-grid-util | vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/RangeCellFilterComponentFactory.java | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/BetweenFilter.java
// public class BetweenFilter<T extends Comparable<? super T>> implements SerializablePredicate<Comparable<T>> {
// private final T startValue;
// private final T endValue;
//
// public BetweenFilter(T startValue, T endValue) {
// this.startValue = startValue;
// this.endValue = endValue;
// }
//
// @Override
// public boolean test(Comparable<T> value) {
// if (value == null) {
// return startValue == null && endValue == null;
// }
// return isAfterStart(value) && isBeforeEnd(value);
// }
//
// private boolean isAfterStart(final Comparable<T> value) {
// return startValue == null || value.compareTo(startValue) >= 0;
// }
//
// private boolean isBeforeEnd(final Comparable<T> value) {
// return endValue == null || value.compareTo(endValue) <= 0;
// }
//
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/EqualFilter.java
// public class EqualFilter<T> implements SerializablePredicate<T> {
//
// final T toCompare;
//
// public EqualFilter(T toCompare) {
// this.toCompare = toCompare;
// }
//
// @Override
// public boolean test(T value) {
// if (value == null && toCompare == null) {
// return true;
// }
// if (value == null || toCompare == null) {
// return false;
// }
// return value.equals(toCompare);
// }
// }
| import com.vaadin.data.Converter;
import com.vaadin.server.SerializablePredicate;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TextField;
import org.vaadin.gridutil.cell.filter.BetweenFilter;
import org.vaadin.gridutil.cell.filter.EqualFilter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer; | return biggest;
}
private TextField genNumberField(final String propertyId, final Converter converter, final String inputPrompt) {
return FieldFactory.genNumberField(getBinder(), propertyId, converter, inputPrompt);
}
@Override
public HorizontalLayout layoutComponent() {
getHLayout().addComponent(getSmallestField());
getHLayout().addComponent(getBiggestField());
getHLayout().setExpandRatio(getSmallestField(), 1);
getHLayout().setExpandRatio(getBiggestField(), 1);
initBinderValueChangeHandler();
return getHLayout();
}
private void initBinderValueChangeHandler() {
getBinder().addValueChangeListener(e -> {
final T smallest = getBinder().getBean()
.getSmallest();
final T biggest = getBinder().getBean()
.getBiggest();
if (smallest != null || biggest != null) {
//final T smallestValue = checkObject(smallest);
//final T biggestValue = checkObject(biggest);
if (smallest != null && biggest != null && smallest.equals(biggest)) {
filterReplaceConsumer.accept( | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/BetweenFilter.java
// public class BetweenFilter<T extends Comparable<? super T>> implements SerializablePredicate<Comparable<T>> {
// private final T startValue;
// private final T endValue;
//
// public BetweenFilter(T startValue, T endValue) {
// this.startValue = startValue;
// this.endValue = endValue;
// }
//
// @Override
// public boolean test(Comparable<T> value) {
// if (value == null) {
// return startValue == null && endValue == null;
// }
// return isAfterStart(value) && isBeforeEnd(value);
// }
//
// private boolean isAfterStart(final Comparable<T> value) {
// return startValue == null || value.compareTo(startValue) >= 0;
// }
//
// private boolean isBeforeEnd(final Comparable<T> value) {
// return endValue == null || value.compareTo(endValue) <= 0;
// }
//
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/EqualFilter.java
// public class EqualFilter<T> implements SerializablePredicate<T> {
//
// final T toCompare;
//
// public EqualFilter(T toCompare) {
// this.toCompare = toCompare;
// }
//
// @Override
// public boolean test(T value) {
// if (value == null && toCompare == null) {
// return true;
// }
// if (value == null || toCompare == null) {
// return false;
// }
// return value.equals(toCompare);
// }
// }
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/RangeCellFilterComponentFactory.java
import com.vaadin.data.Converter;
import com.vaadin.server.SerializablePredicate;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TextField;
import org.vaadin.gridutil.cell.filter.BetweenFilter;
import org.vaadin.gridutil.cell.filter.EqualFilter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
return biggest;
}
private TextField genNumberField(final String propertyId, final Converter converter, final String inputPrompt) {
return FieldFactory.genNumberField(getBinder(), propertyId, converter, inputPrompt);
}
@Override
public HorizontalLayout layoutComponent() {
getHLayout().addComponent(getSmallestField());
getHLayout().addComponent(getBiggestField());
getHLayout().setExpandRatio(getSmallestField(), 1);
getHLayout().setExpandRatio(getBiggestField(), 1);
initBinderValueChangeHandler();
return getHLayout();
}
private void initBinderValueChangeHandler() {
getBinder().addValueChangeListener(e -> {
final T smallest = getBinder().getBean()
.getSmallest();
final T biggest = getBinder().getBean()
.getBiggest();
if (smallest != null || biggest != null) {
//final T smallestValue = checkObject(smallest);
//final T biggestValue = checkObject(biggest);
if (smallest != null && biggest != null && smallest.equals(biggest)) {
filterReplaceConsumer.accept( | new EqualFilter(smallest), |
melistik/vaadin-grid-util | vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/RangeCellFilterComponentFactory.java | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/BetweenFilter.java
// public class BetweenFilter<T extends Comparable<? super T>> implements SerializablePredicate<Comparable<T>> {
// private final T startValue;
// private final T endValue;
//
// public BetweenFilter(T startValue, T endValue) {
// this.startValue = startValue;
// this.endValue = endValue;
// }
//
// @Override
// public boolean test(Comparable<T> value) {
// if (value == null) {
// return startValue == null && endValue == null;
// }
// return isAfterStart(value) && isBeforeEnd(value);
// }
//
// private boolean isAfterStart(final Comparable<T> value) {
// return startValue == null || value.compareTo(startValue) >= 0;
// }
//
// private boolean isBeforeEnd(final Comparable<T> value) {
// return endValue == null || value.compareTo(endValue) <= 0;
// }
//
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/EqualFilter.java
// public class EqualFilter<T> implements SerializablePredicate<T> {
//
// final T toCompare;
//
// public EqualFilter(T toCompare) {
// this.toCompare = toCompare;
// }
//
// @Override
// public boolean test(T value) {
// if (value == null && toCompare == null) {
// return true;
// }
// if (value == null || toCompare == null) {
// return false;
// }
// return value.equals(toCompare);
// }
// }
| import com.vaadin.data.Converter;
import com.vaadin.server.SerializablePredicate;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TextField;
import org.vaadin.gridutil.cell.filter.BetweenFilter;
import org.vaadin.gridutil.cell.filter.EqualFilter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer; | return FieldFactory.genNumberField(getBinder(), propertyId, converter, inputPrompt);
}
@Override
public HorizontalLayout layoutComponent() {
getHLayout().addComponent(getSmallestField());
getHLayout().addComponent(getBiggestField());
getHLayout().setExpandRatio(getSmallestField(), 1);
getHLayout().setExpandRatio(getBiggestField(), 1);
initBinderValueChangeHandler();
return getHLayout();
}
private void initBinderValueChangeHandler() {
getBinder().addValueChangeListener(e -> {
final T smallest = getBinder().getBean()
.getSmallest();
final T biggest = getBinder().getBean()
.getBiggest();
if (smallest != null || biggest != null) {
//final T smallestValue = checkObject(smallest);
//final T biggestValue = checkObject(biggest);
if (smallest != null && biggest != null && smallest.equals(biggest)) {
filterReplaceConsumer.accept(
new EqualFilter(smallest),
propertyId);
} else {
filterReplaceConsumer.accept( | // Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/BetweenFilter.java
// public class BetweenFilter<T extends Comparable<? super T>> implements SerializablePredicate<Comparable<T>> {
// private final T startValue;
// private final T endValue;
//
// public BetweenFilter(T startValue, T endValue) {
// this.startValue = startValue;
// this.endValue = endValue;
// }
//
// @Override
// public boolean test(Comparable<T> value) {
// if (value == null) {
// return startValue == null && endValue == null;
// }
// return isAfterStart(value) && isBeforeEnd(value);
// }
//
// private boolean isAfterStart(final Comparable<T> value) {
// return startValue == null || value.compareTo(startValue) >= 0;
// }
//
// private boolean isBeforeEnd(final Comparable<T> value) {
// return endValue == null || value.compareTo(endValue) <= 0;
// }
//
// }
//
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/filter/EqualFilter.java
// public class EqualFilter<T> implements SerializablePredicate<T> {
//
// final T toCompare;
//
// public EqualFilter(T toCompare) {
// this.toCompare = toCompare;
// }
//
// @Override
// public boolean test(T value) {
// if (value == null && toCompare == null) {
// return true;
// }
// if (value == null || toCompare == null) {
// return false;
// }
// return value.equals(toCompare);
// }
// }
// Path: vaadin-grid-util/src/main/java/org/vaadin/gridutil/cell/RangeCellFilterComponentFactory.java
import com.vaadin.data.Converter;
import com.vaadin.server.SerializablePredicate;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TextField;
import org.vaadin.gridutil.cell.filter.BetweenFilter;
import org.vaadin.gridutil.cell.filter.EqualFilter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
return FieldFactory.genNumberField(getBinder(), propertyId, converter, inputPrompt);
}
@Override
public HorizontalLayout layoutComponent() {
getHLayout().addComponent(getSmallestField());
getHLayout().addComponent(getBiggestField());
getHLayout().setExpandRatio(getSmallestField(), 1);
getHLayout().setExpandRatio(getBiggestField(), 1);
initBinderValueChangeHandler();
return getHLayout();
}
private void initBinderValueChangeHandler() {
getBinder().addValueChangeListener(e -> {
final T smallest = getBinder().getBean()
.getSmallest();
final T biggest = getBinder().getBean()
.getBiggest();
if (smallest != null || biggest != null) {
//final T smallestValue = checkObject(smallest);
//final T biggestValue = checkObject(biggest);
if (smallest != null && biggest != null && smallest.equals(biggest)) {
filterReplaceConsumer.accept(
new EqualFilter(smallest),
propertyId);
} else {
filterReplaceConsumer.accept( | new BetweenFilter( |
AKSW/TripleCheckMate | src/main/java/org/aksw/TripleCheckMate/server/storage/JDBCStorageService.java | // Path: src/main/java/org/aksw/TripleCheckMate/shared/sparql/Endpoint.java
// public class Endpoint implements Serializable {
// private long endpointID = 0;
// private String endpoint;
// private List<String> graphs = new ArrayList<String>();
// private String name;
//
// public Endpoint() {
// endpoint = "";
// name="";
// graphs = Arrays.asList();
// }
//
// public Endpoint(long id, String endpoint, String graphs, String name) {
// this.endpointID = id;
// this.endpoint = endpoint;
// String[] g = graphs.split(";");
// for (int i = 0; i < g.length; i++)
// this.graphs.add(g[i]);
// this.name = name;
// }
//
// public long getID(){
// return endpointID;
// }
//
// public String getName() {
// return name;
// }
//
// public String getEndpoint() {
// return endpoint;
// }
//
// public List<String> getGraphs() {
// return graphs;
// }
//
// public String getDefaultGraph() {
// return graphs.get(0);
// }
//
// public String generateQueryURL(String sparqlQuery) {
// String retVal = "";
// retVal += endpoint;
// //retVal += "?default-graph-uri=" + URL.encode(graphs.get(0));
// retVal += "?format=json&query=";
// retVal += URL.encode(sparqlQuery).replace("#", "%23");
// return retVal;
// }
//
// public String getQueryforResourceTriples(String resource) {
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return "select ?p ?o " +
// from +
// "where {<" +
// resource +
// "> ?p ?o} ORDER BY ?p";
// }
//
// public String getQueryforRandomResource() {
//
// int offset = Random.nextInt(760129);
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT ?s " + from +
// " WHERE { ?s foaf:isPrimaryTopicOf ?o } LIMIT 1 OFFSET " + offset;
// }
//
// public String getQueryforRandomClassResource(String classURI, long maxRand) {
//
// int offset = Random.nextInt((int) maxRand);
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT ?s " + from +
// " WHERE { ?s rdf:type <" + classURI + "> } LIMIT 1 OFFSET " + offset;
// }
//
// public String getQueryforClassCount(String classURI) {
//
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT count(?s) " + from +
// " WHERE { ?s rdf:type <" + classURI + "> }";
// }
//
// public String getQueryforAutocomplete(String namepart) {
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT ?s " + from +
// " WHERE { ?s foaf:isPrimaryTopicOf ?o . " +
// " FILTER regex(str(?s), '" + namepart + "', 'i'). } LIMIT 10";
// }
// }
//
// Path: src/main/java/org/aksw/TripleCheckMate/shared/exceptions/StorageServiceException.java
// public class StorageServiceException extends Exception implements
// Serializable {
//
// /**
// * Autogenerated for serialization
// */
// private static final long serialVersionUID = -1709522630145405589L;
//
// private String errorMessage;
//
// public StorageServiceException() {
// }
//
// public StorageServiceException(String message) {
// this.errorMessage = message;
// }
//
// public String getErrorMessage() {
// return this.errorMessage;
// }
//
// }
| import org.aksw.TripleCheckMate.shared.evaluate.*;
import org.aksw.TripleCheckMate.shared.sparql.Endpoint;
import org.aksw.TripleCheckMate.shared.exceptions.StorageServiceException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List; | /*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.server.storage;
public class JDBCStorageService extends StorageService {
private String JDBC_DRIVER = "org.h2.Driver";
private String DB_URL = "jdbc:h2:evaluation_db";
private String USER = "sa";
private String PASS = "";
public JDBCStorageService(String driver, String dburl, String username,
String password) {
JDBC_DRIVER = driver;
DB_URL = dburl;
USER = username;
PASS = password;
}
private void executeUpdateQuery(String query) | // Path: src/main/java/org/aksw/TripleCheckMate/shared/sparql/Endpoint.java
// public class Endpoint implements Serializable {
// private long endpointID = 0;
// private String endpoint;
// private List<String> graphs = new ArrayList<String>();
// private String name;
//
// public Endpoint() {
// endpoint = "";
// name="";
// graphs = Arrays.asList();
// }
//
// public Endpoint(long id, String endpoint, String graphs, String name) {
// this.endpointID = id;
// this.endpoint = endpoint;
// String[] g = graphs.split(";");
// for (int i = 0; i < g.length; i++)
// this.graphs.add(g[i]);
// this.name = name;
// }
//
// public long getID(){
// return endpointID;
// }
//
// public String getName() {
// return name;
// }
//
// public String getEndpoint() {
// return endpoint;
// }
//
// public List<String> getGraphs() {
// return graphs;
// }
//
// public String getDefaultGraph() {
// return graphs.get(0);
// }
//
// public String generateQueryURL(String sparqlQuery) {
// String retVal = "";
// retVal += endpoint;
// //retVal += "?default-graph-uri=" + URL.encode(graphs.get(0));
// retVal += "?format=json&query=";
// retVal += URL.encode(sparqlQuery).replace("#", "%23");
// return retVal;
// }
//
// public String getQueryforResourceTriples(String resource) {
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return "select ?p ?o " +
// from +
// "where {<" +
// resource +
// "> ?p ?o} ORDER BY ?p";
// }
//
// public String getQueryforRandomResource() {
//
// int offset = Random.nextInt(760129);
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT ?s " + from +
// " WHERE { ?s foaf:isPrimaryTopicOf ?o } LIMIT 1 OFFSET " + offset;
// }
//
// public String getQueryforRandomClassResource(String classURI, long maxRand) {
//
// int offset = Random.nextInt((int) maxRand);
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT ?s " + from +
// " WHERE { ?s rdf:type <" + classURI + "> } LIMIT 1 OFFSET " + offset;
// }
//
// public String getQueryforClassCount(String classURI) {
//
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT count(?s) " + from +
// " WHERE { ?s rdf:type <" + classURI + "> }";
// }
//
// public String getQueryforAutocomplete(String namepart) {
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT ?s " + from +
// " WHERE { ?s foaf:isPrimaryTopicOf ?o . " +
// " FILTER regex(str(?s), '" + namepart + "', 'i'). } LIMIT 10";
// }
// }
//
// Path: src/main/java/org/aksw/TripleCheckMate/shared/exceptions/StorageServiceException.java
// public class StorageServiceException extends Exception implements
// Serializable {
//
// /**
// * Autogenerated for serialization
// */
// private static final long serialVersionUID = -1709522630145405589L;
//
// private String errorMessage;
//
// public StorageServiceException() {
// }
//
// public StorageServiceException(String message) {
// this.errorMessage = message;
// }
//
// public String getErrorMessage() {
// return this.errorMessage;
// }
//
// }
// Path: src/main/java/org/aksw/TripleCheckMate/server/storage/JDBCStorageService.java
import org.aksw.TripleCheckMate.shared.evaluate.*;
import org.aksw.TripleCheckMate.shared.sparql.Endpoint;
import org.aksw.TripleCheckMate.shared.exceptions.StorageServiceException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
/*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.server.storage;
public class JDBCStorageService extends StorageService {
private String JDBC_DRIVER = "org.h2.Driver";
private String DB_URL = "jdbc:h2:evaluation_db";
private String USER = "sa";
private String PASS = "";
public JDBCStorageService(String driver, String dburl, String username,
String password) {
JDBC_DRIVER = driver;
DB_URL = dburl;
USER = username;
PASS = password;
}
private void executeUpdateQuery(String query) | throws StorageServiceException { |
AKSW/TripleCheckMate | src/main/java/org/aksw/TripleCheckMate/server/storage/JDBCStorageService.java | // Path: src/main/java/org/aksw/TripleCheckMate/shared/sparql/Endpoint.java
// public class Endpoint implements Serializable {
// private long endpointID = 0;
// private String endpoint;
// private List<String> graphs = new ArrayList<String>();
// private String name;
//
// public Endpoint() {
// endpoint = "";
// name="";
// graphs = Arrays.asList();
// }
//
// public Endpoint(long id, String endpoint, String graphs, String name) {
// this.endpointID = id;
// this.endpoint = endpoint;
// String[] g = graphs.split(";");
// for (int i = 0; i < g.length; i++)
// this.graphs.add(g[i]);
// this.name = name;
// }
//
// public long getID(){
// return endpointID;
// }
//
// public String getName() {
// return name;
// }
//
// public String getEndpoint() {
// return endpoint;
// }
//
// public List<String> getGraphs() {
// return graphs;
// }
//
// public String getDefaultGraph() {
// return graphs.get(0);
// }
//
// public String generateQueryURL(String sparqlQuery) {
// String retVal = "";
// retVal += endpoint;
// //retVal += "?default-graph-uri=" + URL.encode(graphs.get(0));
// retVal += "?format=json&query=";
// retVal += URL.encode(sparqlQuery).replace("#", "%23");
// return retVal;
// }
//
// public String getQueryforResourceTriples(String resource) {
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return "select ?p ?o " +
// from +
// "where {<" +
// resource +
// "> ?p ?o} ORDER BY ?p";
// }
//
// public String getQueryforRandomResource() {
//
// int offset = Random.nextInt(760129);
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT ?s " + from +
// " WHERE { ?s foaf:isPrimaryTopicOf ?o } LIMIT 1 OFFSET " + offset;
// }
//
// public String getQueryforRandomClassResource(String classURI, long maxRand) {
//
// int offset = Random.nextInt((int) maxRand);
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT ?s " + from +
// " WHERE { ?s rdf:type <" + classURI + "> } LIMIT 1 OFFSET " + offset;
// }
//
// public String getQueryforClassCount(String classURI) {
//
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT count(?s) " + from +
// " WHERE { ?s rdf:type <" + classURI + "> }";
// }
//
// public String getQueryforAutocomplete(String namepart) {
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT ?s " + from +
// " WHERE { ?s foaf:isPrimaryTopicOf ?o . " +
// " FILTER regex(str(?s), '" + namepart + "', 'i'). } LIMIT 10";
// }
// }
//
// Path: src/main/java/org/aksw/TripleCheckMate/shared/exceptions/StorageServiceException.java
// public class StorageServiceException extends Exception implements
// Serializable {
//
// /**
// * Autogenerated for serialization
// */
// private static final long serialVersionUID = -1709522630145405589L;
//
// private String errorMessage;
//
// public StorageServiceException() {
// }
//
// public StorageServiceException(String message) {
// this.errorMessage = message;
// }
//
// public String getErrorMessage() {
// return this.errorMessage;
// }
//
// }
| import org.aksw.TripleCheckMate.shared.evaluate.*;
import org.aksw.TripleCheckMate.shared.sparql.Endpoint;
import org.aksw.TripleCheckMate.shared.exceptions.StorageServiceException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List; | }
private void updateUserStatistics(long userID)
throws StorageServiceException {
String qCountRes = " SELECT COUNT( r.rid ) AS total "
+ " FROM evaluated_resource r INNER JOIN evaluation_session s ON (r.sid = s.sid) "
+ " WHERE s.uid = " + userID;
long cntRes = getNumberFromQuery(qCountRes, "total", true);
String qCountTrpl = "SELECT COUNT( d.eid ) AS total "
+ " FROM evaluated_resource_details d "
+ " INNER JOIN evaluated_resource r ON (d.rid = r.rid) "
+ " INNER JOIN evaluation_session s ON (r.sid = s.sid) "
+ " WHERE s.uid = " + userID;
long cntTrpl = getNumberFromQuery(qCountTrpl, "total", true);
String qCountDistinct = "SELECT count(DISTINCT d.error_id) AS total "
+ " FROM evaluated_resource_details d "
+ " INNER JOIN evaluated_resource r ON (d.rid = r.rid) "
+ " INNER JOIN evaluation_session s ON (r.sid = s.sid) "
+ " WHERE s.uid = " + userID;
long cntDistinct = getNumberFromQuery(qCountDistinct, "total", true);
String userUpdateQuery = "UPDATE users SET " + " statR=" + cntRes
+ ", " + " statT=" + cntTrpl + ", " + " statD=" + cntDistinct
+ " " + " WHERE uid = " + userID;
executeUpdateQuery(userUpdateQuery);
}
@Override | // Path: src/main/java/org/aksw/TripleCheckMate/shared/sparql/Endpoint.java
// public class Endpoint implements Serializable {
// private long endpointID = 0;
// private String endpoint;
// private List<String> graphs = new ArrayList<String>();
// private String name;
//
// public Endpoint() {
// endpoint = "";
// name="";
// graphs = Arrays.asList();
// }
//
// public Endpoint(long id, String endpoint, String graphs, String name) {
// this.endpointID = id;
// this.endpoint = endpoint;
// String[] g = graphs.split(";");
// for (int i = 0; i < g.length; i++)
// this.graphs.add(g[i]);
// this.name = name;
// }
//
// public long getID(){
// return endpointID;
// }
//
// public String getName() {
// return name;
// }
//
// public String getEndpoint() {
// return endpoint;
// }
//
// public List<String> getGraphs() {
// return graphs;
// }
//
// public String getDefaultGraph() {
// return graphs.get(0);
// }
//
// public String generateQueryURL(String sparqlQuery) {
// String retVal = "";
// retVal += endpoint;
// //retVal += "?default-graph-uri=" + URL.encode(graphs.get(0));
// retVal += "?format=json&query=";
// retVal += URL.encode(sparqlQuery).replace("#", "%23");
// return retVal;
// }
//
// public String getQueryforResourceTriples(String resource) {
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return "select ?p ?o " +
// from +
// "where {<" +
// resource +
// "> ?p ?o} ORDER BY ?p";
// }
//
// public String getQueryforRandomResource() {
//
// int offset = Random.nextInt(760129);
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT ?s " + from +
// " WHERE { ?s foaf:isPrimaryTopicOf ?o } LIMIT 1 OFFSET " + offset;
// }
//
// public String getQueryforRandomClassResource(String classURI, long maxRand) {
//
// int offset = Random.nextInt((int) maxRand);
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT ?s " + from +
// " WHERE { ?s rdf:type <" + classURI + "> } LIMIT 1 OFFSET " + offset;
// }
//
// public String getQueryforClassCount(String classURI) {
//
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT count(?s) " + from +
// " WHERE { ?s rdf:type <" + classURI + "> }";
// }
//
// public String getQueryforAutocomplete(String namepart) {
// String from = "";
// for (String g : graphs)
// from += " FROM <" + g + "> ";
// return " SELECT ?s " + from +
// " WHERE { ?s foaf:isPrimaryTopicOf ?o . " +
// " FILTER regex(str(?s), '" + namepart + "', 'i'). } LIMIT 10";
// }
// }
//
// Path: src/main/java/org/aksw/TripleCheckMate/shared/exceptions/StorageServiceException.java
// public class StorageServiceException extends Exception implements
// Serializable {
//
// /**
// * Autogenerated for serialization
// */
// private static final long serialVersionUID = -1709522630145405589L;
//
// private String errorMessage;
//
// public StorageServiceException() {
// }
//
// public StorageServiceException(String message) {
// this.errorMessage = message;
// }
//
// public String getErrorMessage() {
// return this.errorMessage;
// }
//
// }
// Path: src/main/java/org/aksw/TripleCheckMate/server/storage/JDBCStorageService.java
import org.aksw.TripleCheckMate.shared.evaluate.*;
import org.aksw.TripleCheckMate.shared.sparql.Endpoint;
import org.aksw.TripleCheckMate.shared.exceptions.StorageServiceException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
}
private void updateUserStatistics(long userID)
throws StorageServiceException {
String qCountRes = " SELECT COUNT( r.rid ) AS total "
+ " FROM evaluated_resource r INNER JOIN evaluation_session s ON (r.sid = s.sid) "
+ " WHERE s.uid = " + userID;
long cntRes = getNumberFromQuery(qCountRes, "total", true);
String qCountTrpl = "SELECT COUNT( d.eid ) AS total "
+ " FROM evaluated_resource_details d "
+ " INNER JOIN evaluated_resource r ON (d.rid = r.rid) "
+ " INNER JOIN evaluation_session s ON (r.sid = s.sid) "
+ " WHERE s.uid = " + userID;
long cntTrpl = getNumberFromQuery(qCountTrpl, "total", true);
String qCountDistinct = "SELECT count(DISTINCT d.error_id) AS total "
+ " FROM evaluated_resource_details d "
+ " INNER JOIN evaluated_resource r ON (d.rid = r.rid) "
+ " INNER JOIN evaluation_session s ON (r.sid = s.sid) "
+ " WHERE s.uid = " + userID;
long cntDistinct = getNumberFromQuery(qCountDistinct, "total", true);
String userUpdateQuery = "UPDATE users SET " + " statR=" + cntRes
+ ", " + " statT=" + cntTrpl + ", " + " statD=" + cntDistinct
+ " " + " WHERE uid = " + userID;
executeUpdateQuery(userUpdateQuery);
}
@Override | public List<Endpoint> getCampaigns() throws StorageServiceException { |
AKSW/TripleCheckMate | src/main/java/org/aksw/TripleCheckMate/client/TripleCheckMate.java | // Path: src/main/java/org/aksw/TripleCheckMate/shared/evaluate/SessionContext.java
// public class SessionContext {
// private SessionContext() {
// }
//
// // User related
// public static UserRecord user = new UserRecord();
// public static long userSession = 0;
//
// // Evaluation
// public static int evaluationCampaign = 0;
// public static EvaluateResource latestEvaluateResource = new EvaluateResource();
// public static List<EvaluateResource> evaluations = new ArrayList<EvaluateResource>();
// // TODO get it with RPC
// public static Endpoint endpoint = new Endpoint(
// 0,
// "http://live.dbpedia.org/sparql",
// "http://dbpedia.org",
// "live.dbpedia.org/sparql");
//
// // Async RPC Requests
// public static EvaluationRequestAsync evaluationReqSrv = GWT
// .create(EvaluationRequest.class);
// public static UserRequestAsync userReqSrv = GWT.create(UserRequest.class);
//
// // GUI related
// public static DecoratedTabPanel tabPanel = new DecoratedTabPanel();
// public static EvaluationPage pageEval = new EvaluationPage();
// public static StartPage pageStart = new StartPage();
// public static LoadingPopup popup = new LoadingPopup();
//
// public static void showPopup() {
// popup.center();
// popup.show();
// }
//
// public static void hidePopup() {
// popup.hide();
// }
//
// public static void setNewEvaluation(String aboutURI,
// List<EvaluateItem> data, String classType) {
// if (!latestEvaluateResource.about.equals("")) {
// // Add evaluation history
// evaluations.add(new EvaluateResource(latestEvaluateResource));
// }
// latestEvaluateResource.updateContents(aboutURI, false, "",
// new ArrayList<EvaluateItem>(), classType);
// pageEval.setNewEvaluation(aboutURI, data);
// }
//
// public static boolean existsInSessionHistory(String resource) {
// if (latestEvaluateResource.about.equals(resource))
// return true;
// for (EvaluateResource r : evaluations)
// if (r.about.equals(resource))
// return true;
// return false;
// }
//
// public static void submitEvaluation(EvaluateResource e) {
//
// }
//
// public static void gotoEvaluationPage() {
// SessionContext.tabPanel.selectTab(1);
// pageEval.openSelectDialog();
// }
//
// public static String getUserProgressTxt() {
// int submitted = 0;
// int skipped = 0;
// for (EvaluateResource i : evaluations) {
// if (i.isSkipped == true)
// skipped++;
// else
// submitted++;
// }
// if (!latestEvaluateResource.about.equals(""))
// if (latestEvaluateResource.isSkipped == true)
// skipped++;
// else
// submitted++;
//
// return "<div class=\"user-progress\">" + user.toHTMLString()
// + "<div class=\"user-progress-item\">Submitted " + submitted
// + ", Skipped " + skipped + "</div></div>";
// }
//
// public static void finishEvaluation() {
// pageEval.finishEvaluation();
// pageStart.StartEvaluation();
// SessionContext.tabPanel.selectTab(0);
//
// }
//
// }
| import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.logical.shared.BeforeSelectionEvent;
import com.google.gwt.event.logical.shared.BeforeSelectionHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import org.aksw.TripleCheckMate.shared.evaluate.SessionContext; | /*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.client;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class TripleCheckMate implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad() {
setHeaderTop();
setHeaderBottom();
setVisualPlacement();
}
private void setVisualPlacement() {
RootPanel rootPanel = RootPanel.get();
VerticalPanel page = new VerticalPanel();
page.setHeight("100%");
page.setWidth("100%");
rootPanel.add(page);
VerticalPanel evalTabPanel = new VerticalPanel();
| // Path: src/main/java/org/aksw/TripleCheckMate/shared/evaluate/SessionContext.java
// public class SessionContext {
// private SessionContext() {
// }
//
// // User related
// public static UserRecord user = new UserRecord();
// public static long userSession = 0;
//
// // Evaluation
// public static int evaluationCampaign = 0;
// public static EvaluateResource latestEvaluateResource = new EvaluateResource();
// public static List<EvaluateResource> evaluations = new ArrayList<EvaluateResource>();
// // TODO get it with RPC
// public static Endpoint endpoint = new Endpoint(
// 0,
// "http://live.dbpedia.org/sparql",
// "http://dbpedia.org",
// "live.dbpedia.org/sparql");
//
// // Async RPC Requests
// public static EvaluationRequestAsync evaluationReqSrv = GWT
// .create(EvaluationRequest.class);
// public static UserRequestAsync userReqSrv = GWT.create(UserRequest.class);
//
// // GUI related
// public static DecoratedTabPanel tabPanel = new DecoratedTabPanel();
// public static EvaluationPage pageEval = new EvaluationPage();
// public static StartPage pageStart = new StartPage();
// public static LoadingPopup popup = new LoadingPopup();
//
// public static void showPopup() {
// popup.center();
// popup.show();
// }
//
// public static void hidePopup() {
// popup.hide();
// }
//
// public static void setNewEvaluation(String aboutURI,
// List<EvaluateItem> data, String classType) {
// if (!latestEvaluateResource.about.equals("")) {
// // Add evaluation history
// evaluations.add(new EvaluateResource(latestEvaluateResource));
// }
// latestEvaluateResource.updateContents(aboutURI, false, "",
// new ArrayList<EvaluateItem>(), classType);
// pageEval.setNewEvaluation(aboutURI, data);
// }
//
// public static boolean existsInSessionHistory(String resource) {
// if (latestEvaluateResource.about.equals(resource))
// return true;
// for (EvaluateResource r : evaluations)
// if (r.about.equals(resource))
// return true;
// return false;
// }
//
// public static void submitEvaluation(EvaluateResource e) {
//
// }
//
// public static void gotoEvaluationPage() {
// SessionContext.tabPanel.selectTab(1);
// pageEval.openSelectDialog();
// }
//
// public static String getUserProgressTxt() {
// int submitted = 0;
// int skipped = 0;
// for (EvaluateResource i : evaluations) {
// if (i.isSkipped == true)
// skipped++;
// else
// submitted++;
// }
// if (!latestEvaluateResource.about.equals(""))
// if (latestEvaluateResource.isSkipped == true)
// skipped++;
// else
// submitted++;
//
// return "<div class=\"user-progress\">" + user.toHTMLString()
// + "<div class=\"user-progress-item\">Submitted " + submitted
// + ", Skipped " + skipped + "</div></div>";
// }
//
// public static void finishEvaluation() {
// pageEval.finishEvaluation();
// pageStart.StartEvaluation();
// SessionContext.tabPanel.selectTab(0);
//
// }
//
// }
// Path: src/main/java/org/aksw/TripleCheckMate/client/TripleCheckMate.java
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.logical.shared.BeforeSelectionEvent;
import com.google.gwt.event.logical.shared.BeforeSelectionHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import org.aksw.TripleCheckMate.shared.evaluate.SessionContext;
/*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.client;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class TripleCheckMate implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad() {
setHeaderTop();
setHeaderBottom();
setVisualPlacement();
}
private void setVisualPlacement() {
RootPanel rootPanel = RootPanel.get();
VerticalPanel page = new VerticalPanel();
page.setHeight("100%");
page.setWidth("100%");
rootPanel.add(page);
VerticalPanel evalTabPanel = new VerticalPanel();
| SessionContext.tabPanel.add(SessionContext.pageStart, "DBpedia Evaluation Campaign"); |
AKSW/TripleCheckMate | src/main/java/org/aksw/TripleCheckMate/client/requests/UserRequest.java | // Path: src/main/java/org/aksw/TripleCheckMate/shared/evaluate/UserRecord.java
// public class UserRecord implements Comparable<UserRecord>, Serializable {
// /**
// * Auto-generated for serialization
// */
// private static final long serialVersionUID = 8871828625070002603L;
//
// public long userID = -1;
// public String googleID = "";
// public String name = "";
// public String picture = "";
// public String profile = "";
//
// public int recordCount = 0;
// public int errorCount = 0;
// public int distinctErrorCount = 0;
//
//
// public UserRecord() {
// }
//
// public UserRecord(long userID, String googleID, String name, String picture, String profile) {
// this.userID = userID;
// this.googleID = googleID;
// this.name = name;
// this.picture = picture;
// this.profile = profile;
// }
//
// public UserRecord(UserRecord u) {
// update(u);
// }
//
// public void update(UserRecord u) {
// this.userID = u.userID;
// this.googleID = u.googleID;
// this.name = u.name;
// this.picture = u.picture;
// this.profile = u.profile;
// this.recordCount = u.recordCount;
// this.errorCount = u.errorCount;
// this.distinctErrorCount = u.distinctErrorCount;
// }
//
// public void updateStatistics(int rc, int ec, int dc) {
// this.recordCount = rc;
// this.errorCount = ec;
// this.distinctErrorCount = dc;
// }
//
// public static final ProvidesKey<UserRecord> KEY_PROVIDER = new ProvidesKey<UserRecord>() {
// public Object getKey(UserRecord item) {
// return item == null ? null : item.userID;
// }
// };
//
// public String toHTMLString() {
// String img = (picture.equals("")) ? "" : "<img width=\"20\" height=\"20\" src=\"" + picture + "\" class =\"user-display-picture\"/>";
// return "<div class=\"user-display\">" + img + name + "</div>";
// }
//
// public int compareTo(UserRecord arg0) {
// // TODO Auto-generated method stub
// return name.compareTo(arg0.name);
// }
//
// }
//
// Path: src/main/java/org/aksw/TripleCheckMate/shared/exceptions/StorageServiceException.java
// public class StorageServiceException extends Exception implements
// Serializable {
//
// /**
// * Autogenerated for serialization
// */
// private static final long serialVersionUID = -1709522630145405589L;
//
// private String errorMessage;
//
// public StorageServiceException() {
// }
//
// public StorageServiceException(String message) {
// this.errorMessage = message;
// }
//
// public String getErrorMessage() {
// return this.errorMessage;
// }
//
// }
| import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import org.aksw.TripleCheckMate.shared.evaluate.UserRecord;
import org.aksw.TripleCheckMate.shared.exceptions.StorageServiceException;
import java.util.List; | /*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.client.requests;
@RemoteServiceRelativePath("UserRequest")
public interface UserRequest extends RemoteService { | // Path: src/main/java/org/aksw/TripleCheckMate/shared/evaluate/UserRecord.java
// public class UserRecord implements Comparable<UserRecord>, Serializable {
// /**
// * Auto-generated for serialization
// */
// private static final long serialVersionUID = 8871828625070002603L;
//
// public long userID = -1;
// public String googleID = "";
// public String name = "";
// public String picture = "";
// public String profile = "";
//
// public int recordCount = 0;
// public int errorCount = 0;
// public int distinctErrorCount = 0;
//
//
// public UserRecord() {
// }
//
// public UserRecord(long userID, String googleID, String name, String picture, String profile) {
// this.userID = userID;
// this.googleID = googleID;
// this.name = name;
// this.picture = picture;
// this.profile = profile;
// }
//
// public UserRecord(UserRecord u) {
// update(u);
// }
//
// public void update(UserRecord u) {
// this.userID = u.userID;
// this.googleID = u.googleID;
// this.name = u.name;
// this.picture = u.picture;
// this.profile = u.profile;
// this.recordCount = u.recordCount;
// this.errorCount = u.errorCount;
// this.distinctErrorCount = u.distinctErrorCount;
// }
//
// public void updateStatistics(int rc, int ec, int dc) {
// this.recordCount = rc;
// this.errorCount = ec;
// this.distinctErrorCount = dc;
// }
//
// public static final ProvidesKey<UserRecord> KEY_PROVIDER = new ProvidesKey<UserRecord>() {
// public Object getKey(UserRecord item) {
// return item == null ? null : item.userID;
// }
// };
//
// public String toHTMLString() {
// String img = (picture.equals("")) ? "" : "<img width=\"20\" height=\"20\" src=\"" + picture + "\" class =\"user-display-picture\"/>";
// return "<div class=\"user-display\">" + img + name + "</div>";
// }
//
// public int compareTo(UserRecord arg0) {
// // TODO Auto-generated method stub
// return name.compareTo(arg0.name);
// }
//
// }
//
// Path: src/main/java/org/aksw/TripleCheckMate/shared/exceptions/StorageServiceException.java
// public class StorageServiceException extends Exception implements
// Serializable {
//
// /**
// * Autogenerated for serialization
// */
// private static final long serialVersionUID = -1709522630145405589L;
//
// private String errorMessage;
//
// public StorageServiceException() {
// }
//
// public StorageServiceException(String message) {
// this.errorMessage = message;
// }
//
// public String getErrorMessage() {
// return this.errorMessage;
// }
//
// }
// Path: src/main/java/org/aksw/TripleCheckMate/client/requests/UserRequest.java
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import org.aksw.TripleCheckMate.shared.evaluate.UserRecord;
import org.aksw.TripleCheckMate.shared.exceptions.StorageServiceException;
import java.util.List;
/*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.client.requests;
@RemoteServiceRelativePath("UserRequest")
public interface UserRequest extends RemoteService { | public UserRecord getUserInfo(String userGoogleID) throws StorageServiceException; |
AKSW/TripleCheckMate | src/main/java/org/aksw/TripleCheckMate/client/requests/UserRequest.java | // Path: src/main/java/org/aksw/TripleCheckMate/shared/evaluate/UserRecord.java
// public class UserRecord implements Comparable<UserRecord>, Serializable {
// /**
// * Auto-generated for serialization
// */
// private static final long serialVersionUID = 8871828625070002603L;
//
// public long userID = -1;
// public String googleID = "";
// public String name = "";
// public String picture = "";
// public String profile = "";
//
// public int recordCount = 0;
// public int errorCount = 0;
// public int distinctErrorCount = 0;
//
//
// public UserRecord() {
// }
//
// public UserRecord(long userID, String googleID, String name, String picture, String profile) {
// this.userID = userID;
// this.googleID = googleID;
// this.name = name;
// this.picture = picture;
// this.profile = profile;
// }
//
// public UserRecord(UserRecord u) {
// update(u);
// }
//
// public void update(UserRecord u) {
// this.userID = u.userID;
// this.googleID = u.googleID;
// this.name = u.name;
// this.picture = u.picture;
// this.profile = u.profile;
// this.recordCount = u.recordCount;
// this.errorCount = u.errorCount;
// this.distinctErrorCount = u.distinctErrorCount;
// }
//
// public void updateStatistics(int rc, int ec, int dc) {
// this.recordCount = rc;
// this.errorCount = ec;
// this.distinctErrorCount = dc;
// }
//
// public static final ProvidesKey<UserRecord> KEY_PROVIDER = new ProvidesKey<UserRecord>() {
// public Object getKey(UserRecord item) {
// return item == null ? null : item.userID;
// }
// };
//
// public String toHTMLString() {
// String img = (picture.equals("")) ? "" : "<img width=\"20\" height=\"20\" src=\"" + picture + "\" class =\"user-display-picture\"/>";
// return "<div class=\"user-display\">" + img + name + "</div>";
// }
//
// public int compareTo(UserRecord arg0) {
// // TODO Auto-generated method stub
// return name.compareTo(arg0.name);
// }
//
// }
//
// Path: src/main/java/org/aksw/TripleCheckMate/shared/exceptions/StorageServiceException.java
// public class StorageServiceException extends Exception implements
// Serializable {
//
// /**
// * Autogenerated for serialization
// */
// private static final long serialVersionUID = -1709522630145405589L;
//
// private String errorMessage;
//
// public StorageServiceException() {
// }
//
// public StorageServiceException(String message) {
// this.errorMessage = message;
// }
//
// public String getErrorMessage() {
// return this.errorMessage;
// }
//
// }
| import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import org.aksw.TripleCheckMate.shared.evaluate.UserRecord;
import org.aksw.TripleCheckMate.shared.exceptions.StorageServiceException;
import java.util.List; | /*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.client.requests;
@RemoteServiceRelativePath("UserRequest")
public interface UserRequest extends RemoteService { | // Path: src/main/java/org/aksw/TripleCheckMate/shared/evaluate/UserRecord.java
// public class UserRecord implements Comparable<UserRecord>, Serializable {
// /**
// * Auto-generated for serialization
// */
// private static final long serialVersionUID = 8871828625070002603L;
//
// public long userID = -1;
// public String googleID = "";
// public String name = "";
// public String picture = "";
// public String profile = "";
//
// public int recordCount = 0;
// public int errorCount = 0;
// public int distinctErrorCount = 0;
//
//
// public UserRecord() {
// }
//
// public UserRecord(long userID, String googleID, String name, String picture, String profile) {
// this.userID = userID;
// this.googleID = googleID;
// this.name = name;
// this.picture = picture;
// this.profile = profile;
// }
//
// public UserRecord(UserRecord u) {
// update(u);
// }
//
// public void update(UserRecord u) {
// this.userID = u.userID;
// this.googleID = u.googleID;
// this.name = u.name;
// this.picture = u.picture;
// this.profile = u.profile;
// this.recordCount = u.recordCount;
// this.errorCount = u.errorCount;
// this.distinctErrorCount = u.distinctErrorCount;
// }
//
// public void updateStatistics(int rc, int ec, int dc) {
// this.recordCount = rc;
// this.errorCount = ec;
// this.distinctErrorCount = dc;
// }
//
// public static final ProvidesKey<UserRecord> KEY_PROVIDER = new ProvidesKey<UserRecord>() {
// public Object getKey(UserRecord item) {
// return item == null ? null : item.userID;
// }
// };
//
// public String toHTMLString() {
// String img = (picture.equals("")) ? "" : "<img width=\"20\" height=\"20\" src=\"" + picture + "\" class =\"user-display-picture\"/>";
// return "<div class=\"user-display\">" + img + name + "</div>";
// }
//
// public int compareTo(UserRecord arg0) {
// // TODO Auto-generated method stub
// return name.compareTo(arg0.name);
// }
//
// }
//
// Path: src/main/java/org/aksw/TripleCheckMate/shared/exceptions/StorageServiceException.java
// public class StorageServiceException extends Exception implements
// Serializable {
//
// /**
// * Autogenerated for serialization
// */
// private static final long serialVersionUID = -1709522630145405589L;
//
// private String errorMessage;
//
// public StorageServiceException() {
// }
//
// public StorageServiceException(String message) {
// this.errorMessage = message;
// }
//
// public String getErrorMessage() {
// return this.errorMessage;
// }
//
// }
// Path: src/main/java/org/aksw/TripleCheckMate/client/requests/UserRequest.java
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import org.aksw.TripleCheckMate.shared.evaluate.UserRecord;
import org.aksw.TripleCheckMate.shared.exceptions.StorageServiceException;
import java.util.List;
/*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.client.requests;
@RemoteServiceRelativePath("UserRequest")
public interface UserRequest extends RemoteService { | public UserRecord getUserInfo(String userGoogleID) throws StorageServiceException; |
AKSW/TripleCheckMate | src/main/java/org/aksw/TripleCheckMate/shared/evaluate/EvaluateItem.java | // Path: src/main/java/org/aksw/TripleCheckMate/shared/sparql/ResultItem.java
// public class ResultItem implements Serializable {
// /**
// * Autogenerated for serialization
// */
// private static final long serialVersionUID = -2067749804344339633L;
// public String value = "";
// public String type = "";
// public String lang = "";
// public String datatype = "";
//
// public ResultItem() {
// }
//
// public ResultItem(String v, String t, String l, String d) {
// value = v;
// type = t;
// lang = l;
// datatype = d;
// }
//
// public String toString() {
// if (type.equalsIgnoreCase("literal"))
// return "\"" + value + "\" (@lang = " + lang + ")";
// if (type.equalsIgnoreCase("typed-literal"))
// return "\"" + value + "\" (@type = " + datatype + ")";
// return value;
// }
//
// public String toHTMLString() {
// if (type.equalsIgnoreCase("uri"))
// return "<a href=\"" + dereferenceURI(value) + "\" title=\"" + value + "\" target=\"_blank\">" + abbreviateURI(value) + "</a>";
// if (type.equalsIgnoreCase("literal"))
// return "\"" + value + "\" (@lang = " + lang + ")";
// if (type.equalsIgnoreCase("typed-literal"))
// return "\"" + value + "\" (@type = " + datatype + ")";
// return value;
// }
//
// private String abbreviateURI(String uri) {
// return PrefixService.getAbbeviatedForm(uri);
// }
//
// private String dereferenceURI(String uri) {
// return uri.replace("http://dbpedia.org/", "http://live.dbpedia.org/");
// }
// }
| import com.google.gwt.view.client.ProvidesKey;
import org.aksw.TripleCheckMate.shared.sparql.ResultItem;
import java.io.Serializable; | /*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.shared.evaluate;
public class EvaluateItem implements Comparable<EvaluateItem>, Serializable {
/**
* Auto-generated for serialization
*/
private static final long serialVersionUID = 147695789864172749L;
public long ID = 0; | // Path: src/main/java/org/aksw/TripleCheckMate/shared/sparql/ResultItem.java
// public class ResultItem implements Serializable {
// /**
// * Autogenerated for serialization
// */
// private static final long serialVersionUID = -2067749804344339633L;
// public String value = "";
// public String type = "";
// public String lang = "";
// public String datatype = "";
//
// public ResultItem() {
// }
//
// public ResultItem(String v, String t, String l, String d) {
// value = v;
// type = t;
// lang = l;
// datatype = d;
// }
//
// public String toString() {
// if (type.equalsIgnoreCase("literal"))
// return "\"" + value + "\" (@lang = " + lang + ")";
// if (type.equalsIgnoreCase("typed-literal"))
// return "\"" + value + "\" (@type = " + datatype + ")";
// return value;
// }
//
// public String toHTMLString() {
// if (type.equalsIgnoreCase("uri"))
// return "<a href=\"" + dereferenceURI(value) + "\" title=\"" + value + "\" target=\"_blank\">" + abbreviateURI(value) + "</a>";
// if (type.equalsIgnoreCase("literal"))
// return "\"" + value + "\" (@lang = " + lang + ")";
// if (type.equalsIgnoreCase("typed-literal"))
// return "\"" + value + "\" (@type = " + datatype + ")";
// return value;
// }
//
// private String abbreviateURI(String uri) {
// return PrefixService.getAbbeviatedForm(uri);
// }
//
// private String dereferenceURI(String uri) {
// return uri.replace("http://dbpedia.org/", "http://live.dbpedia.org/");
// }
// }
// Path: src/main/java/org/aksw/TripleCheckMate/shared/evaluate/EvaluateItem.java
import com.google.gwt.view.client.ProvidesKey;
import org.aksw.TripleCheckMate.shared.sparql.ResultItem;
import java.io.Serializable;
/*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.shared.evaluate;
public class EvaluateItem implements Comparable<EvaluateItem>, Serializable {
/**
* Auto-generated for serialization
*/
private static final long serialVersionUID = 147695789864172749L;
public long ID = 0; | public ResultItem S = null; |
AKSW/TripleCheckMate | src/main/java/org/aksw/TripleCheckMate/client/widgets/EvaluationTable.java | // Path: src/main/java/org/aksw/TripleCheckMate/shared/evaluate/EvaluateItem.java
// public class EvaluateItem implements Comparable<EvaluateItem>, Serializable {
// /**
// * Auto-generated for serialization
// */
// private static final long serialVersionUID = 147695789864172749L;
//
// public long ID = 0;
// public ResultItem S = null;
// public ResultItem P = null;
// public ResultItem O = null;
// public long errorType = 0;
// public String errorTittle = "";
// public String comments = "";
// public boolean isWrong = false;
//
//
// /**
// * The key provider that provides the unique ID of an Evaluate Item.
// */
// public static final ProvidesKey<EvaluateItem> KEY_PROVIDER = new ProvidesKey<EvaluateItem>() {
// public Object getKey(EvaluateItem item) {
// return item == null ? null : item.ID;
// }
// };
//
// public EvaluateItem() {
//
// }
//
// public EvaluateItem(long id, ResultItem s, ResultItem p, ResultItem o) {
// ID = id;
// S = s;
// P = p;
// O = o;
// isWrong = false;
// }
//
// public int compareTo(EvaluateItem item) {
// if (item == null)
// return -1;
// int cmpS = item.S.value.compareTo(S.value);
// if (cmpS != 0) return cmpS;
//
// int cmpP = item.S.value.compareTo(P.value);
// if (cmpP != 0) return cmpP;
//
// int cmpO = item.S.value.compareTo(O.value);
// if (cmpO != 0) return cmpO;
//
// return 0;
// }
// }
| import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.SafeHtmlCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.CellPreviewEvent;
import com.google.gwt.view.client.ListDataProvider;
import org.aksw.TripleCheckMate.shared.evaluate.EvaluateItem;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List; | /*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.client.widgets;
public class EvaluationTable extends Composite {
interface EvaluationTableUiBinder extends UiBinder<Widget, EvaluationTable> {
}
private static EvaluationTableUiBinder uiBinder = GWT.create(EvaluationTableUiBinder.class);
@UiField | // Path: src/main/java/org/aksw/TripleCheckMate/shared/evaluate/EvaluateItem.java
// public class EvaluateItem implements Comparable<EvaluateItem>, Serializable {
// /**
// * Auto-generated for serialization
// */
// private static final long serialVersionUID = 147695789864172749L;
//
// public long ID = 0;
// public ResultItem S = null;
// public ResultItem P = null;
// public ResultItem O = null;
// public long errorType = 0;
// public String errorTittle = "";
// public String comments = "";
// public boolean isWrong = false;
//
//
// /**
// * The key provider that provides the unique ID of an Evaluate Item.
// */
// public static final ProvidesKey<EvaluateItem> KEY_PROVIDER = new ProvidesKey<EvaluateItem>() {
// public Object getKey(EvaluateItem item) {
// return item == null ? null : item.ID;
// }
// };
//
// public EvaluateItem() {
//
// }
//
// public EvaluateItem(long id, ResultItem s, ResultItem p, ResultItem o) {
// ID = id;
// S = s;
// P = p;
// O = o;
// isWrong = false;
// }
//
// public int compareTo(EvaluateItem item) {
// if (item == null)
// return -1;
// int cmpS = item.S.value.compareTo(S.value);
// if (cmpS != 0) return cmpS;
//
// int cmpP = item.S.value.compareTo(P.value);
// if (cmpP != 0) return cmpP;
//
// int cmpO = item.S.value.compareTo(O.value);
// if (cmpO != 0) return cmpO;
//
// return 0;
// }
// }
// Path: src/main/java/org/aksw/TripleCheckMate/client/widgets/EvaluationTable.java
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.SafeHtmlCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.CellPreviewEvent;
import com.google.gwt.view.client.ListDataProvider;
import org.aksw.TripleCheckMate.shared.evaluate.EvaluateItem;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.client.widgets;
public class EvaluationTable extends Composite {
interface EvaluationTableUiBinder extends UiBinder<Widget, EvaluationTable> {
}
private static EvaluationTableUiBinder uiBinder = GWT.create(EvaluationTableUiBinder.class);
@UiField | CellTable<EvaluateItem> tblEvalTriples = new CellTable<EvaluateItem>( |
AKSW/TripleCheckMate | src/main/java/org/aksw/TripleCheckMate/client/widgets/UserSessionStatistics.java | // Path: src/main/java/org/aksw/TripleCheckMate/shared/evaluate/SessionContext.java
// public class SessionContext {
// private SessionContext() {
// }
//
// // User related
// public static UserRecord user = new UserRecord();
// public static long userSession = 0;
//
// // Evaluation
// public static int evaluationCampaign = 0;
// public static EvaluateResource latestEvaluateResource = new EvaluateResource();
// public static List<EvaluateResource> evaluations = new ArrayList<EvaluateResource>();
// // TODO get it with RPC
// public static Endpoint endpoint = new Endpoint(
// 0,
// "http://live.dbpedia.org/sparql",
// "http://dbpedia.org",
// "live.dbpedia.org/sparql");
//
// // Async RPC Requests
// public static EvaluationRequestAsync evaluationReqSrv = GWT
// .create(EvaluationRequest.class);
// public static UserRequestAsync userReqSrv = GWT.create(UserRequest.class);
//
// // GUI related
// public static DecoratedTabPanel tabPanel = new DecoratedTabPanel();
// public static EvaluationPage pageEval = new EvaluationPage();
// public static StartPage pageStart = new StartPage();
// public static LoadingPopup popup = new LoadingPopup();
//
// public static void showPopup() {
// popup.center();
// popup.show();
// }
//
// public static void hidePopup() {
// popup.hide();
// }
//
// public static void setNewEvaluation(String aboutURI,
// List<EvaluateItem> data, String classType) {
// if (!latestEvaluateResource.about.equals("")) {
// // Add evaluation history
// evaluations.add(new EvaluateResource(latestEvaluateResource));
// }
// latestEvaluateResource.updateContents(aboutURI, false, "",
// new ArrayList<EvaluateItem>(), classType);
// pageEval.setNewEvaluation(aboutURI, data);
// }
//
// public static boolean existsInSessionHistory(String resource) {
// if (latestEvaluateResource.about.equals(resource))
// return true;
// for (EvaluateResource r : evaluations)
// if (r.about.equals(resource))
// return true;
// return false;
// }
//
// public static void submitEvaluation(EvaluateResource e) {
//
// }
//
// public static void gotoEvaluationPage() {
// SessionContext.tabPanel.selectTab(1);
// pageEval.openSelectDialog();
// }
//
// public static String getUserProgressTxt() {
// int submitted = 0;
// int skipped = 0;
// for (EvaluateResource i : evaluations) {
// if (i.isSkipped == true)
// skipped++;
// else
// submitted++;
// }
// if (!latestEvaluateResource.about.equals(""))
// if (latestEvaluateResource.isSkipped == true)
// skipped++;
// else
// submitted++;
//
// return "<div class=\"user-progress\">" + user.toHTMLString()
// + "<div class=\"user-progress-item\">Submitted " + submitted
// + ", Skipped " + skipped + "</div></div>";
// }
//
// public static void finishEvaluation() {
// pageEval.finishEvaluation();
// pageStart.StartEvaluation();
// SessionContext.tabPanel.selectTab(0);
//
// }
//
// }
| import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import org.aksw.TripleCheckMate.shared.evaluate.SessionContext; | /*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.client.widgets;
public class UserSessionStatistics extends Composite {
private VerticalPanel bodyPanel = new VerticalPanel();
private final HTML txtUser = new HTML();
private final HTML txtSession = new HTML();
private final HTML txtAlltime = new HTML();
public UserSessionStatistics() {
super();
// All composites must call initWidget() in their constructors.
initWidget(bodyPanel);
bodyPanel.add(txtUser);
bodyPanel.add(txtSession);
bodyPanel.add(txtAlltime);
}
public void updateSession(int rcount, int scount, int ecount) { | // Path: src/main/java/org/aksw/TripleCheckMate/shared/evaluate/SessionContext.java
// public class SessionContext {
// private SessionContext() {
// }
//
// // User related
// public static UserRecord user = new UserRecord();
// public static long userSession = 0;
//
// // Evaluation
// public static int evaluationCampaign = 0;
// public static EvaluateResource latestEvaluateResource = new EvaluateResource();
// public static List<EvaluateResource> evaluations = new ArrayList<EvaluateResource>();
// // TODO get it with RPC
// public static Endpoint endpoint = new Endpoint(
// 0,
// "http://live.dbpedia.org/sparql",
// "http://dbpedia.org",
// "live.dbpedia.org/sparql");
//
// // Async RPC Requests
// public static EvaluationRequestAsync evaluationReqSrv = GWT
// .create(EvaluationRequest.class);
// public static UserRequestAsync userReqSrv = GWT.create(UserRequest.class);
//
// // GUI related
// public static DecoratedTabPanel tabPanel = new DecoratedTabPanel();
// public static EvaluationPage pageEval = new EvaluationPage();
// public static StartPage pageStart = new StartPage();
// public static LoadingPopup popup = new LoadingPopup();
//
// public static void showPopup() {
// popup.center();
// popup.show();
// }
//
// public static void hidePopup() {
// popup.hide();
// }
//
// public static void setNewEvaluation(String aboutURI,
// List<EvaluateItem> data, String classType) {
// if (!latestEvaluateResource.about.equals("")) {
// // Add evaluation history
// evaluations.add(new EvaluateResource(latestEvaluateResource));
// }
// latestEvaluateResource.updateContents(aboutURI, false, "",
// new ArrayList<EvaluateItem>(), classType);
// pageEval.setNewEvaluation(aboutURI, data);
// }
//
// public static boolean existsInSessionHistory(String resource) {
// if (latestEvaluateResource.about.equals(resource))
// return true;
// for (EvaluateResource r : evaluations)
// if (r.about.equals(resource))
// return true;
// return false;
// }
//
// public static void submitEvaluation(EvaluateResource e) {
//
// }
//
// public static void gotoEvaluationPage() {
// SessionContext.tabPanel.selectTab(1);
// pageEval.openSelectDialog();
// }
//
// public static String getUserProgressTxt() {
// int submitted = 0;
// int skipped = 0;
// for (EvaluateResource i : evaluations) {
// if (i.isSkipped == true)
// skipped++;
// else
// submitted++;
// }
// if (!latestEvaluateResource.about.equals(""))
// if (latestEvaluateResource.isSkipped == true)
// skipped++;
// else
// submitted++;
//
// return "<div class=\"user-progress\">" + user.toHTMLString()
// + "<div class=\"user-progress-item\">Submitted " + submitted
// + ", Skipped " + skipped + "</div></div>";
// }
//
// public static void finishEvaluation() {
// pageEval.finishEvaluation();
// pageStart.StartEvaluation();
// SessionContext.tabPanel.selectTab(0);
//
// }
//
// }
// Path: src/main/java/org/aksw/TripleCheckMate/client/widgets/UserSessionStatistics.java
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import org.aksw.TripleCheckMate.shared.evaluate.SessionContext;
/*******************************************************************************
* Copyright 2013 Agile Knowledge Engineering and Semantic Web (AKSW) Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.aksw.TripleCheckMate.client.widgets;
public class UserSessionStatistics extends Composite {
private VerticalPanel bodyPanel = new VerticalPanel();
private final HTML txtUser = new HTML();
private final HTML txtSession = new HTML();
private final HTML txtAlltime = new HTML();
public UserSessionStatistics() {
super();
// All composites must call initWidget() in their constructors.
initWidget(bodyPanel);
bodyPanel.add(txtUser);
bodyPanel.add(txtSession);
bodyPanel.add(txtAlltime);
}
public void updateSession(int rcount, int scount, int ecount) { | txtUser.setText(SessionContext.user.toHTMLString()); |
lhartikk/JunitQuest | src/test/java/org/tsers/junitquest/testgenerator/ArithmeticMethodsTest.java | // Path: src/main/java/org/tsers/junitquest/CallParam.java
// public class CallParam {
//
//
// private final Instance instance;
// private final int position;
//
// public CallParam(Instance instance, int position) {
// this.instance = instance;
// this.position = position;
// }
//
//
// public int getPosition() {
// return position;
// }
//
// public Instance getInstance() {
// return instance;
// }
//
// }
| import org.tsers.junitquest.CallParam;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertTrue; | package org.tsers.junitquest.testgenerator;
public class ArithmeticMethodsTest extends JunitQuestTest {
@Test
public void testArithmeticMethod() throws Exception { | // Path: src/main/java/org/tsers/junitquest/CallParam.java
// public class CallParam {
//
//
// private final Instance instance;
// private final int position;
//
// public CallParam(Instance instance, int position) {
// this.instance = instance;
// this.position = position;
// }
//
//
// public int getPosition() {
// return position;
// }
//
// public Instance getInstance() {
// return instance;
// }
//
// }
// Path: src/test/java/org/tsers/junitquest/testgenerator/ArithmeticMethodsTest.java
import org.tsers.junitquest.CallParam;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertTrue;
package org.tsers.junitquest.testgenerator;
public class ArithmeticMethodsTest extends JunitQuestTest {
@Test
public void testArithmeticMethod() throws Exception { | List<List<CallParam>> tests = generator.generateTests("org.tsers.junitquest.testmethods.ArithmeticMethods", "arithmeticMethod", "(I)V"); |
lhartikk/JunitQuest | src/main/java/org/tsers/junitquest/Instrumenter.java | // Path: src/main/java/org/tsers/junitquest/finder/MyClassWriter.java
// public class MyClassWriter extends ClassWriter {
// private ClassLoader classLoader;
//
// public MyClassWriter(int i, ClassLoader loader) {
// super(i);
// this.classLoader = loader;
// }
//
// @Override
// protected String getCommonSuperClass(final String type1, final String type2) {
// Class c, d;
// try {
// c = classLoader.loadClass(type1.replace('/', '.'));
// d = classLoader.loadClass(type2.replace('/', '.'));
// } catch (Exception e) {
// throw new RuntimeException(e.toString());
// }
// if (c.isAssignableFrom(d)) {
// return type1;
// }
// if (d.isAssignableFrom(c)) {
// return type2;
// }
// if (c.isInterface() || d.isInterface()) {
// return "java/lang/Object";
// } else {
// do {
// c = c.getSuperclass();
// } while (!c.isAssignableFrom(d));
// return c.getName().replace('.', '/');
// }
// }
// }
| import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.*;
import org.tsers.junitquest.finder.MyClassWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*; |
InstanceHelper.setClassLoader(urlClassLoader);
InstanceHelper.init(urlClassLoader, bytecodeLocation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static List<MethodNode> getMethodNodes() {
return methodNodes;
}
public static MethodNode getMethodNode(String packagename, String methodName, String methodDesc) {
MethodNode node = getMethodNodes().stream()
.filter(m -> m.name.equals(methodName) && m.desc.equals(methodDesc))
.findAny()
.orElseThrow(() -> new RuntimeException("Cannot find methodnode for: " + methodName));
return node;
}
private static byte[] getInstrumentedByteCode(InputStream classStream) throws IOException {
ClassReader classReader = new ClassReader(classStream);
ClassNode classNode = new ClassNode();
classReader.accept(classNode, 0);
methodNodes.addAll(classNode.methods);
((List<MethodNode>) classNode.methods).stream()
.forEach(m -> instrumentMethod(m));
ClassWriter classWriter; | // Path: src/main/java/org/tsers/junitquest/finder/MyClassWriter.java
// public class MyClassWriter extends ClassWriter {
// private ClassLoader classLoader;
//
// public MyClassWriter(int i, ClassLoader loader) {
// super(i);
// this.classLoader = loader;
// }
//
// @Override
// protected String getCommonSuperClass(final String type1, final String type2) {
// Class c, d;
// try {
// c = classLoader.loadClass(type1.replace('/', '.'));
// d = classLoader.loadClass(type2.replace('/', '.'));
// } catch (Exception e) {
// throw new RuntimeException(e.toString());
// }
// if (c.isAssignableFrom(d)) {
// return type1;
// }
// if (d.isAssignableFrom(c)) {
// return type2;
// }
// if (c.isInterface() || d.isInterface()) {
// return "java/lang/Object";
// } else {
// do {
// c = c.getSuperclass();
// } while (!c.isAssignableFrom(d));
// return c.getName().replace('.', '/');
// }
// }
// }
// Path: src/main/java/org/tsers/junitquest/Instrumenter.java
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.*;
import org.tsers.junitquest.finder.MyClassWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
InstanceHelper.setClassLoader(urlClassLoader);
InstanceHelper.init(urlClassLoader, bytecodeLocation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static List<MethodNode> getMethodNodes() {
return methodNodes;
}
public static MethodNode getMethodNode(String packagename, String methodName, String methodDesc) {
MethodNode node = getMethodNodes().stream()
.filter(m -> m.name.equals(methodName) && m.desc.equals(methodDesc))
.findAny()
.orElseThrow(() -> new RuntimeException("Cannot find methodnode for: " + methodName));
return node;
}
private static byte[] getInstrumentedByteCode(InputStream classStream) throws IOException {
ClassReader classReader = new ClassReader(classStream);
ClassNode classNode = new ClassNode();
classReader.accept(classNode, 0);
methodNodes.addAll(classNode.methods);
((List<MethodNode>) classNode.methods).stream()
.forEach(m -> instrumentMethod(m));
ClassWriter classWriter; | classWriter = new MyClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, urlClassLoader); |
lhartikk/JunitQuest | src/main/java/org/tsers/junitquest/InstanceHelper.java | // Path: src/main/java/org/tsers/junitquest/finder/JavaClassFinder.java
// public class JavaClassFinder {
// public static final String JAVA_CLASS_PATH_PROPERTY = "java.class.path";
// public static final String SUN_BOOT_CLASS_PATH = "sun.boot.class.path";
// private static final String RUNTIME_JAR_TO_SEARCH = File.separatorChar + "rt.jar";
// public final List<Class> runtimeClasses;
//
// private static String bytecodeDir;
// private static String runtimeJarLocation;
// private ClassLoader classLoader;
//
// public JavaClassFinder(ClassLoader loader, String bytecodeDir) {
// this.bytecodeDir = bytecodeDir;
// this.classLoader = loader;
//
// String runtimeJarLocation = getRuntimeLocation();
// runtimeClasses = solveFromRT(runtimeJarLocation);
// }
//
// public static void setRuntimeJarLocation(String runtimeJarLocation) {
// JavaClassFinder.runtimeJarLocation = runtimeJarLocation;
// }
//
// private static String getRuntimeLocation() {
//
// if (runtimeJarLocation == null) {
// Optional<String> runtimeJarLocation =
// getClassPathRoots(JAVA_CLASS_PATH_PROPERTY).stream()
// .filter(c -> c.endsWith(RUNTIME_JAR_TO_SEARCH))
// .findFirst();
// if (runtimeJarLocation.isPresent()) {
// return runtimeJarLocation.get();
// }
// String runtimeJarLocation2 =
// getClassPathRoots(SUN_BOOT_CLASS_PATH).stream()
// .filter(c -> c.endsWith(RUNTIME_JAR_TO_SEARCH))
// .findFirst().orElse("");
//
//
// return runtimeJarLocation2;
// }
// return runtimeJarLocation;
// }
//
// public List<Class> findAllMatchingTypes(Class toFind) {
//
//
// List<Class> foundClasses =
// runtimeClasses.stream()
// .filter(c -> toFind.isAssignableFrom(c))
// .collect(Collectors.toList());
//
// for (String classPathRoot : getClassPathRoots(JAVA_CLASS_PATH_PROPERTY)) {
// if (classPathRoot.endsWith(".jar")) {
// continue;
// }
//
// FileWalker fileWalker = new FileWalker(classPathRoot, classLoader, toFind);
// List<Class> matchedClasses = fileWalker.walk();
// foundClasses.addAll(matchedClasses);
// }
//
// return foundClasses;
// }
//
// private static List<Class> solveFromRT(String classPathRoot) {
//
// List<Class> classNames = new ArrayList<Class>();
// try {
//
// ZipInputStream zip = new ZipInputStream(new FileInputStream(classPathRoot));
// for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
// if (!entry.isDirectory() && entry.getName().endsWith(".class") && entry.getName().startsWith("java/")
// && !entry.getName().contains("$")) {
// String className = entry.getName().replace('/', '.');
// String n = className.substring(0, className.length() - ".class".length());
// classNames.add(Class.forName(n));
// }
// }
//
// } catch (Exception e) {
//
// }
// return classNames;
// }
//
//
// public static List<String> getClassPathRoots(String classPathProperty) {
// String classPath = System.getProperty(classPathProperty);
//
// classPath = classPath + File.pathSeparator + bytecodeDir;
// String[] pathElements = classPath.split(File.pathSeparator);
//
// return Arrays.asList(pathElements);
// }
//
// }
| import org.tsers.junitquest.finder.JavaClassFinder;
import java.lang.reflect.Array;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors; | package org.tsers.junitquest;
public class InstanceHelper {
static ClassLoader classLoader; | // Path: src/main/java/org/tsers/junitquest/finder/JavaClassFinder.java
// public class JavaClassFinder {
// public static final String JAVA_CLASS_PATH_PROPERTY = "java.class.path";
// public static final String SUN_BOOT_CLASS_PATH = "sun.boot.class.path";
// private static final String RUNTIME_JAR_TO_SEARCH = File.separatorChar + "rt.jar";
// public final List<Class> runtimeClasses;
//
// private static String bytecodeDir;
// private static String runtimeJarLocation;
// private ClassLoader classLoader;
//
// public JavaClassFinder(ClassLoader loader, String bytecodeDir) {
// this.bytecodeDir = bytecodeDir;
// this.classLoader = loader;
//
// String runtimeJarLocation = getRuntimeLocation();
// runtimeClasses = solveFromRT(runtimeJarLocation);
// }
//
// public static void setRuntimeJarLocation(String runtimeJarLocation) {
// JavaClassFinder.runtimeJarLocation = runtimeJarLocation;
// }
//
// private static String getRuntimeLocation() {
//
// if (runtimeJarLocation == null) {
// Optional<String> runtimeJarLocation =
// getClassPathRoots(JAVA_CLASS_PATH_PROPERTY).stream()
// .filter(c -> c.endsWith(RUNTIME_JAR_TO_SEARCH))
// .findFirst();
// if (runtimeJarLocation.isPresent()) {
// return runtimeJarLocation.get();
// }
// String runtimeJarLocation2 =
// getClassPathRoots(SUN_BOOT_CLASS_PATH).stream()
// .filter(c -> c.endsWith(RUNTIME_JAR_TO_SEARCH))
// .findFirst().orElse("");
//
//
// return runtimeJarLocation2;
// }
// return runtimeJarLocation;
// }
//
// public List<Class> findAllMatchingTypes(Class toFind) {
//
//
// List<Class> foundClasses =
// runtimeClasses.stream()
// .filter(c -> toFind.isAssignableFrom(c))
// .collect(Collectors.toList());
//
// for (String classPathRoot : getClassPathRoots(JAVA_CLASS_PATH_PROPERTY)) {
// if (classPathRoot.endsWith(".jar")) {
// continue;
// }
//
// FileWalker fileWalker = new FileWalker(classPathRoot, classLoader, toFind);
// List<Class> matchedClasses = fileWalker.walk();
// foundClasses.addAll(matchedClasses);
// }
//
// return foundClasses;
// }
//
// private static List<Class> solveFromRT(String classPathRoot) {
//
// List<Class> classNames = new ArrayList<Class>();
// try {
//
// ZipInputStream zip = new ZipInputStream(new FileInputStream(classPathRoot));
// for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
// if (!entry.isDirectory() && entry.getName().endsWith(".class") && entry.getName().startsWith("java/")
// && !entry.getName().contains("$")) {
// String className = entry.getName().replace('/', '.');
// String n = className.substring(0, className.length() - ".class".length());
// classNames.add(Class.forName(n));
// }
// }
//
// } catch (Exception e) {
//
// }
// return classNames;
// }
//
//
// public static List<String> getClassPathRoots(String classPathProperty) {
// String classPath = System.getProperty(classPathProperty);
//
// classPath = classPath + File.pathSeparator + bytecodeDir;
// String[] pathElements = classPath.split(File.pathSeparator);
//
// return Arrays.asList(pathElements);
// }
//
// }
// Path: src/main/java/org/tsers/junitquest/InstanceHelper.java
import org.tsers.junitquest.finder.JavaClassFinder;
import java.lang.reflect.Array;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
package org.tsers.junitquest;
public class InstanceHelper {
static ClassLoader classLoader; | final JavaClassFinder classFinder; |
lhartikk/JunitQuest | src/test/java/org/tsers/junitquest/solver/LogicalSolverTest.java | // Path: src/main/java/org/tsers/junitquest/expr/AddNode.java
// public class AddNode extends ExprNode {
//
// public AddNode(List<ExprNode> children) {
// super(children);
// }
//
// @Override
// public ExprNode copy(List<ExprNode> newchildren) {
// return new AddNode(newchildren);
// }
//
// @Override
// public boolean equals(ExprNode exprNode) {
// if (exprNode.getClass().equals(this.getClass())) {
// return childrenEquals(exprNode.getChildren());
// }
// return false;
// }
// }
//
// Path: src/main/java/org/tsers/junitquest/expr/AndNode.java
// public class AndNode extends ExprNode {
//
// public AndNode(List<ExprNode> children) {
// super(children);
// }
//
// @Override
// public ExprNode copy(List<ExprNode> newchildren) {
// return new AndNode(newchildren);
// }
//
// @Override
// public boolean equals(ExprNode exprNode) {
// if (exprNode.getClass().equals(this.getClass())) {
// return childrenEquals(exprNode.getChildren());
// }
// return false;
// }
//
// }
//
// Path: src/main/java/org/tsers/junitquest/expr/ExprNode.java
// public abstract class ExprNode {
//
// private final List<ExprNode> children;
//
// public ExprNode(List<ExprNode> children) {
// this.children = children;
// }
//
// public List<ExprNode> getChildren() {
// return children;
// }
//
// abstract public ExprNode copy(List<ExprNode> newchildren);
//
// abstract public boolean equals(ExprNode exprNode);
//
// public boolean childrenEquals(List<ExprNode> otherChildren) {
// if (otherChildren.size() != children.size()) {
// return false;
// }
// for (int i = 0; i < children.size(); i++) {
// ExprNode a = children.get(i);
// ExprNode b = otherChildren.get(i);
// if (!a.equals(b)) {
// return false;
// }
// }
// return true;
// }
//
// }
//
// Path: src/main/java/org/tsers/junitquest/expr/IntNode.java
// public class IntNode extends ConstantNode {
//
// final int value;
//
// public IntNode(int value) {
// super();
// this.value = value;
// }
//
// public int getValue() {
// return this.value;
// }
//
// @Override
// public ExprNode copy(List<ExprNode> newchildren) {
// return new IntNode(value);
// }
//
// @Override
// public boolean equals(ExprNode exprNode) {
// if (exprNode.getClass().equals(this.getClass())) {
// return ((IntNode) exprNode).getValue() == value;
// }
// return false;
// }
//
// }
| import org.tsers.junitquest.expr.AddNode;
import org.tsers.junitquest.expr.AndNode;
import org.tsers.junitquest.expr.ExprNode;
import org.tsers.junitquest.expr.IntNode;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals; | package org.tsers.junitquest.solver;
public class LogicalSolverTest {
ExprNode baseAnd = new AndNode( | // Path: src/main/java/org/tsers/junitquest/expr/AddNode.java
// public class AddNode extends ExprNode {
//
// public AddNode(List<ExprNode> children) {
// super(children);
// }
//
// @Override
// public ExprNode copy(List<ExprNode> newchildren) {
// return new AddNode(newchildren);
// }
//
// @Override
// public boolean equals(ExprNode exprNode) {
// if (exprNode.getClass().equals(this.getClass())) {
// return childrenEquals(exprNode.getChildren());
// }
// return false;
// }
// }
//
// Path: src/main/java/org/tsers/junitquest/expr/AndNode.java
// public class AndNode extends ExprNode {
//
// public AndNode(List<ExprNode> children) {
// super(children);
// }
//
// @Override
// public ExprNode copy(List<ExprNode> newchildren) {
// return new AndNode(newchildren);
// }
//
// @Override
// public boolean equals(ExprNode exprNode) {
// if (exprNode.getClass().equals(this.getClass())) {
// return childrenEquals(exprNode.getChildren());
// }
// return false;
// }
//
// }
//
// Path: src/main/java/org/tsers/junitquest/expr/ExprNode.java
// public abstract class ExprNode {
//
// private final List<ExprNode> children;
//
// public ExprNode(List<ExprNode> children) {
// this.children = children;
// }
//
// public List<ExprNode> getChildren() {
// return children;
// }
//
// abstract public ExprNode copy(List<ExprNode> newchildren);
//
// abstract public boolean equals(ExprNode exprNode);
//
// public boolean childrenEquals(List<ExprNode> otherChildren) {
// if (otherChildren.size() != children.size()) {
// return false;
// }
// for (int i = 0; i < children.size(); i++) {
// ExprNode a = children.get(i);
// ExprNode b = otherChildren.get(i);
// if (!a.equals(b)) {
// return false;
// }
// }
// return true;
// }
//
// }
//
// Path: src/main/java/org/tsers/junitquest/expr/IntNode.java
// public class IntNode extends ConstantNode {
//
// final int value;
//
// public IntNode(int value) {
// super();
// this.value = value;
// }
//
// public int getValue() {
// return this.value;
// }
//
// @Override
// public ExprNode copy(List<ExprNode> newchildren) {
// return new IntNode(value);
// }
//
// @Override
// public boolean equals(ExprNode exprNode) {
// if (exprNode.getClass().equals(this.getClass())) {
// return ((IntNode) exprNode).getValue() == value;
// }
// return false;
// }
//
// }
// Path: src/test/java/org/tsers/junitquest/solver/LogicalSolverTest.java
import org.tsers.junitquest.expr.AddNode;
import org.tsers.junitquest.expr.AndNode;
import org.tsers.junitquest.expr.ExprNode;
import org.tsers.junitquest.expr.IntNode;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
package org.tsers.junitquest.solver;
public class LogicalSolverTest {
ExprNode baseAnd = new AndNode( | Arrays.asList(new IntNode(555), new IntNode(666)) |
lhartikk/JunitQuest | src/test/java/org/tsers/junitquest/solver/LogicalSolverTest.java | // Path: src/main/java/org/tsers/junitquest/expr/AddNode.java
// public class AddNode extends ExprNode {
//
// public AddNode(List<ExprNode> children) {
// super(children);
// }
//
// @Override
// public ExprNode copy(List<ExprNode> newchildren) {
// return new AddNode(newchildren);
// }
//
// @Override
// public boolean equals(ExprNode exprNode) {
// if (exprNode.getClass().equals(this.getClass())) {
// return childrenEquals(exprNode.getChildren());
// }
// return false;
// }
// }
//
// Path: src/main/java/org/tsers/junitquest/expr/AndNode.java
// public class AndNode extends ExprNode {
//
// public AndNode(List<ExprNode> children) {
// super(children);
// }
//
// @Override
// public ExprNode copy(List<ExprNode> newchildren) {
// return new AndNode(newchildren);
// }
//
// @Override
// public boolean equals(ExprNode exprNode) {
// if (exprNode.getClass().equals(this.getClass())) {
// return childrenEquals(exprNode.getChildren());
// }
// return false;
// }
//
// }
//
// Path: src/main/java/org/tsers/junitquest/expr/ExprNode.java
// public abstract class ExprNode {
//
// private final List<ExprNode> children;
//
// public ExprNode(List<ExprNode> children) {
// this.children = children;
// }
//
// public List<ExprNode> getChildren() {
// return children;
// }
//
// abstract public ExprNode copy(List<ExprNode> newchildren);
//
// abstract public boolean equals(ExprNode exprNode);
//
// public boolean childrenEquals(List<ExprNode> otherChildren) {
// if (otherChildren.size() != children.size()) {
// return false;
// }
// for (int i = 0; i < children.size(); i++) {
// ExprNode a = children.get(i);
// ExprNode b = otherChildren.get(i);
// if (!a.equals(b)) {
// return false;
// }
// }
// return true;
// }
//
// }
//
// Path: src/main/java/org/tsers/junitquest/expr/IntNode.java
// public class IntNode extends ConstantNode {
//
// final int value;
//
// public IntNode(int value) {
// super();
// this.value = value;
// }
//
// public int getValue() {
// return this.value;
// }
//
// @Override
// public ExprNode copy(List<ExprNode> newchildren) {
// return new IntNode(value);
// }
//
// @Override
// public boolean equals(ExprNode exprNode) {
// if (exprNode.getClass().equals(this.getClass())) {
// return ((IntNode) exprNode).getValue() == value;
// }
// return false;
// }
//
// }
| import org.tsers.junitquest.expr.AddNode;
import org.tsers.junitquest.expr.AndNode;
import org.tsers.junitquest.expr.ExprNode;
import org.tsers.junitquest.expr.IntNode;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals; | public void testcombineANDs2() {
ExprNode andNode = new AndNode(Arrays.asList(
new AndNode(
Arrays.asList(baseAnd)
)));
ExprNode newAndNode = LogicalSolver.combineANDs.apply(andNode);
assertEquals(2, newAndNode.getChildren().size());
}
@Test
public void testcombineANDs3() {
ExprNode andNode = new AndNode(Arrays.asList(
new AndNode(
Arrays.asList(
new AndNode(
Arrays.asList(new AndNode(Arrays.asList(baseAnd)))
))
)));
ExprNode newAndNode = LogicalSolver.combineANDs.apply(andNode);
assertEquals(2, newAndNode.getChildren().size());
}
@Test
public void testCombineADDS() {
| // Path: src/main/java/org/tsers/junitquest/expr/AddNode.java
// public class AddNode extends ExprNode {
//
// public AddNode(List<ExprNode> children) {
// super(children);
// }
//
// @Override
// public ExprNode copy(List<ExprNode> newchildren) {
// return new AddNode(newchildren);
// }
//
// @Override
// public boolean equals(ExprNode exprNode) {
// if (exprNode.getClass().equals(this.getClass())) {
// return childrenEquals(exprNode.getChildren());
// }
// return false;
// }
// }
//
// Path: src/main/java/org/tsers/junitquest/expr/AndNode.java
// public class AndNode extends ExprNode {
//
// public AndNode(List<ExprNode> children) {
// super(children);
// }
//
// @Override
// public ExprNode copy(List<ExprNode> newchildren) {
// return new AndNode(newchildren);
// }
//
// @Override
// public boolean equals(ExprNode exprNode) {
// if (exprNode.getClass().equals(this.getClass())) {
// return childrenEquals(exprNode.getChildren());
// }
// return false;
// }
//
// }
//
// Path: src/main/java/org/tsers/junitquest/expr/ExprNode.java
// public abstract class ExprNode {
//
// private final List<ExprNode> children;
//
// public ExprNode(List<ExprNode> children) {
// this.children = children;
// }
//
// public List<ExprNode> getChildren() {
// return children;
// }
//
// abstract public ExprNode copy(List<ExprNode> newchildren);
//
// abstract public boolean equals(ExprNode exprNode);
//
// public boolean childrenEquals(List<ExprNode> otherChildren) {
// if (otherChildren.size() != children.size()) {
// return false;
// }
// for (int i = 0; i < children.size(); i++) {
// ExprNode a = children.get(i);
// ExprNode b = otherChildren.get(i);
// if (!a.equals(b)) {
// return false;
// }
// }
// return true;
// }
//
// }
//
// Path: src/main/java/org/tsers/junitquest/expr/IntNode.java
// public class IntNode extends ConstantNode {
//
// final int value;
//
// public IntNode(int value) {
// super();
// this.value = value;
// }
//
// public int getValue() {
// return this.value;
// }
//
// @Override
// public ExprNode copy(List<ExprNode> newchildren) {
// return new IntNode(value);
// }
//
// @Override
// public boolean equals(ExprNode exprNode) {
// if (exprNode.getClass().equals(this.getClass())) {
// return ((IntNode) exprNode).getValue() == value;
// }
// return false;
// }
//
// }
// Path: src/test/java/org/tsers/junitquest/solver/LogicalSolverTest.java
import org.tsers.junitquest.expr.AddNode;
import org.tsers.junitquest.expr.AndNode;
import org.tsers.junitquest.expr.ExprNode;
import org.tsers.junitquest.expr.IntNode;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
public void testcombineANDs2() {
ExprNode andNode = new AndNode(Arrays.asList(
new AndNode(
Arrays.asList(baseAnd)
)));
ExprNode newAndNode = LogicalSolver.combineANDs.apply(andNode);
assertEquals(2, newAndNode.getChildren().size());
}
@Test
public void testcombineANDs3() {
ExprNode andNode = new AndNode(Arrays.asList(
new AndNode(
Arrays.asList(
new AndNode(
Arrays.asList(new AndNode(Arrays.asList(baseAnd)))
))
)));
ExprNode newAndNode = LogicalSolver.combineANDs.apply(andNode);
assertEquals(2, newAndNode.getChildren().size());
}
@Test
public void testCombineADDS() {
| ExprNode addNode = new AddNode(Arrays.asList( |
lhartikk/JunitQuest | src/main/java/org/tsers/junitquest/ConcolerInput.java | // Path: src/main/java/org/tsers/junitquest/expr/ExprNode.java
// public abstract class ExprNode {
//
// private final List<ExprNode> children;
//
// public ExprNode(List<ExprNode> children) {
// this.children = children;
// }
//
// public List<ExprNode> getChildren() {
// return children;
// }
//
// abstract public ExprNode copy(List<ExprNode> newchildren);
//
// abstract public boolean equals(ExprNode exprNode);
//
// public boolean childrenEquals(List<ExprNode> otherChildren) {
// if (otherChildren.size() != children.size()) {
// return false;
// }
// for (int i = 0; i < children.size(); i++) {
// ExprNode a = children.get(i);
// ExprNode b = otherChildren.get(i);
// if (!a.equals(b)) {
// return false;
// }
// }
// return true;
// }
//
// }
| import org.tsers.junitquest.expr.ExprNode; | package org.tsers.junitquest;
public class ConcolerInput {
final ExecutionPath executionPath; | // Path: src/main/java/org/tsers/junitquest/expr/ExprNode.java
// public abstract class ExprNode {
//
// private final List<ExprNode> children;
//
// public ExprNode(List<ExprNode> children) {
// this.children = children;
// }
//
// public List<ExprNode> getChildren() {
// return children;
// }
//
// abstract public ExprNode copy(List<ExprNode> newchildren);
//
// abstract public boolean equals(ExprNode exprNode);
//
// public boolean childrenEquals(List<ExprNode> otherChildren) {
// if (otherChildren.size() != children.size()) {
// return false;
// }
// for (int i = 0; i < children.size(); i++) {
// ExprNode a = children.get(i);
// ExprNode b = otherChildren.get(i);
// if (!a.equals(b)) {
// return false;
// }
// }
// return true;
// }
//
// }
// Path: src/main/java/org/tsers/junitquest/ConcolerInput.java
import org.tsers.junitquest.expr.ExprNode;
package org.tsers.junitquest;
public class ConcolerInput {
final ExecutionPath executionPath; | final ExprNode node; |
bulenkov/Darcula | demo/swingset3/com/sun/swingset3/demos/frame/FrameDemo.java | // Path: demo/swingset3/com/sun/swingset3/demos/DemoUtilities.java
// public class DemoUtilities {
// private DemoUtilities() {
// // Hide constructor
// }
//
// public static void setToplevelLocation(Window toplevel, Component component,
// int relativePosition) {
//
// Rectangle compBounds = component.getBounds();
//
// // Convert component location to screen coordinates
// Point p = new Point();
// SwingUtilities.convertPointToScreen(p, component);
//
// int x;
// int y;
//
// // Set frame location to be centered on panel
// switch (relativePosition) {
// case SwingConstants.NORTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.EAST: {
// x = p.x + compBounds.width;
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.SOUTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.WEST: {
// x = p.x - toplevel.getWidth();
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.NORTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.NORTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.SOUTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.SOUTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y + compBounds.height;
// break;
// }
// default:
// case SwingConstants.CENTER: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// }
// }
// toplevel.setLocation(x, y);
// }
//
// public static boolean browse(URI uri) throws IOException {
// // Try using the Desktop api first
// try {
// Desktop desktop = Desktop.getDesktop();
// desktop.browse(uri);
//
// return true;
// } catch (SecurityException e) {
// }
//
// return false;
// }
// }
| import com.bulenkov.iconloader.util.DoubleColor;
import com.sun.swingset3.DemoProperties;
import com.sun.swingset3.demos.DemoUtilities;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL; | //<snip>Add a horizontal toolbar
JToolBar toolbar = new JToolBar();
frame.add(toolbar, BorderLayout.NORTH);
toolbar.add(new JButton("Toolbar Button"));
//</snip>
//<snip>Add the content area
JLabel label = new JLabel("I'm content but a little blue.");
label.setHorizontalAlignment(JLabel.CENTER);
label.setPreferredSize(new Dimension(300, 160));
label.setBackground(new DoubleColor(new Color(197, 216, 236), new Color(102, 117, 136)));
label.setOpaque(true); // labels non-opaque by default
frame.add(label);
//snip
//<snip>Add a statusbar
JLabel statusLabel = new JLabel("I show status.");
statusLabel.setBorder(new EmptyBorder(4, 4, 4, 4));
statusLabel.setHorizontalAlignment(JLabel.LEADING);
frame.add(statusLabel, BorderLayout.SOUTH);
//</snip>
//<snip>Initialize frame's size to fit it's content
frame.pack();
//</snip>
return frame;
}
public void start() { | // Path: demo/swingset3/com/sun/swingset3/demos/DemoUtilities.java
// public class DemoUtilities {
// private DemoUtilities() {
// // Hide constructor
// }
//
// public static void setToplevelLocation(Window toplevel, Component component,
// int relativePosition) {
//
// Rectangle compBounds = component.getBounds();
//
// // Convert component location to screen coordinates
// Point p = new Point();
// SwingUtilities.convertPointToScreen(p, component);
//
// int x;
// int y;
//
// // Set frame location to be centered on panel
// switch (relativePosition) {
// case SwingConstants.NORTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.EAST: {
// x = p.x + compBounds.width;
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.SOUTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.WEST: {
// x = p.x - toplevel.getWidth();
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.NORTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.NORTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.SOUTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.SOUTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y + compBounds.height;
// break;
// }
// default:
// case SwingConstants.CENTER: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// }
// }
// toplevel.setLocation(x, y);
// }
//
// public static boolean browse(URI uri) throws IOException {
// // Try using the Desktop api first
// try {
// Desktop desktop = Desktop.getDesktop();
// desktop.browse(uri);
//
// return true;
// } catch (SecurityException e) {
// }
//
// return false;
// }
// }
// Path: demo/swingset3/com/sun/swingset3/demos/frame/FrameDemo.java
import com.bulenkov.iconloader.util.DoubleColor;
import com.sun.swingset3.DemoProperties;
import com.sun.swingset3.demos.DemoUtilities;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
//<snip>Add a horizontal toolbar
JToolBar toolbar = new JToolBar();
frame.add(toolbar, BorderLayout.NORTH);
toolbar.add(new JButton("Toolbar Button"));
//</snip>
//<snip>Add the content area
JLabel label = new JLabel("I'm content but a little blue.");
label.setHorizontalAlignment(JLabel.CENTER);
label.setPreferredSize(new Dimension(300, 160));
label.setBackground(new DoubleColor(new Color(197, 216, 236), new Color(102, 117, 136)));
label.setOpaque(true); // labels non-opaque by default
frame.add(label);
//snip
//<snip>Add a statusbar
JLabel statusLabel = new JLabel("I show status.");
statusLabel.setBorder(new EmptyBorder(4, 4, 4, 4));
statusLabel.setHorizontalAlignment(JLabel.LEADING);
frame.add(statusLabel, BorderLayout.SOUTH);
//</snip>
//<snip>Initialize frame's size to fit it's content
frame.pack();
//</snip>
return frame;
}
public void start() { | DemoUtilities.setToplevelLocation(frame, frameSpaceholder, SwingConstants.CENTER); |
bulenkov/Darcula | demo/swingset3/com/sun/swingset3/demos/window/WindowDemo.java | // Path: demo/swingset3/com/sun/swingset3/demos/DemoUtilities.java
// public class DemoUtilities {
// private DemoUtilities() {
// // Hide constructor
// }
//
// public static void setToplevelLocation(Window toplevel, Component component,
// int relativePosition) {
//
// Rectangle compBounds = component.getBounds();
//
// // Convert component location to screen coordinates
// Point p = new Point();
// SwingUtilities.convertPointToScreen(p, component);
//
// int x;
// int y;
//
// // Set frame location to be centered on panel
// switch (relativePosition) {
// case SwingConstants.NORTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.EAST: {
// x = p.x + compBounds.width;
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.SOUTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.WEST: {
// x = p.x - toplevel.getWidth();
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.NORTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.NORTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.SOUTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.SOUTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y + compBounds.height;
// break;
// }
// default:
// case SwingConstants.CENTER: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// }
// }
// toplevel.setLocation(x, y);
// }
//
// public static boolean browse(URI uri) throws IOException {
// // Try using the Desktop api first
// try {
// Desktop desktop = Desktop.getDesktop();
// desktop.browse(uri);
//
// return true;
// } catch (SecurityException e) {
// }
//
// return false;
// }
// }
| import com.sun.swingset3.DemoProperties;
import com.sun.swingset3.demos.DemoUtilities;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; |
return windowPlaceholder;
}
private static JWindow createWindow() {
//<snip>Create window
JWindow window = new JWindow();
//</snip>
//<snip>Add a border to the window
window.getRootPane().setBorder(new LineBorder(Color.BLACK, 1));
//</snip>
//<snip>Add window's content
JLabel label = new JLabel("I have no system border.");
label.setHorizontalAlignment(JLabel.CENTER);
label.setPreferredSize(new Dimension(250, 200));
window.add(label);
//</snip>
//<snip>Initialize window's size
// which will shrink-to-fit its contents
window.pack();
//</snip>
return window;
}
public void start() { | // Path: demo/swingset3/com/sun/swingset3/demos/DemoUtilities.java
// public class DemoUtilities {
// private DemoUtilities() {
// // Hide constructor
// }
//
// public static void setToplevelLocation(Window toplevel, Component component,
// int relativePosition) {
//
// Rectangle compBounds = component.getBounds();
//
// // Convert component location to screen coordinates
// Point p = new Point();
// SwingUtilities.convertPointToScreen(p, component);
//
// int x;
// int y;
//
// // Set frame location to be centered on panel
// switch (relativePosition) {
// case SwingConstants.NORTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.EAST: {
// x = p.x + compBounds.width;
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.SOUTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.WEST: {
// x = p.x - toplevel.getWidth();
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.NORTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.NORTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.SOUTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.SOUTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y + compBounds.height;
// break;
// }
// default:
// case SwingConstants.CENTER: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// }
// }
// toplevel.setLocation(x, y);
// }
//
// public static boolean browse(URI uri) throws IOException {
// // Try using the Desktop api first
// try {
// Desktop desktop = Desktop.getDesktop();
// desktop.browse(uri);
//
// return true;
// } catch (SecurityException e) {
// }
//
// return false;
// }
// }
// Path: demo/swingset3/com/sun/swingset3/demos/window/WindowDemo.java
import com.sun.swingset3.DemoProperties;
import com.sun.swingset3.demos.DemoUtilities;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
return windowPlaceholder;
}
private static JWindow createWindow() {
//<snip>Create window
JWindow window = new JWindow();
//</snip>
//<snip>Add a border to the window
window.getRootPane().setBorder(new LineBorder(Color.BLACK, 1));
//</snip>
//<snip>Add window's content
JLabel label = new JLabel("I have no system border.");
label.setHorizontalAlignment(JLabel.CENTER);
label.setPreferredSize(new Dimension(250, 200));
window.add(label);
//</snip>
//<snip>Initialize window's size
// which will shrink-to-fit its contents
window.pack();
//</snip>
return window;
}
public void start() { | DemoUtilities.setToplevelLocation(window, windowSpaceholder, SwingConstants.CENTER); |
bulenkov/Darcula | demo/swingset3/com/sun/swingset3/utilities/HTMLPanel.java | // Path: demo/swingset3/com/sun/swingset3/demos/DemoUtilities.java
// public class DemoUtilities {
// private DemoUtilities() {
// // Hide constructor
// }
//
// public static void setToplevelLocation(Window toplevel, Component component,
// int relativePosition) {
//
// Rectangle compBounds = component.getBounds();
//
// // Convert component location to screen coordinates
// Point p = new Point();
// SwingUtilities.convertPointToScreen(p, component);
//
// int x;
// int y;
//
// // Set frame location to be centered on panel
// switch (relativePosition) {
// case SwingConstants.NORTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.EAST: {
// x = p.x + compBounds.width;
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.SOUTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.WEST: {
// x = p.x - toplevel.getWidth();
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.NORTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.NORTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.SOUTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.SOUTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y + compBounds.height;
// break;
// }
// default:
// case SwingConstants.CENTER: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// }
// }
// toplevel.setLocation(x, y);
// }
//
// public static boolean browse(URI uri) throws IOException {
// // Try using the Desktop api first
// try {
// Desktop desktop = Desktop.getDesktop();
// desktop.browse(uri);
//
// return true;
// } catch (SecurityException e) {
// }
//
// return false;
// }
// }
| import com.sun.swingset3.demos.DemoUtilities;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.*;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.ObjectView;
import java.awt.*;
import java.util.EventListener; | final Component component = super.createComponent();
Runnable notifier = new Runnable() {
public void run() {
final ComponentCreationListener listeners[] =
HTMLPanel.this.listenerList.getListeners(ComponentCreationListener.class);
for (ComponentCreationListener l : listeners) {
l.componentCreated(HTMLPanel.this, component);
}
}
};
// just in case document is being loaded in separate thread. (?)
if (EventQueue.isDispatchThread()) {
notifier.run();
} else {
EventQueue.invokeLater(notifier);
}
return component;
}
}
// single instance of handler is shared for ALL DemoPanel instances
public static class HyperlinkHandler implements HyperlinkListener {
Cursor defaultCursor;
public void hyperlinkUpdate(HyperlinkEvent event) {
JEditorPane descriptionPane = (JEditorPane) event.getSource();
HyperlinkEvent.EventType type = event.getEventType();
if (type == HyperlinkEvent.EventType.ACTIVATED) {
try { | // Path: demo/swingset3/com/sun/swingset3/demos/DemoUtilities.java
// public class DemoUtilities {
// private DemoUtilities() {
// // Hide constructor
// }
//
// public static void setToplevelLocation(Window toplevel, Component component,
// int relativePosition) {
//
// Rectangle compBounds = component.getBounds();
//
// // Convert component location to screen coordinates
// Point p = new Point();
// SwingUtilities.convertPointToScreen(p, component);
//
// int x;
// int y;
//
// // Set frame location to be centered on panel
// switch (relativePosition) {
// case SwingConstants.NORTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.EAST: {
// x = p.x + compBounds.width;
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.SOUTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.WEST: {
// x = p.x - toplevel.getWidth();
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.NORTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.NORTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.SOUTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.SOUTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y + compBounds.height;
// break;
// }
// default:
// case SwingConstants.CENTER: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// }
// }
// toplevel.setLocation(x, y);
// }
//
// public static boolean browse(URI uri) throws IOException {
// // Try using the Desktop api first
// try {
// Desktop desktop = Desktop.getDesktop();
// desktop.browse(uri);
//
// return true;
// } catch (SecurityException e) {
// }
//
// return false;
// }
// }
// Path: demo/swingset3/com/sun/swingset3/utilities/HTMLPanel.java
import com.sun.swingset3.demos.DemoUtilities;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.*;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.ObjectView;
import java.awt.*;
import java.util.EventListener;
final Component component = super.createComponent();
Runnable notifier = new Runnable() {
public void run() {
final ComponentCreationListener listeners[] =
HTMLPanel.this.listenerList.getListeners(ComponentCreationListener.class);
for (ComponentCreationListener l : listeners) {
l.componentCreated(HTMLPanel.this, component);
}
}
};
// just in case document is being loaded in separate thread. (?)
if (EventQueue.isDispatchThread()) {
notifier.run();
} else {
EventQueue.invokeLater(notifier);
}
return component;
}
}
// single instance of handler is shared for ALL DemoPanel instances
public static class HyperlinkHandler implements HyperlinkListener {
Cursor defaultCursor;
public void hyperlinkUpdate(HyperlinkEvent event) {
JEditorPane descriptionPane = (JEditorPane) event.getSource();
HyperlinkEvent.EventType type = event.getEventType();
if (type == HyperlinkEvent.EventType.ACTIVATED) {
try { | DemoUtilities.browse(event.getURL().toURI()); |
bulenkov/Darcula | demo/swingset3/com/sun/swingset3/demos/dialog/DialogDemo.java | // Path: demo/swingset3/com/sun/swingset3/demos/DemoUtilities.java
// public class DemoUtilities {
// private DemoUtilities() {
// // Hide constructor
// }
//
// public static void setToplevelLocation(Window toplevel, Component component,
// int relativePosition) {
//
// Rectangle compBounds = component.getBounds();
//
// // Convert component location to screen coordinates
// Point p = new Point();
// SwingUtilities.convertPointToScreen(p, component);
//
// int x;
// int y;
//
// // Set frame location to be centered on panel
// switch (relativePosition) {
// case SwingConstants.NORTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.EAST: {
// x = p.x + compBounds.width;
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.SOUTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.WEST: {
// x = p.x - toplevel.getWidth();
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.NORTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.NORTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.SOUTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.SOUTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y + compBounds.height;
// break;
// }
// default:
// case SwingConstants.CENTER: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// }
// }
// toplevel.setLocation(x, y);
// }
//
// public static boolean browse(URI uri) throws IOException {
// // Try using the Desktop api first
// try {
// Desktop desktop = Desktop.getDesktop();
// desktop.browse(uri);
//
// return true;
// } catch (SecurityException e) {
// }
//
// return false;
// }
// }
| import com.sun.swingset3.DemoProperties;
import com.sun.swingset3.demos.DemoUtilities;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; | // Create button to control visibility of frame
JButton showButton = new JButton("Show JDialog...");
showButton.addActionListener(new ShowActionListener());
panel.add(showButton);
return panel;
}
private static JDialog createDialog() {
//<snip>Create dialog
JDialog dialog = new JDialog(new JFrame(), "Demo JDialog", false);
//</snip>
//<snip>Add dialog's content
JLabel label = new JLabel("I'm content.");
label.setHorizontalAlignment(JLabel.CENTER);
label.setPreferredSize(new Dimension(200,140));
dialog.add(label);
//</snip>
//<snip>Initialize dialog's size
// which will shrink-to-fit its contents
dialog.pack();
//</snip>
return dialog;
}
public void start() { | // Path: demo/swingset3/com/sun/swingset3/demos/DemoUtilities.java
// public class DemoUtilities {
// private DemoUtilities() {
// // Hide constructor
// }
//
// public static void setToplevelLocation(Window toplevel, Component component,
// int relativePosition) {
//
// Rectangle compBounds = component.getBounds();
//
// // Convert component location to screen coordinates
// Point p = new Point();
// SwingUtilities.convertPointToScreen(p, component);
//
// int x;
// int y;
//
// // Set frame location to be centered on panel
// switch (relativePosition) {
// case SwingConstants.NORTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.EAST: {
// x = p.x + compBounds.width;
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.SOUTH: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.WEST: {
// x = p.x - toplevel.getWidth();
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// break;
// }
// case SwingConstants.NORTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.NORTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y - toplevel.getHeight();
// break;
// }
// case SwingConstants.SOUTH_EAST: {
// x = p.x + compBounds.width;
// y = p.y + compBounds.height;
// break;
// }
// case SwingConstants.SOUTH_WEST: {
// x = p.x - toplevel.getWidth();
// y = p.y + compBounds.height;
// break;
// }
// default:
// case SwingConstants.CENTER: {
// x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
// y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
// }
// }
// toplevel.setLocation(x, y);
// }
//
// public static boolean browse(URI uri) throws IOException {
// // Try using the Desktop api first
// try {
// Desktop desktop = Desktop.getDesktop();
// desktop.browse(uri);
//
// return true;
// } catch (SecurityException e) {
// }
//
// return false;
// }
// }
// Path: demo/swingset3/com/sun/swingset3/demos/dialog/DialogDemo.java
import com.sun.swingset3.DemoProperties;
import com.sun.swingset3.demos.DemoUtilities;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Create button to control visibility of frame
JButton showButton = new JButton("Show JDialog...");
showButton.addActionListener(new ShowActionListener());
panel.add(showButton);
return panel;
}
private static JDialog createDialog() {
//<snip>Create dialog
JDialog dialog = new JDialog(new JFrame(), "Demo JDialog", false);
//</snip>
//<snip>Add dialog's content
JLabel label = new JLabel("I'm content.");
label.setHorizontalAlignment(JLabel.CENTER);
label.setPreferredSize(new Dimension(200,140));
dialog.add(label);
//</snip>
//<snip>Initialize dialog's size
// which will shrink-to-fit its contents
dialog.pack();
//</snip>
return dialog;
}
public void start() { | DemoUtilities.setToplevelLocation(dialog, dialogSpaceholder, SwingConstants.CENTER); |
chicm/CmRaft | cmraft-core/src/main/java/com/chicm/cmraft/core/ClusterMemberManager.java | // Path: cmraft-core/src/main/java/com/chicm/cmraft/common/Configuration.java
// public interface Configuration {
//
// void useResource(String resourceName);
//
// String getString(String key);
//
// String getString(String key, String defaultValue);
//
// int getInt(String key);
//
// int getInt(String key, int defaultValue);
//
// void set(String key, String value);
//
// void clear();
//
// void remove(String key);
//
// Iterable<String> getKeys();
//
// Iterable<String> getKeys(String prefix);
// }
//
// Path: cmraft-core/src/main/java/com/chicm/cmraft/common/ServerInfo.java
// public class ServerInfo {
// static final Log LOG = LogFactory.getLog(ServerInfo.class);
// private final String host;
// private final int port;
//
// public ServerInfo(String host, int port) {
// this.host = host;
// this.port = port;
// }
//
// /**
// * @return the host
// */
// public String getHost() {
// return host;
// }
//
// /**
// * @return the port
// */
// public int getPort() {
// return port;
// }
//
// public static ServerInfo parseFromString(String hostAddress) {
// if(hostAddress == null)
// return null;
// String[] results = hostAddress.split(":");
// if(results == null || results.length != 2)
// return null;
// int port;
// try {
// port = Integer.parseInt(results[1]);
// } catch(Exception e) {
// LOG.error("parse port form configuration exception", e);
// return null;
// }
// return new ServerInfo(results[0], port);
// }
// /*
// public static List<ServerInfo> getRemoteServersFromConfiguration(Configuration conf) {
// List<ServerInfo> servers = new ArrayList<ServerInfo>();
// for (String key: conf.getKeys("raft.server.remote")) {
// ServerInfo server = ServerInfo.parseFromString(conf.getString(key));
// servers.add(server);
// }
// return servers;
// }*/
//
// public ServerId toServerId() {
// ServerId.Builder builder = ServerId.newBuilder();
// if(getHost() != null)
// builder.setHostName(getHost());
// builder.setPort(getPort());
//
// return builder.build();
// }
//
// public static ServerInfo copyFrom(ServerId serverId) {
// if(serverId == null)
// return null;
// ServerInfo server = new ServerInfo(serverId.getHostName(), serverId.getPort());
// return server;
// }
//
// @Override
// public String toString() {
// return String.format("[%s:%d]", getHost(), getPort());
// }
//
//
// private int memoizedHashCode = 0;
//
// @Override
// public int hashCode() {
// if (memoizedHashCode != 0) {
// return memoizedHashCode;
// }
// int hash = 41;
// hash = (19 * hash) + getPort();
// if(getHost()!=null) {
// hash = (53 * hash) + getHost().hashCode();
// }
// memoizedHashCode = hash;
// return hash;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if(obj == null) {
// LOG.debug("equals (null)");
// return false;
// }
// if (!(obj instanceof ServerInfo)) {
// return super.equals(obj);
// }
// ServerInfo other = (ServerInfo)obj;
// boolean result = true;
// result = result && ((getHost()!=null) == (other.getHost()!=null));
// if (getHost()!=null) {
// result = result && getHost()
// .equals(other.getHost());
// }
//
// result = result && (getPort()==other.getPort());
//
// return result;
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.chicm.cmraft.common.Configuration;
import com.chicm.cmraft.common.ServerInfo;
import com.google.common.base.Preconditions;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set; | /**
* Copyright 2014 The CmRaft Project
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.chicm.cmraft.core;
public class ClusterMemberManager {
static final Log LOG = LogFactory.getLog(ClusterMemberManager.class);
private static final String RAFT_SERVER_KEY_PREFIX = "raft.server";
private static final String RAFT_LOCAL_SERVER_KEY = "raft.local.server";
| // Path: cmraft-core/src/main/java/com/chicm/cmraft/common/Configuration.java
// public interface Configuration {
//
// void useResource(String resourceName);
//
// String getString(String key);
//
// String getString(String key, String defaultValue);
//
// int getInt(String key);
//
// int getInt(String key, int defaultValue);
//
// void set(String key, String value);
//
// void clear();
//
// void remove(String key);
//
// Iterable<String> getKeys();
//
// Iterable<String> getKeys(String prefix);
// }
//
// Path: cmraft-core/src/main/java/com/chicm/cmraft/common/ServerInfo.java
// public class ServerInfo {
// static final Log LOG = LogFactory.getLog(ServerInfo.class);
// private final String host;
// private final int port;
//
// public ServerInfo(String host, int port) {
// this.host = host;
// this.port = port;
// }
//
// /**
// * @return the host
// */
// public String getHost() {
// return host;
// }
//
// /**
// * @return the port
// */
// public int getPort() {
// return port;
// }
//
// public static ServerInfo parseFromString(String hostAddress) {
// if(hostAddress == null)
// return null;
// String[] results = hostAddress.split(":");
// if(results == null || results.length != 2)
// return null;
// int port;
// try {
// port = Integer.parseInt(results[1]);
// } catch(Exception e) {
// LOG.error("parse port form configuration exception", e);
// return null;
// }
// return new ServerInfo(results[0], port);
// }
// /*
// public static List<ServerInfo> getRemoteServersFromConfiguration(Configuration conf) {
// List<ServerInfo> servers = new ArrayList<ServerInfo>();
// for (String key: conf.getKeys("raft.server.remote")) {
// ServerInfo server = ServerInfo.parseFromString(conf.getString(key));
// servers.add(server);
// }
// return servers;
// }*/
//
// public ServerId toServerId() {
// ServerId.Builder builder = ServerId.newBuilder();
// if(getHost() != null)
// builder.setHostName(getHost());
// builder.setPort(getPort());
//
// return builder.build();
// }
//
// public static ServerInfo copyFrom(ServerId serverId) {
// if(serverId == null)
// return null;
// ServerInfo server = new ServerInfo(serverId.getHostName(), serverId.getPort());
// return server;
// }
//
// @Override
// public String toString() {
// return String.format("[%s:%d]", getHost(), getPort());
// }
//
//
// private int memoizedHashCode = 0;
//
// @Override
// public int hashCode() {
// if (memoizedHashCode != 0) {
// return memoizedHashCode;
// }
// int hash = 41;
// hash = (19 * hash) + getPort();
// if(getHost()!=null) {
// hash = (53 * hash) + getHost().hashCode();
// }
// memoizedHashCode = hash;
// return hash;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if(obj == null) {
// LOG.debug("equals (null)");
// return false;
// }
// if (!(obj instanceof ServerInfo)) {
// return super.equals(obj);
// }
// ServerInfo other = (ServerInfo)obj;
// boolean result = true;
// result = result && ((getHost()!=null) == (other.getHost()!=null));
// if (getHost()!=null) {
// result = result && getHost()
// .equals(other.getHost());
// }
//
// result = result && (getPort()==other.getPort());
//
// return result;
// }
// }
// Path: cmraft-core/src/main/java/com/chicm/cmraft/core/ClusterMemberManager.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.chicm.cmraft.common.Configuration;
import com.chicm.cmraft.common.ServerInfo;
import com.google.common.base.Preconditions;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Copyright 2014 The CmRaft Project
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.chicm.cmraft.core;
public class ClusterMemberManager {
static final Log LOG = LogFactory.getLog(ClusterMemberManager.class);
private static final String RAFT_SERVER_KEY_PREFIX = "raft.server";
private static final String RAFT_LOCAL_SERVER_KEY = "raft.local.server";
| private Set<ServerInfo> remoteServers = new HashSet<ServerInfo>(); |
chicm/CmRaft | cmraft-core/src/main/java/com/chicm/cmraft/core/ClusterMemberManager.java | // Path: cmraft-core/src/main/java/com/chicm/cmraft/common/Configuration.java
// public interface Configuration {
//
// void useResource(String resourceName);
//
// String getString(String key);
//
// String getString(String key, String defaultValue);
//
// int getInt(String key);
//
// int getInt(String key, int defaultValue);
//
// void set(String key, String value);
//
// void clear();
//
// void remove(String key);
//
// Iterable<String> getKeys();
//
// Iterable<String> getKeys(String prefix);
// }
//
// Path: cmraft-core/src/main/java/com/chicm/cmraft/common/ServerInfo.java
// public class ServerInfo {
// static final Log LOG = LogFactory.getLog(ServerInfo.class);
// private final String host;
// private final int port;
//
// public ServerInfo(String host, int port) {
// this.host = host;
// this.port = port;
// }
//
// /**
// * @return the host
// */
// public String getHost() {
// return host;
// }
//
// /**
// * @return the port
// */
// public int getPort() {
// return port;
// }
//
// public static ServerInfo parseFromString(String hostAddress) {
// if(hostAddress == null)
// return null;
// String[] results = hostAddress.split(":");
// if(results == null || results.length != 2)
// return null;
// int port;
// try {
// port = Integer.parseInt(results[1]);
// } catch(Exception e) {
// LOG.error("parse port form configuration exception", e);
// return null;
// }
// return new ServerInfo(results[0], port);
// }
// /*
// public static List<ServerInfo> getRemoteServersFromConfiguration(Configuration conf) {
// List<ServerInfo> servers = new ArrayList<ServerInfo>();
// for (String key: conf.getKeys("raft.server.remote")) {
// ServerInfo server = ServerInfo.parseFromString(conf.getString(key));
// servers.add(server);
// }
// return servers;
// }*/
//
// public ServerId toServerId() {
// ServerId.Builder builder = ServerId.newBuilder();
// if(getHost() != null)
// builder.setHostName(getHost());
// builder.setPort(getPort());
//
// return builder.build();
// }
//
// public static ServerInfo copyFrom(ServerId serverId) {
// if(serverId == null)
// return null;
// ServerInfo server = new ServerInfo(serverId.getHostName(), serverId.getPort());
// return server;
// }
//
// @Override
// public String toString() {
// return String.format("[%s:%d]", getHost(), getPort());
// }
//
//
// private int memoizedHashCode = 0;
//
// @Override
// public int hashCode() {
// if (memoizedHashCode != 0) {
// return memoizedHashCode;
// }
// int hash = 41;
// hash = (19 * hash) + getPort();
// if(getHost()!=null) {
// hash = (53 * hash) + getHost().hashCode();
// }
// memoizedHashCode = hash;
// return hash;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if(obj == null) {
// LOG.debug("equals (null)");
// return false;
// }
// if (!(obj instanceof ServerInfo)) {
// return super.equals(obj);
// }
// ServerInfo other = (ServerInfo)obj;
// boolean result = true;
// result = result && ((getHost()!=null) == (other.getHost()!=null));
// if (getHost()!=null) {
// result = result && getHost()
// .equals(other.getHost());
// }
//
// result = result && (getPort()==other.getPort());
//
// return result;
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.chicm.cmraft.common.Configuration;
import com.chicm.cmraft.common.ServerInfo;
import com.google.common.base.Preconditions;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set; | /**
* Copyright 2014 The CmRaft Project
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.chicm.cmraft.core;
public class ClusterMemberManager {
static final Log LOG = LogFactory.getLog(ClusterMemberManager.class);
private static final String RAFT_SERVER_KEY_PREFIX = "raft.server";
private static final String RAFT_LOCAL_SERVER_KEY = "raft.local.server";
private Set<ServerInfo> remoteServers = new HashSet<ServerInfo>();
private ServerInfo localServer;
private Set<String> localAddresses = new HashSet<String>();
| // Path: cmraft-core/src/main/java/com/chicm/cmraft/common/Configuration.java
// public interface Configuration {
//
// void useResource(String resourceName);
//
// String getString(String key);
//
// String getString(String key, String defaultValue);
//
// int getInt(String key);
//
// int getInt(String key, int defaultValue);
//
// void set(String key, String value);
//
// void clear();
//
// void remove(String key);
//
// Iterable<String> getKeys();
//
// Iterable<String> getKeys(String prefix);
// }
//
// Path: cmraft-core/src/main/java/com/chicm/cmraft/common/ServerInfo.java
// public class ServerInfo {
// static final Log LOG = LogFactory.getLog(ServerInfo.class);
// private final String host;
// private final int port;
//
// public ServerInfo(String host, int port) {
// this.host = host;
// this.port = port;
// }
//
// /**
// * @return the host
// */
// public String getHost() {
// return host;
// }
//
// /**
// * @return the port
// */
// public int getPort() {
// return port;
// }
//
// public static ServerInfo parseFromString(String hostAddress) {
// if(hostAddress == null)
// return null;
// String[] results = hostAddress.split(":");
// if(results == null || results.length != 2)
// return null;
// int port;
// try {
// port = Integer.parseInt(results[1]);
// } catch(Exception e) {
// LOG.error("parse port form configuration exception", e);
// return null;
// }
// return new ServerInfo(results[0], port);
// }
// /*
// public static List<ServerInfo> getRemoteServersFromConfiguration(Configuration conf) {
// List<ServerInfo> servers = new ArrayList<ServerInfo>();
// for (String key: conf.getKeys("raft.server.remote")) {
// ServerInfo server = ServerInfo.parseFromString(conf.getString(key));
// servers.add(server);
// }
// return servers;
// }*/
//
// public ServerId toServerId() {
// ServerId.Builder builder = ServerId.newBuilder();
// if(getHost() != null)
// builder.setHostName(getHost());
// builder.setPort(getPort());
//
// return builder.build();
// }
//
// public static ServerInfo copyFrom(ServerId serverId) {
// if(serverId == null)
// return null;
// ServerInfo server = new ServerInfo(serverId.getHostName(), serverId.getPort());
// return server;
// }
//
// @Override
// public String toString() {
// return String.format("[%s:%d]", getHost(), getPort());
// }
//
//
// private int memoizedHashCode = 0;
//
// @Override
// public int hashCode() {
// if (memoizedHashCode != 0) {
// return memoizedHashCode;
// }
// int hash = 41;
// hash = (19 * hash) + getPort();
// if(getHost()!=null) {
// hash = (53 * hash) + getHost().hashCode();
// }
// memoizedHashCode = hash;
// return hash;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if(obj == null) {
// LOG.debug("equals (null)");
// return false;
// }
// if (!(obj instanceof ServerInfo)) {
// return super.equals(obj);
// }
// ServerInfo other = (ServerInfo)obj;
// boolean result = true;
// result = result && ((getHost()!=null) == (other.getHost()!=null));
// if (getHost()!=null) {
// result = result && getHost()
// .equals(other.getHost());
// }
//
// result = result && (getPort()==other.getPort());
//
// return result;
// }
// }
// Path: cmraft-core/src/main/java/com/chicm/cmraft/core/ClusterMemberManager.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.chicm.cmraft.common.Configuration;
import com.chicm.cmraft.common.ServerInfo;
import com.google.common.base.Preconditions;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Copyright 2014 The CmRaft Project
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.chicm.cmraft.core;
public class ClusterMemberManager {
static final Log LOG = LogFactory.getLog(ClusterMemberManager.class);
private static final String RAFT_SERVER_KEY_PREFIX = "raft.server";
private static final String RAFT_LOCAL_SERVER_KEY = "raft.local.server";
private Set<ServerInfo> remoteServers = new HashSet<ServerInfo>();
private ServerInfo localServer;
private Set<String> localAddresses = new HashSet<String>();
| public ClusterMemberManager(Configuration conf) { |
chicm/CmRaft | cmraft-core/src/main/java/com/chicm/cmraft/util/BlockingHashMap.java | // Path: cmraft-core/src/main/java/com/chicm/cmraft/rpc/RpcTimeoutException.java
// public class RpcTimeoutException extends Exception {
//
// private static final long serialVersionUID = 3670017286407961069L;
//
// public RpcTimeoutException (String msg) {
// super(msg);
// }
// }
| import com.chicm.cmraft.rpc.RpcTimeoutException;
import com.google.common.base.Preconditions;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; | /**
* Copyright 2014 The CmRaft Project
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.chicm.cmraft.util;
/**
* A hash table supports blocking method like a blocking queue, except that
* user thread blocks only on specified keys. If a user thread trying to get
* a value with specified key which does not exist in the hash table, user thread
* is blocked until the key is put into the table.
*
* @author chicm
*
* @param <K>
* @param <V>
*/
public class BlockingHashMap <K,V> {
static final Log LOG = LogFactory.getLog(BlockingHashMap.class);
private ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>();
private ConcurrentHashMap<K, KeyLock> locks = new ConcurrentHashMap<>();
private void signalKeyArrive(K key) {
final KeyLock lock = locks.get(key);
if(lock == null)
return;
lock.lock();
try {
LOG.debug("singal key:[" + key + "] arrive");
lock.signal();
} finally {
lock.unlock();
}
}
public V put(K key, V value) {
V ret = map.put(key, value);
signalKeyArrive(key);
return ret;
}
private V remove(K key) {
locks.remove(key);
return map.remove(key);
}
public V take(K key) {
try {
return take(key, 0); | // Path: cmraft-core/src/main/java/com/chicm/cmraft/rpc/RpcTimeoutException.java
// public class RpcTimeoutException extends Exception {
//
// private static final long serialVersionUID = 3670017286407961069L;
//
// public RpcTimeoutException (String msg) {
// super(msg);
// }
// }
// Path: cmraft-core/src/main/java/com/chicm/cmraft/util/BlockingHashMap.java
import com.chicm.cmraft.rpc.RpcTimeoutException;
import com.google.common.base.Preconditions;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Copyright 2014 The CmRaft Project
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.chicm.cmraft.util;
/**
* A hash table supports blocking method like a blocking queue, except that
* user thread blocks only on specified keys. If a user thread trying to get
* a value with specified key which does not exist in the hash table, user thread
* is blocked until the key is put into the table.
*
* @author chicm
*
* @param <K>
* @param <V>
*/
public class BlockingHashMap <K,V> {
static final Log LOG = LogFactory.getLog(BlockingHashMap.class);
private ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>();
private ConcurrentHashMap<K, KeyLock> locks = new ConcurrentHashMap<>();
private void signalKeyArrive(K key) {
final KeyLock lock = locks.get(key);
if(lock == null)
return;
lock.lock();
try {
LOG.debug("singal key:[" + key + "] arrive");
lock.signal();
} finally {
lock.unlock();
}
}
public V put(K key, V value) {
V ret = map.put(key, value);
signalKeyArrive(key);
return ret;
}
private V remove(K key) {
locks.remove(key);
return map.remove(key);
}
public V take(K key) {
try {
return take(key, 0); | } catch (RpcTimeoutException e) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.