file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
Optional.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/org/docopt/Optional.java | package org.docopt;
import java.util.List;
import static org.docopt.Python.list;
class Optional extends BranchPattern {
public Optional(final List<? extends Pattern> children) {
super(children);
}
@Override
protected MatchResult match(List<LeafPattern> left,
List<LeafPattern> collected) {
if (collected == null) {
collected = list();
}
for (final Pattern pattern : getChildren()) {
final MatchResult u = pattern.match(left, collected);
left = u.getLeft();
collected = u.getCollected();
}
return new MatchResult(true, left, collected);
}
}
| 579 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
PatternFindingWorker.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/PatternFindingWorker.java | package bca.redact;
import java.util.ArrayList;
import java.util.List;
import javax.swing.SwingWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.itextpdf.kernel.colors.DeviceGray;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor;
import com.itextpdf.kernel.pdf.canvas.parser.listener.IPdfTextLocation;
import com.itextpdf.kernel.pdf.canvas.parser.listener.RegexBasedLocationExtractionStrategy;
import com.itextpdf.pdfcleanup.PdfCleanUpLocation;
public class PatternFindingWorker extends SwingWorker<List<RedactLocation>, RedactLocation> {
Logger log = LoggerFactory.getLogger(PatternFindingWorker.class);
PdfDocument pdfDoc = null;
List<TextPattern> patterns = null;
public PatternFindingWorker(PdfDocument pdfDoc, List<TextPattern> patterns) {
this.pdfDoc = pdfDoc;
this.patterns = patterns;
}
@Override
protected List<RedactLocation> doInBackground() {
log.info("Starting redaction scan..");
List<RedactLocation> locations = new ArrayList<RedactLocation>();
int pages = pdfDoc.getNumberOfPages();
for (int i = 1; i <= pages; i++) {
PdfPage page = pdfDoc.getPage(i /* FIXME */);
for (TextPattern pattern : patterns) {
log.info("Working on entity: {}", pattern.getRegex());
String entityRegex = pattern.getRegex();
RegexBasedLocationExtractionStrategy extractionStrategy = new RegexBasedLocationExtractionStrategy(
entityRegex);
new PdfCanvasProcessor(extractionStrategy).processPageContent(page);
for (IPdfTextLocation location : extractionStrategy.getResultantLocations()) {
PdfCleanUpLocation loc = new PdfCleanUpLocation(i, location.getRectangle(), DeviceGray.BLACK);
RedactLocation myloc = new RedactLocation();
myloc.pattern = pattern;
myloc.page = i;
myloc.loc = loc;
myloc.action = pattern.policy;
publish(myloc);
locations.add(myloc);
}
}
}
return locations;
}
}
| 2,007 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
RedactLocation.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/RedactLocation.java | package bca.redact;
import java.util.Comparator;
import com.itextpdf.pdfcleanup.PdfCleanUpLocation;
import bca.redact.TextPattern;
public class RedactLocation implements Comparable<RedactLocation> {
public int page = -1;
public TextPattern pattern = null;
public PdfCleanUpLocation loc = null;
public Action action = null;
RedactLocation() {
}
public int getPage() {
return this.loc.getPage();
}
public float getTop() {
return this.loc.getRegion().getTop();
}
public float getLeft() {
return this.loc.getRegion().getLeft();
}
@Override
public int compareTo(RedactLocation loc0) {
return Comparator.comparingInt(RedactLocation::getPage)
.thenComparing(Comparator.comparingDouble(RedactLocation::getTop).reversed())
.thenComparingDouble(RedactLocation::getLeft)
.compare(this, loc0);
}
}
| 866 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
RedactDialog.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/RedactDialog.java | package bca.redact;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Component;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.border.BevelBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import org.ghost4j.document.PDFDocument;
import org.ghost4j.renderer.SimpleRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.pdfcleanup.PdfCleanUpLocation;
import com.itextpdf.pdfcleanup.PdfCleanUpTool;
import com.lowagie.text.Font;
import javax.swing.JButton;
public class RedactDialog extends JDialog {
public class RedactionsTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
public final String[] cols = new String[] { "Page", "Text", "Type", "Action" };
Color defaultBackground = null;
@Override
public String getColumnName(int column) {
return cols[column];
}
@Override
public int getColumnCount() {
return 4;
}
@Override
public int getRowCount() {
return redactLocations.size();
}
@Override
public Object getValueAt(int row, int col) {
RedactLocation rl = redactLocations.get(row);
switch (col) {
case 0:
return rl.page;
case 1:
return rl.pattern.getLabel();
case 2:
return rl.pattern.getType();
case 3:
return rl.action;
}
return null;
}
public Action getAction(int row) {
return redactLocations.get(row).action;
}
public boolean isCellEditable(int row, int col) {
return col == 3;
}
@Override
public void setValueAt(Object value, int row, int col) {
RedactLocation rl = redactLocations.get(row);
if (col == 3) {
rl.action = (Action) value;
this.fireTableRowsUpdated(row, row);
previewPanel.repaint(500);
}
fireTableCellUpdated(row, col);
}
}
Logger log = LoggerFactory.getLogger(RedactDialog.class);
private static final long serialVersionUID = 2027484467240740791L;
// private PreviewPanel previewPanel;
List<TextPattern> patterns = null;
File pdfFile = null;
File outFile = null;
List<RedactLocation> redactLocations = new ArrayList<>();
RedactionsTableModel tableModel = new RedactionsTableModel();
// user policies from prompts
Set<String> entitiesAccepted = new HashSet<>();
Set<String> entitiesRejected = new HashSet<>();
// Ghostscript rendering variables for preview
PreviewPanel previewPanel;
PDFDocument doc = null;
Image pageImage = null;
private PdfDocument itextPDF;
private int currentPage = -1;
private Document layoutDoc;
private JTable table;
Color backgroundColor = null;
private final javax.swing.Action actionNextPage = new AbstractAction("Next >") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
setPreviewPage(currentPage + 1);
}
};
private final javax.swing.Action actionPrevPage = new AbstractAction("< Prev") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
setPreviewPage(currentPage - 1);
}
};
private void updateEnabledPaging() {
this.actionNextPage.setEnabled( layoutDoc != null && currentPage < layoutDoc.getPdfDocument().getNumberOfPages() );
this.actionPrevPage.setEnabled( currentPage > 1 );
}
public RedactDialog() {
setDefaultCloseOperation(HIDE_ON_CLOSE);
setModal(false);
setTitle("Redact Document");
setAlwaysOnTop(true);
JToolBar toolBar = new JToolBar();
getContentPane().add(toolBar, BorderLayout.SOUTH);
JButton btnPrev = new JButton("< Prev");
btnPrev.setAction(actionPrevPage);
toolBar.add(btnPrev);
JButton btnNext = new JButton("Next >");
btnNext.setAction(actionNextPage);
toolBar.add(btnNext);
Button btnRedact = new Button("Redact");
btnRedact.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
redactButtonHandler();
}
});
toolBar.add(btnRedact);
Button btnClose = new Button("Close");
btnClose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
close();
}
});
toolBar.add(btnClose);
//setModalityType(ModalityType.DOCUMENT_MODAL);
JPanel panel = new JPanel(new BorderLayout());
//panel.setMinimumSize(new Dimension(600, 500));
getContentPane().add(panel, BorderLayout.CENTER);
previewPanel = new PreviewPanel();
//previewPanel.setMinimumSize(new Dimension(600, 400));
previewPanel.setBackground(new java.awt.Color(255, 255, 255));
previewPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
JScrollPane scrolls = new JScrollPane(previewPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
panel.add(scrolls, BorderLayout.CENTER);
JComboBox<Action> actionComboBox = new JComboBox<>();
actionComboBox.addItem(Action.Ignore);
actionComboBox.addItem(Action.Ask);
actionComboBox.addItem(Action.Redact);
table = new JTable();
table.setFillsViewportHeight(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//table.setPreferredSize(new Dimension(400, 300));
table.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
table.setModel(new RedactionsTableModel());
TableColumn pageColumn = table.getColumn(tableModel.getColumnName(0));
pageColumn.setPreferredWidth(10);
TableColumn actionColumn = table.getColumn(tableModel.getColumnName(3));
actionColumn.setCellEditor(new DefaultCellEditor(actionComboBox));
// Single click jumps to show redact location
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent mouseEvent) {
int row = table.rowAtPoint(mouseEvent.getPoint());
if(0 <= row && row < redactLocations.size()) {
markPageLocation(redactLocations.get(row));
}
}
});
table.getColumn(tableModel.getColumnName(3)).setCellRenderer(
new DefaultTableCellRenderer() {
private static final long serialVersionUID = 1L;
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
JLabel superRenderer = (JLabel)super.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if(backgroundColor == null) backgroundColor = getBackground();
RedactLocation rl = redactLocations.get(row);
java.awt.Font f = superRenderer.getFont();
if(!rl.pattern.policy.equals(Action.Ask) && !rl.pattern.policy.equals(rl.action)) {
if(Action.Redact.equals(rl.action)) {
superRenderer.setFont(f.deriveFont(Font.BOLDITALIC));
} else {
superRenderer.setFont(f.deriveFont(Font.ITALIC));
}
superRenderer.setToolTipText("Chosen action differs from this entity's policy of "+rl.pattern.policy.name());
} else {
if(Action.Redact.equals(rl.action)) {
superRenderer.setFont(f.deriveFont(Font.BOLD));
}
superRenderer.setToolTipText(null);
}
if(!isSelected) {
switch(rl.action) {
case Ask:
superRenderer.setBackground(PreviewPanel.askColor);
break;
case Redact:
superRenderer.setBackground(PreviewPanel.redactColor);
break;
case Ignore:
superRenderer.setBackground(backgroundColor);
break;
}
}
return superRenderer;
}
});
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(scrollPane, BorderLayout.EAST);
pack();
}
public void markPageLocation(RedactLocation loc) {
if (loc.page != this.currentPage) {
setPreviewPage(loc.page);
}
previewPanel.setPDFLocation(loc.loc, this.layoutDoc);
}
public void redactButtonHandler() {
log.info("in redact button handler");
long asks = this.redactLocations.stream().filter(l -> Action.Ask.equals(l.action)).count();
if(asks > 0) {
JOptionPane.showMessageDialog(this.getContentPane(), "Please choose \"Redact\" or \"Ignore\" actions for the entities highlighted in yellow and marked \"Ask\".", "Redact Choices Required", JOptionPane.INFORMATION_MESSAGE);
return;
}
log.info("in redact button handler, past the asks check");
List<PdfCleanUpLocation> cleanUps = this.redactLocations.stream().filter(x -> Action.Redact.equals(x.action)).map(x -> x.loc)
.collect(Collectors.toList());
PdfCleanUpTool cleaner = new PdfCleanUpTool(this.itextPDF, cleanUps);
try {
log.info("in redact button handler, starting cleanup");
cleaner.cleanUp();
log.info("in redact button handler, past the cleanup operation");
} catch (IOException e) {
log.error("in redact button handler, cleanup threw error", e);
}
closeDoc();
}
public void closeDoc() {
this.itextPDF.close();
this.itextPDF = null;
this.setVisible(false);
this.doc = null;
this.pageImage = null;
this.currentPage = -1;
this.redactLocations.clear();
tableModel.fireTableDataChanged();
}
public void close() {
this.setVisible(false);
previewPanel.clearPDFLocation();
closeDoc();
}
public void startDoc(File pdfFile, File outputFile, List<TextPattern> filePatterns)
throws FileNotFoundException, IOException {
log.debug("Starting redaction dialog for {}, outputting to {} with {} patterns", pdfFile.getPath(), outputFile.getPath(), filePatterns.size());
this.redactLocations = new ArrayList<>();
this.patterns = filePatterns;
this.pdfFile = pdfFile;
this.outFile = outputFile;
this.outFile.getParentFile().mkdirs();
PDFDocument mydoc = new PDFDocument();
mydoc.load(pdfFile);
this.doc = mydoc;
this.currentPage = -1;
try {
this.itextPDF = new PdfDocument(new PdfReader(pdfFile), new PdfWriter(outFile));
this.layoutDoc = new Document(this.itextPDF);
PatternFindingWorker worker = new PatternFindingWorker(itextPDF, this.patterns) {
@Override
protected void process(List<RedactLocation> newLocations) {
log.info("Found {} redaction locations.", newLocations.size());
redactLocations.addAll(newLocations);
java.util.Collections.sort(redactLocations);
if (currentPage == -1 && !newLocations.isEmpty()) {
RedactLocation l = newLocations.get(0);
markPageLocation(l);
}
tableModel.fireTableDataChanged();
}
};
worker.execute();
} catch (IOException e) {
throw new Error(e);
}
this.previewPanel.clearPDFLocation();
this.previewPanel.setRedactLocations(redactLocations);
tableModel.fireTableDataChanged();
if(this.currentPage == -1)
setPreviewPage(1);
pack();
}
private void setPreviewPage(int i) {
try {
SimpleRenderer renderer = new SimpleRenderer();
renderer.setResolution(72);
List<Image> pages = renderer.render(doc, i - 1, i - 1);
log.info("size of image list: {}", pages.size());
BufferedImage pageImage = (BufferedImage)pages.get(0);
previewPanel.setPage(pageImage, i, itextPDF.getPage(i).getPageSize());
this.currentPage = i;
updateEnabledPaging();
} catch (Exception e) {
throw new Error(e);
}
}
} | 12,692 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
AnalysisException.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/AnalysisException.java | package bca.redact;
import java.io.File;
public class AnalysisException extends Exception {
private static final long serialVersionUID = 1L;
File file;
Throwable cause;
AnalysisException(File f, Throwable e) {
file=f;
cause=e;
}
} | 241 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
AnalysisWorker.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/AnalysisWorker.java | package bca.redact;
import java.util.Set;
import javax.swing.SwingWorker;
public abstract class AnalysisWorker extends SwingWorker<Set<PDFAnalysis>, PDFAnalysis> {
}
| 170 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
EntityPattern.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/EntityPattern.java | package bca.redact;
import java.util.regex.Pattern;
public class EntityPattern extends TextPattern {
public EntityPattern(String text, String type, Action policy) {
this.text = text;
this.type = type;
this.policy = policy;
this.count = 1;
}
public String text;
public String type;
public String sentence;
@Override
public String getRegex() {
return Pattern.quote(this.text);
}
@Override
public String getLabel() {
return this.text;
}
@Override
public String getType() {
return this.type;
}
public String getExampleSentence() {
return this.sentence;
}
public void setExampleSentence(String sentence) {
this.sentence = sentence;
}
}
| 678 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
TextPattern.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/TextPattern.java | package bca.redact;
/**
* TextPattern is an abstract class representing patterns that can be found in text documents.
* Each TextPattern must generate a regular expression that allows the pattern to be matched.
* Each TextPattern can keep a count of occurances.
* @author jansen
*
*/
public abstract class TextPattern {
public int count;
public void incr() {
this.count++;
}
public Action policy;
public abstract String getRegex();
public abstract String getLabel();
public abstract String getType();
}
| 519 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
CoreNLPAnalysisWorker.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/CoreNLPAnalysisWorker.java | package bca.redact;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor;
import com.itextpdf.kernel.pdf.canvas.parser.listener.LocationTextExtractionStrategy;
import edu.stanford.nlp.pipeline.CoreDocument;
import edu.stanford.nlp.pipeline.CoreEntityMention;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
public class CoreNLPAnalysisWorker extends AnalysisWorker {
private static final Logger log = Logger.getLogger(CoreNLPAnalysisWorker.class);
private static Properties props = new Properties();
private static final String[][] empty = new String[][] {};
File[] pdfs;
StanfordCoreNLP pipeline;
private Set<String> entityTypesIncluded = new HashSet<>();
static {
props.setProperty("annotators", "tokenize,ssplit,pos,ner");
// set a property for an annotator, in this case the coref annotator is being
// set to use the neural algorithm
props.setProperty("ner.model", "edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz");
props.setProperty("ner.useSUTime", "false");
props.setProperty("ner.applyNumericClassifiers", "false");
props.setProperty("ner.applyFineGrained", "false");
}
CoreNLPAnalysisWorker(File[] pdfs, boolean includePerson, boolean includeLocation, boolean includeOrganization) {
this.pdfs = pdfs;
if(includeOrganization) entityTypesIncluded.add("ORGANIZATION");
if(includePerson) entityTypesIncluded.add("PERSON");
if(includeLocation) entityTypesIncluded.add("LOCATION");
}
@Override
protected Set<PDFAnalysis> doInBackground() {
Set<PDFAnalysis> analyses = new HashSet<>();
if (pipeline == null) {
pipeline = new StanfordCoreNLP(props);
}
int errors = 0;
for (File f : pdfs) {
PdfDocument pdfDoc = null;
try {
try {
pdfDoc = new PdfDocument(new PdfReader(f.getAbsolutePath()));
} catch (Throwable e) {
throw new AnalysisException(f, e);
}
LocationTextExtractionStrategy strategy = new LocationTextExtractionStrategy();
PdfCanvasProcessor parser = new PdfCanvasProcessor(strategy);
for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) {
try {
parser.processPageContent(pdfDoc.getPage(i));
} catch (Throwable e) {
throw new AnalysisException(f, e);
} finally {
parser.reset();
}
}
String str = strategy.getResultantText();
CoreDocument doc = new CoreDocument(str);
try {
pipeline.annotate(doc);
} catch (Throwable e) {
throw new AnalysisException(f, e);
}
List<String[]> pdfentities = new ArrayList<>();
for (CoreEntityMention cem : doc.entityMentions()) {
if(entityTypesIncluded.contains(cem.entityType())) {
pdfentities.add(new String[] {cem.text(), cem.entityType(), cem.sentence().text()});
}
}
PDFAnalysis analysis = new PDFAnalysis(f, pdfentities.toArray(empty));
analyses.add(analysis);
publish(analysis);
} catch (AnalysisException e) {
PDFAnalysis analysis = new PDFAnalysis(f, e);
analyses.add(analysis);
publish(analysis);
} finally {
if(pdfDoc != null) {
pdfDoc.close();
}
}
}
if(errors > 0) {
log.error("There were PDF Entity Analysis errors: "+errors);
}
return analyses;
}
}
| 3,456 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
PDFAnalysis.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/PDFAnalysis.java | package bca.redact;
import java.io.File;
import java.util.Objects;
public class PDFAnalysis {
public File file;
public String[][] entities;
public AnalysisException error;
PDFAnalysis(File file, String[][] entities) {
this.file = file;
this.entities = entities;
}
PDFAnalysis(File file, AnalysisException error) {
this.file = file;
this.error = error;
}
@Override
public int hashCode() {
return Objects.hash(file);
}
}
| 445 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
ExpressionPattern.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/ExpressionPattern.java | package bca.redact;
public class ExpressionPattern extends TextPattern {
public String label;
public String regex;
public ExpressionPattern(String label, String regex, Action policy) {
this.label = label;
this.regex = regex;
this.policy = policy;
this.count = 1;
}
@Override
public String getRegex() {
return this.regex;
}
@Override
public String getLabel() {
return this.label;
}
@Override
public String getType() {
return "REGEX";
}
}
| 471 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
PreviewPanel.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/PreviewPanel.java | package bca.redact;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.List;
import javax.swing.JPanel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.layout.Document;
import com.itextpdf.pdfcleanup.PdfCleanUpLocation;
class PreviewPanel extends JPanel {
private static final Logger log = LoggerFactory.getLogger(PreviewPanel.class);
private static final long serialVersionUID = 8082940778123734607L;
BufferedImage pageImage = null;
int page = -1;
Rectangle currentLocation = null;
List<RedactLocation> locations = Collections.emptyList();
//private boolean paintedPage;
public static Color redactColor = new Color(0, 0, 0, .4f);
public static Color y = Color.yellow.brighter();
public static Color askColor = new Color(y.getRed(), y.getGreen(), y.getBlue(), 100);
private com.itextpdf.kernel.geom.Rectangle pageSize;
PreviewPanel() {
log.debug("Created PreviewPanel");
// set a preferred size for the custom panel.
//setPreferredSize(new Dimension(420, 420));
}
public void setRedactLocations(List<RedactLocation> locations) {
this.locations = locations;
}
public void setPage(BufferedImage image, int page, com.itextpdf.kernel.geom.Rectangle pageSize) {
this.pageImage = image;
this.page = page;
this.pageSize = pageSize;
//this.paintedPage = false;
repaint(500);
}
@Override
public Dimension getPreferredSize() {
if(this.pageImage != null) {
int h = this.pageImage.getHeight();
int w = this.pageImage.getWidth();
Dimension size = new Dimension(w, h);
return size;
} else {
return new Dimension(612, 792);
}
}
public void setPDFLocation(PdfCleanUpLocation loc, Document doc) {
com.itextpdf.kernel.geom.Rectangle r = loc.getRegion();
PdfPage page = doc.getPdfDocument().getPage(loc.getPage());
com.itextpdf.kernel.geom.Rectangle pageSize = page.getPageSize();
this.currentLocation = translateLocation(r, pageSize);
repaint(500);
}
public void clearPDFLocation() {
this.currentLocation = null;
repaint(500);
}
private Rectangle translateLocation(com.itextpdf.kernel.geom.Rectangle location, com.itextpdf.kernel.geom.Rectangle pageSize) {
int awtX = (int)(location.getX());
int awtY = (int)(pageSize.getHeight()-location.getY()-location.getHeight());
return new Rectangle(awtX, awtY, (int)location.getWidth(), (int)location.getHeight());
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(pageImage != null) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(pageImage, 0, 0, this);
g2d.dispose();
}
//this.paintedPage = true;
// g.drawString("BLAH", 20, 20);
Color prev = g.getColor();
//.getSize().g.setComposite(AlphaComposite.SrcOver.derive(0.8f));
for(RedactLocation rl : this.locations) {
if(rl.page == page) {
Rectangle r = translateLocation(rl.loc.getRegion(), pageSize);
switch(rl.action) {
case Redact:
g.setColor(redactColor);
g.fillRect(r.x-1, r.y-1, r.width+2, r.height+2);
break;
case Ignore:
g.setColor(Color.GRAY);
g.drawRect(r.x, r.y, r.width, r.height);
g.drawRect(r.x-1, r.y-1, r.width+2, r.height+2);
break;
case Ask:
g.setColor(askColor);
g.fillRect(r.x-1, r.y-1, r.width+2, r.height+2);
break;
}
}
}
if (currentLocation != null) {
g.setColor(Color.red);
g.drawRect(currentLocation.x, currentLocation.y, currentLocation.width, currentLocation.height);
g.drawRect(currentLocation.x-1, currentLocation.y-1, currentLocation.width+2, currentLocation.height+2);
this.scrollRectToVisible(currentLocation);
}
g.setColor(prev);
}
} | 3,851 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
TextPatternUtil.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/TextPatternUtil.java | package bca.redact;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.io.IOUtils;
public class TextPatternUtil {
public static List<ExpressionPattern> loadBEFeatures(File f) {
try {
return IOUtils.readLines(new FileReader(f)).parallelStream()
.filter(line -> !line.startsWith("#"))
.map(line -> (String)line.split("\t")[1] )
.map(pat -> new ExpressionPattern(pat, Pattern.quote(pat), Action.Ask) )
.collect(Collectors.toList());
} catch (FileNotFoundException e) {
throw new Error("Not Expected", e);
} catch (IOException e) {
throw new Error("Not Expected", e);
}
}
public static List<ExpressionPattern> loadExpressionActionList(File f) {
try {
return IOUtils.readLines(new FileReader(f)).parallelStream()
.filter(line -> !line.startsWith("#") && line.contains("\t"))
.map(line -> {
String[] foo = line.split("\t");
StringBuilder label = new StringBuilder();
if(foo.length > 2) {
for(int i = 2; i < foo.length; i++) {
label.append(foo[i]);
}
}
return new ExpressionPattern(label.toString(), foo[0], Action.valueOf(foo[1]));
})
.collect(Collectors.toList());
} catch (FileNotFoundException e) {
throw new Error("Not Expected", e);
} catch (IOException e) {
throw new Error("Not Expected", e);
}
}
public static void saveExpressionPatterns(File f, Collection<ExpressionPattern> list) {
try(PrintWriter pw = new PrintWriter(new FileWriter(f))) {
pw.println("# Expression patterns saved from BitCurator PDF Redactor");
pw.println("# Format: <Regex><tab><Redact/Ignore/Ask><tab>a pattern label");
pw.println("# Example: \\\\d{3}-\\\\d{2}-\\\\d{4}<tab>Redact<tab>Social Security Numbers");
list.stream().forEach( ep -> {
String line = MessageFormat.format("{0}\t{1}\t{2}", ep.regex, ep.policy.name(), ep.label);
pw.println(line);
});
} catch (IOException e) {
throw new Error(e);
}
}
}
| 2,250 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
RedactionApp.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/RedactionApp.java | package bca.redact;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.SwingWorker.StateValue;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import org.apache.commons.collections4.ListValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.apache.log4j.Logger;
import org.docopt.Docopt;
public class RedactionApp {
private static final Logger log = Logger.getLogger(RedactionApp.class);
private static final File[] EMPTY_FILE_ARRAY = new File[] {};
private static final String DEFAULT_PATTERNS_PATH = "bca_redact-pdf/default_patterns.txt";
protected static final Color ANALYZED_BG_COLOR = Color.lightGray;
private Action defaultAction = Action.Ignore;
private JFrame frmBitcuratorPdfRedact;
private JTable table_entities;
private JTable table_expressions;
private JFileChooser fileChooser_pdfs;
private JFileChooser fileChooser_textpattern;
private ButtonGroup nlpToolGroup;
private JCheckBoxMenuItem chckbxmntmDetectPlaces;
private JCheckBoxMenuItem chckbxmntmDetectPersons;
private JCheckBoxMenuItem chckbxmntmDetectOrganizations;
private List<File> pdfFiles = new ArrayList<>();
private Map<File, PDFAnalysis> file_analyses = new HashMap<>();
private ListValuedMap<String, File> pattern_files = new ArrayListValuedHashMap<>();
private Map<String, EntityPattern> entities = new HashMap<String, EntityPattern>();
private List<String> entityOrder = new ArrayList<String>();
private List<ExpressionPattern> expressions = new ArrayList<>();
private boolean useSpacy = false;
Color backgroundColor = null;
Object file_columnNames[] = { "Filename", "Path", "Output" };
AbstractTableModel tableModel_pdfs = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
public String getColumnName(int column) {
return file_columnNames[column].toString();
}
public int getRowCount() {
return pdfFiles.size();
}
public int getColumnCount() {
return file_columnNames.length;
}
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return pdfFiles.get(row).getName();
case 1:
return pdfFiles.get(row).getParentFile().getPath();
case 2:
File output = getOutputFile(pdfFiles.get(row));
if(output.exists()) {
return output.getPath();
} else {
return "";
}
default:
return "n/a";
}
}
};
AbstractTableModel tableModel_patterns = new AbstractTableModel() {
public Object columnNames[] = { "Name", "Expression", "Action" };
private static final long serialVersionUID = 1L;
public String getColumnName(int column) {
return columnNames[column].toString();
}
public int getRowCount() {
return expressions.size();
}
public int getColumnCount() {
return columnNames.length;
}
public boolean isCellEditable(int row, int col) {
return true;
}
@Override
public void setValueAt(Object value, int row, int col) {
ExpressionPattern p = expressions.get(row);
switch(col) {
case 0:
p.label = (String)value;
return;
case 1:
// TODO check valid expression
p.regex = (String)value;
return;
case 2:
p.policy = (Action)value;
return;
}
fireTableCellUpdated(row, col);
}
public Object getValueAt(int row, int col) {
ExpressionPattern p = expressions.get(row);
switch(col) {
case 0:
return p.label;
case 1:
return p.regex;
case 2:
return p.policy;
default:
return "";
}
}
};
AbstractTableModel tableModel_entities = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
Object columnNames[] = { "Entity Text", "Type", "#", "Files", "Action"};
public String getColumnName(int column) {
return columnNames[column].toString();
}
public int getRowCount() {
return entities.size();
}
public int getColumnCount() {
return columnNames.length;
}
public boolean isCellEditable(int row, int col) {
return col == 4;
}
@Override
public void setValueAt(Object value, int row, int col) {
String name = entityOrder.get(row);
EntityPattern e = entities.get(name);
switch(col) {
case 0:
e.text = (String)value;
return;
case 1:
e.type = (String)value;
return;
case 4:
e.policy = (Action)value;
return;
}
fireTableCellUpdated(row, col);
}
public Object getValueAt(int row, int col) {
String name = entityOrder.get(row);
EntityPattern e = entities.get(name);
switch(col) {
case 0:
return e.text;
case 1:
return e.type;
case 2:
return e.count;
case 3:
return pattern_files.get(e.getLabel()).stream().distinct().count();
case 4:
return e.policy;
}
return "?";
}
};
private JTable table;
private String outPath;
private RedactDialog redactDialog;
private final javax.swing.Action actionAddPDFs = new AbstractAction("Open File(s)..") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
int retVal = fileChooser_pdfs.showOpenDialog(frmBitcuratorPdfRedact);
if (retVal == JFileChooser.APPROVE_OPTION) {
File[] files = fileChooser_pdfs.getSelectedFiles();
addPDFPaths(files);
}
}
};
private final javax.swing.Action actionClearPDFs = new AbstractAction("Clear All") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
entities.clear();
entityOrder.clear();
pattern_files.clear();
tableModel_entities.fireTableDataChanged();
clearPDFPaths();
}
};
private javax.swing.Action actionRunEntityAnalysis = new AbstractAction("Run Recognition") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
entities.clear();
entityOrder.clear();
pattern_files.clear();
tableModel_entities.fireTableDataChanged();
startEntityAnalysisWorker();
}
};
private javax.swing.Action actionImportPatterns = new AbstractAction("Open File(s)..") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
fileChooser_textpattern.setDialogTitle("Open text patterns file(s)");
int retVal = fileChooser_textpattern.showOpenDialog(frmBitcuratorPdfRedact);
if (retVal == JFileChooser.APPROVE_OPTION) {
File[] files = fileChooser_textpattern.getSelectedFiles();
for(File f : files) {
TextPatternUtil.loadExpressionActionList(f).stream()
.forEach(p -> {
log.info(p.label);
expressions.add(p);
});
}
tableModel_patterns.fireTableDataChanged();
}
}
};
private javax.swing.Action actionImportBEPatterns = new AbstractAction("Import Bulk Extractor features..") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
fileChooser_textpattern.setDialogTitle("Import Bulk Extractor features..");
int retVal = fileChooser_textpattern.showOpenDialog(frmBitcuratorPdfRedact);
if (retVal == JFileChooser.APPROVE_OPTION) {
File[] files = fileChooser_textpattern.getSelectedFiles();
for(File f : files) {
TextPatternUtil.loadBEFeatures(f).stream()
.forEach(p -> {
expressions.add(p);
});
}
}
tableModel_patterns.fireTableDataChanged();
}
};
private ActionListener analysisToolListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
useSpacy = "spaCy".equals(e.getActionCommand());
}
};
private javax.swing.Action actionClearEntities = new AbstractAction("Clear All") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent arg0) {
entities = Collections.emptyMap();
entityOrder = Collections.emptyList();
tableModel_entities.fireTableDataChanged();
}
};
private javax.swing.Action actionSaveAsPatterns = new AbstractAction("Save As..") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser();
jfc.setDialogType(JFileChooser.SAVE_DIALOG);
jfc.setDialogTitle("Save Text Patterns to File");
int retVal = jfc.showOpenDialog(frmBitcuratorPdfRedact);
if(retVal != JFileChooser.CANCEL_OPTION) {
File f = jfc.getSelectedFile();
TextPatternUtil.saveExpressionPatterns(f, expressions);
}
}
};
private javax.swing.Action actionResetDefaultPatterns = new AbstractAction("Reset to Defaults") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent arg0) {
expressions.clear();
TextPatternUtil.loadExpressionActionList(new File(DEFAULT_PATTERNS_PATH))
.stream()
.forEach(p -> {
expressions.add(p);
});
tableModel_patterns.fireTableDataChanged();
}
};
private javax.swing.Action actionSaveDefaultPatterns = new AbstractAction("Save as Defaults") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
TextPatternUtil.saveExpressionPatterns(new File(DEFAULT_PATTERNS_PATH), expressions);
}
};
private javax.swing.Action actionClearPatterns = new AbstractAction("Clear All") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
expressions.clear();
tableModel_patterns.fireTableDataChanged();
}
};
private javax.swing.Action actionAddPattern = new AbstractAction("New Pattern") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent arg0) {
expressions.add(new ExpressionPattern("Add a label", "", Action.Ask));
tableModel_patterns.fireTableDataChanged();
}
};
private javax.swing.Action actionAbout = new AbstractAction("About") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
JDialog f = new SimpleAboutDialog(new JFrame());
f.setVisible(true);
}
};
/**
* Launch the application.
*/
public static void main(String[] args) {
InputStream doc = RedactionApp.class.getClassLoader().getResourceAsStream("docopt.txt");
final Map<String, Object> opts = new Docopt(doc).withVersion("BitCurator PDF Redactor 0.1.0").parse(args);
// Validate output path.
String outPathArg = (String) opts.get("--output-dir");
final String outPathAbsolute = Paths.get(outPathArg).toFile().getAbsolutePath();
// Build the list of PDFs
@SuppressWarnings("unchecked")
List<Object> infiles = (List<Object>)opts.get("FILE");
File[] files = infiles.stream()
.map(a -> new File((String) a))
.collect(Collectors.toCollection(ArrayList::new)).toArray(EMPTY_FILE_ARRAY);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RedactionApp window = new RedactionApp();
window.setOutPath(outPathAbsolute);
window.frmBitcuratorPdfRedact.setVisible(true);
window.addPDFPaths(files);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
protected void setOutPath(String outPath) {
this.outPath = outPath;
}
/**
* Create the application.
*/
public RedactionApp() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
loadExpressions();
frmBitcuratorPdfRedact = new JFrame();
frmBitcuratorPdfRedact.setTitle("BitCurator PDF Redact");
frmBitcuratorPdfRedact.setBounds(50, 50, 800, 600);
frmBitcuratorPdfRedact.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frmBitcuratorPdfRedact.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("PDF Files");
menuBar.add(mnFile);
mnFile.setMnemonic('F');
JMenuItem mntmAddPdfs = new JMenuItem("Open File(s)..");
mntmAddPdfs.setAction(actionAddPDFs);
mnFile.add(mntmAddPdfs);
JMenuItem mntmClearPdfs = new JMenuItem("Clear All");
mntmClearPdfs.setAction(actionClearPDFs);
mnFile.add(mntmClearPdfs);
JMenu mnNewMenu = new JMenu("Entity Recognition");
mnNewMenu.setMnemonic('E');
menuBar.add(mnNewMenu);
JMenu mnRecognitionTool = new JMenu("Recognition Tool");
mnNewMenu.add(mnRecognitionTool);
JRadioButtonMenuItem rdbtnmntmCorenlp = new JRadioButtonMenuItem("CoreNLP");
rdbtnmntmCorenlp.setSelected(true);
rdbtnmntmCorenlp.setActionCommand("CoreNLP");
rdbtnmntmCorenlp.addActionListener(analysisToolListener);
mnRecognitionTool.add(rdbtnmntmCorenlp);
JRadioButtonMenuItem rdbtnmntmSpacy = new JRadioButtonMenuItem("spaCy");
rdbtnmntmSpacy.setActionCommand("spaCy");
rdbtnmntmSpacy.addActionListener(analysisToolListener);
mnRecognitionTool.add(rdbtnmntmSpacy);
nlpToolGroup = new ButtonGroup();
nlpToolGroup.add(rdbtnmntmSpacy);
nlpToolGroup.add(rdbtnmntmCorenlp);
JMenuItem mntmRunEntities = new JMenuItem("Run Entity Recognition");
mntmRunEntities.setAction(actionRunEntityAnalysis);
mnNewMenu.add(mntmRunEntities);
chckbxmntmDetectPersons = new JCheckBoxMenuItem("Include Persons");
chckbxmntmDetectPersons.setSelected(true);
mnNewMenu.add(chckbxmntmDetectPersons);
chckbxmntmDetectPlaces = new JCheckBoxMenuItem("Include Locations");
chckbxmntmDetectPlaces.setSelected(true);
mnNewMenu.add(chckbxmntmDetectPlaces);
chckbxmntmDetectOrganizations = new JCheckBoxMenuItem("Include Organizations");
chckbxmntmDetectOrganizations.setSelected(true);
mnNewMenu.add(chckbxmntmDetectOrganizations);
JMenuItem mntmClearNamedEntities = new JMenuItem("Clear All");
mntmClearNamedEntities.setAction(actionClearEntities);
mnNewMenu.add(mntmClearNamedEntities);
JMenu mnTextPatterns = new JMenu("Text Patterns");
menuBar.add(mnTextPatterns);
JMenuItem mntmNewPattern = new JMenuItem("Add Pattern");
mntmNewPattern.setAction(actionAddPattern);
mnTextPatterns.add(mntmNewPattern);
JMenuItem mntmImportPatterns = new JMenuItem("Open File(s)..");
mntmImportPatterns.setAction(actionImportPatterns);
mnTextPatterns.add(mntmImportPatterns);
JMenuItem mntmSaveAsPatterns = new JMenuItem("Save as..");
mntmSaveAsPatterns.setAction(actionSaveAsPatterns);
mnTextPatterns.add(mntmSaveAsPatterns);
JMenuItem mntmResetDefaultPatterns = new JMenuItem("Reset to Defaults");
mntmResetDefaultPatterns.setAction(actionResetDefaultPatterns);
mnTextPatterns.add(mntmResetDefaultPatterns);
JMenuItem mntmSaveDefaultPatterns = new JMenuItem("Save as Defaults");
mntmSaveDefaultPatterns.setAction(actionSaveDefaultPatterns);
mnTextPatterns.add(mntmSaveDefaultPatterns);
JMenuItem mntmClearPatterns = new JMenuItem("Clear All");
mntmClearPatterns.setAction(actionClearPatterns);
mnTextPatterns.add(mntmClearPatterns);
JMenuItem mntmImportBEFeatures = new JMenuItem("Import Bulk Extractor features..");
mntmImportBEFeatures.setAction(actionImportBEPatterns);
mnTextPatterns.add(mntmImportBEFeatures);
JMenu mnHelp = new JMenu("Help");
mnHelp.setHorizontalAlignment(SwingConstants.RIGHT);
mnHelp.setMnemonic('H');
menuBar.add(mnHelp);
JMenuItem mntmOverview = new JMenuItem("Overview");
mnHelp.add(mntmOverview);
JMenuItem mntmAbout = new JMenuItem("About");
mntmAbout.setAction(actionAbout);
mnHelp.add(mntmAbout);
JSplitPane splitPane = new JSplitPane();
splitPane.setDividerLocation(250);
frmBitcuratorPdfRedact.getContentPane().add(splitPane, BorderLayout.CENTER);
Dimension minimumSize = new Dimension(500, 400);
JTabbedPane tabbedPane_1 = new JTabbedPane(JTabbedPane.TOP);
tabbedPane_1.setMinimumSize(minimumSize);
splitPane.setRightComponent(tabbedPane_1);
JPanel panel_Entities = new JPanel();
panel_Entities.setBorder(new EmptyBorder(10, 10, 10, 10));
tabbedPane_1.addTab("Named Entities", null, panel_Entities, null);
panel_Entities.setLayout(new BorderLayout(0, 0));
JTextArea txtrThisToolUses = new JTextArea();
txtrThisToolUses.setBackground(UIManager.getColor("Panel.background"));
txtrThisToolUses.setEditable(false);
txtrThisToolUses.setWrapStyleWord(true);
txtrThisToolUses.setLineWrap(true);
txtrThisToolUses
.setText("Named entities are people, places, and organizations detected in the text of PDF files you have added.");
panel_Entities.add(txtrThisToolUses, BorderLayout.NORTH);
//Set up the editor for the sport cells.
JComboBox<Action> patternAction_comboBox = new JComboBox<>();
patternAction_comboBox.addItem(Action.Ignore);
patternAction_comboBox.addItem(Action.Ask);
patternAction_comboBox.addItem(Action.Redact);
table_entities = new JTable();
table_entities.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table_entities.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
table_entities.setModel(tableModel_entities);
TableCellRenderer rend = table_entities.getTableHeader().getDefaultRenderer();
TableColumn tc0 = table_entities.getColumn(tableModel_entities.getColumnName(0));
tc0.setHeaderRenderer(rend);
tc0.setPreferredWidth(250);
TableColumn tc1 = table_entities.getColumn(tableModel_entities.getColumnName(1));
tc1.setHeaderRenderer(rend);
tc1.setPreferredWidth(150);
TableColumn tc2 = table_entities.getColumn(tableModel_entities.getColumnName(2));
tc2.setHeaderRenderer(rend);
//tc2.sizeWidthToFit();
tc2.setPreferredWidth(35);
TableColumn tc3 = table_entities.getColumn(tableModel_entities.getColumnName(3));
tc3.setHeaderRenderer(rend);
//tc3.sizeWidthToFit();
tc3.setPreferredWidth(35);
TableColumn policyColumn = table_entities.getColumn(tableModel_entities.getColumnName(4));
policyColumn.setHeaderRenderer(rend);
policyColumn.setPreferredWidth(100);
policyColumn.setCellEditor(new DefaultCellEditor(patternAction_comboBox));
//table_entities.setFillsViewportHeight(true);
table_entities.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
//table_entities.setPreferredSize(new Dimension(400, 300));
table_entities.getColumn(tableModel_entities.getColumnName(0)).setCellRenderer(
new DefaultTableCellRenderer() {
private static final long serialVersionUID = 1L;
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
JLabel superRenderer = (JLabel)super.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
String name = entityOrder.get(row);
EntityPattern e = entities.get(name);
superRenderer.setToolTipText(e.getExampleSentence());
return superRenderer;
}
});
table_entities.getColumn(tableModel_entities.getColumnName(4)).setCellRenderer(
new DefaultTableCellRenderer() {
private static final long serialVersionUID = 1L;
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
JLabel superRenderer = (JLabel)super.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if(backgroundColor == null) backgroundColor = getBackground();
Action action = (Action)tableModel_entities.getValueAt(row, column);
if(!isSelected) {
switch(action) {
case Ask:
superRenderer.setBackground(PreviewPanel.askColor);
break;
case Redact:
superRenderer.setBackground(PreviewPanel.redactColor);
break;
case Ignore:
superRenderer.setBackground(backgroundColor);
break;
}
}
return superRenderer;
}
});
JScrollPane entities_scrollPane = new JScrollPane(table_entities);
entities_scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel_Entities.add(entities_scrollPane, BorderLayout.CENTER);
JPanel panel_Patterns = new JPanel();
panel_Patterns.setBorder(new EmptyBorder(10, 10, 10, 10));
tabbedPane_1.addTab("Text Patterns", null, panel_Patterns, null);
panel_Patterns.setLayout(new BorderLayout(0, 0));
JTextArea textArea = new JTextArea();
textArea.setWrapStyleWord(true);
textArea.setText(
"Patterns are regular expressions used to redact matching text in PDFs. Add new patterns by clicking in the empty first row.");
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setBackground(UIManager.getColor("Button.background"));
panel_Patterns.add(textArea, BorderLayout.NORTH);
table_expressions = new JTable();
//table_expressions.setFillsViewportHeight(true);
table_expressions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//table_expressions.setPreferredSize(new Dimension(400, 300));
table_expressions.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
table_expressions.setModel(tableModel_patterns);
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
int rowAtPoint = table.rowAtPoint(SwingUtilities.convertPoint(popupMenu, new Point(0, 0), table));
if (rowAtPoint > -1) {
table.setRowSelectionInterval(rowAtPoint, rowAtPoint);
}
}
});
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
// TODO Auto-generated method stub
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
// TODO Auto-generated method stub
}
});
JMenuItem mntmDelete = new JMenuItem("Delete");
mntmDelete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int i = table_expressions.getSelectedRow();
expressions.remove(i);
tableModel_patterns.fireTableDataChanged();
}
});
popupMenu.add(mntmDelete);
JMenuItem mntmAdd = new JMenuItem("Add");
mntmAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int i = table_expressions.getSelectedRow();
expressions.add(i+1, new ExpressionPattern("", "", Action.Ask));
tableModel_patterns.fireTableDataChanged();
}
});
popupMenu.add(mntmAdd);
table_expressions.setComponentPopupMenu(popupMenu);
TableColumn patternPolicyColumn = table_expressions.getColumn(tableModel_patterns.getColumnName(2));
patternPolicyColumn.setCellEditor(new DefaultCellEditor(patternAction_comboBox));
table_expressions.getColumn(tableModel_patterns.getColumnName(2)).setCellRenderer(
new DefaultTableCellRenderer() {
private static final long serialVersionUID = 1L;
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
JLabel superRenderer = (JLabel)super.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if(backgroundColor == null) backgroundColor = getBackground();
Action action = (Action)tableModel_patterns.getValueAt(row, column);
if(!isSelected) {
switch(action) {
case Ask:
superRenderer.setBackground(PreviewPanel.askColor);
break;
case Redact:
superRenderer.setBackground(PreviewPanel.redactColor);
break;
case Ignore:
superRenderer.setBackground(backgroundColor);
break;
}
}
return superRenderer;
}
});
JScrollPane patterns_scrollPane = new JScrollPane(table_expressions);
patterns_scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel_Patterns.add(patterns_scrollPane, BorderLayout.CENTER);
JPanel panel_Files = new JPanel();
panel_Files.setMinimumSize(minimumSize);
splitPane.setLeftComponent(panel_Files);
panel_Files.setLayout(new BorderLayout(0, 0));
table = new JTable();
//table.setFillsViewportHeight(true);
table.setPreferredScrollableViewportSize(new Dimension(200, 600));
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
table.setModel(tableModel_pdfs);
table.getColumn(file_columnNames[0]).setCellRenderer(
new DefaultTableCellRenderer() {
private static final long serialVersionUID = 1L;
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
JLabel superRenderer = (JLabel)super.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
//Color backgroundColor = getBackground();
if(file_analyses.containsKey(pdfFiles.get(row))) {
PDFAnalysis a = file_analyses.get(pdfFiles.get(row));
if(a.error != null) {
superRenderer.setForeground(Color.red);
if(a.error.getCause() != null) {
superRenderer.setToolTipText(a.error.getCause().getMessage());
}
} else {
superRenderer.setForeground(Color.black);
superRenderer.setToolTipText(a.entities.length + " named entities");
}
} else {
superRenderer.setForeground(Color.gray);
superRenderer.setToolTipText("not analyzed");
}
return superRenderer;
}
});
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent mouseEvent) {
if (mouseEvent.getClickCount() == 2) {
int row = table.rowAtPoint(mouseEvent.getPoint());
if(0 <= row && row < pdfFiles.size()) {
redact(pdfFiles.get(row));
}
}
}
});
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel_Files.add(scrollPane, BorderLayout.CENTER);
JLabel lblStatus = new JLabel("output folder: none");
frmBitcuratorPdfRedact.getContentPane().add(lblStatus, BorderLayout.SOUTH);
frmBitcuratorPdfRedact.pack();
fileChooser_pdfs = new JFileChooser();
fileChooser_pdfs.setDialogTitle("Add PDF Files or Folders");
fileChooser_pdfs.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fileChooser_pdfs.setAcceptAllFileFilterUsed(false);
fileChooser_pdfs.setMultiSelectionEnabled(true);
fileChooser_pdfs.setFileFilter(new FileFilter() {
@Override
public boolean accept(File arg0) {
if (arg0.isDirectory())
return true;
if (arg0.getName().endsWith(".PDF"))
return true;
if (arg0.getName().endsWith(".pdf"))
return true;
return false;
}
@Override
public String getDescription() {
return "Folders and PDF Files";
}
});
fileChooser_textpattern = new JFileChooser();
fileChooser_textpattern.setDialogTitle("Import Text Patterns");
fileChooser_textpattern.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser_textpattern.setAcceptAllFileFilterUsed(false);
fileChooser_textpattern.setMultiSelectionEnabled(true);
fileChooser_textpattern.setFileFilter(new FileFilter() {
public boolean accept(File arg0) {
if(arg0.isDirectory())
return true;
if (arg0.getName().endsWith(".TXT"))
return true;
if (arg0.getName().endsWith(".txt"))
return true;
return false;
}
public String getDescription() {
return "Text files";
}
});
this.redactDialog = new RedactDialog();
}
private void loadExpressions() {
if(!new File(DEFAULT_PATTERNS_PATH).exists()) {
new File(DEFAULT_PATTERNS_PATH).getParentFile().mkdirs();
ExpressionPattern p = new ExpressionPattern("Social Security Number", "\\d{3}-\\d{2}-\\d{4}", Action.Redact);
TextPatternUtil.saveExpressionPatterns(new File(DEFAULT_PATTERNS_PATH), Collections.singletonList(p));
}
// name, regular expression, policy, notes
List<ExpressionPattern> list = TextPatternUtil.loadExpressionActionList(new File(DEFAULT_PATTERNS_PATH));
expressions.addAll(list);
}
private void clearPDFPaths() {
pdfFiles.clear();
tableModel_pdfs.fireTableDataChanged();
}
private void addPDFPaths(final File[] pdfPaths) throws Error {
SwingWorker<List<File>, File> sw = new SwingWorker<List<File>, File>() {
@Override
protected void process(List<File> chunks) {
Collections.sort(pdfFiles);
tableModel_pdfs.fireTableDataChanged();
}
File[] empty = new File[] {};
@Override
protected List<File> doInBackground() throws Exception {
doList(pdfPaths);
return pdfFiles;
}
private void doList(File[] paths) {
List<File> chunks = new ArrayList<>();
for (File file : paths) {
if (!file.isDirectory()) {
if (pdfFiles.contains(file))
continue;
pdfFiles.add(file);
chunks.add(file);
}
}
publish(chunks.toArray(empty));
for (File file : paths) {
if (file.isDirectory()) {
File[] dirFiles = file.listFiles(new java.io.FileFilter() {
@Override
public boolean accept(File f) {
if (f.isDirectory())
return true;
if (f.getName().endsWith(".PDF"))
return true;
if (f.getName().endsWith(".pdf"))
return true;
return false;
}
});
doList(dirFiles);
}
}
}
};
sw.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
switch (event.getPropertyName()) {
case "progress":
break;
case "state":
switch ((StateValue) event.getNewValue()) {
case DONE:
startEntityAnalysisWorker();
default:
}
}
}
});
sw.execute();
}
private void startEntityAnalysisWorker() {
AnalysisWorker pdfAnalysisWorker = null;
if(useSpacy) {
log.info("starting PDF analysis with spaCy");
pdfAnalysisWorker = new SpaceyAnalysisWorker(pdfFiles.toArray(EMPTY_FILE_ARRAY)) {
@Override
protected void process(List<PDFAnalysis> chunks) {
processAnalysisChunks(chunks);
}
};
} else {
log.info("starting PDF analysis with CoreNLP");
pdfAnalysisWorker = new CoreNLPAnalysisWorker(pdfFiles.toArray(EMPTY_FILE_ARRAY),
chckbxmntmDetectPersons.isSelected(),
chckbxmntmDetectPlaces.isSelected(),
chckbxmntmDetectOrganizations.isSelected()) {
@Override
protected void process(List<PDFAnalysis> chunks) {
processAnalysisChunks(chunks);
}
};
}
pdfAnalysisWorker.execute();
}
private void processAnalysisChunks(List<PDFAnalysis> chunks) {
for(PDFAnalysis a : chunks) {
if(a.entities != null && a.entities.length > 0) {
Arrays.stream(a.entities)
.forEach( x -> {
EntityPattern p = new EntityPattern(x[0], x[1], defaultAction);
p.setExampleSentence(x[2]);
if(!entities.containsKey(p.getLabel())) {
entities.put(p.getLabel(), p);
} else {
EntityPattern e = entities.get(p.getLabel());
if(x[2].length() < 200 && x[2].length() > e.getExampleSentence().length()) {
e.setExampleSentence(x[2]);
}
e.incr();
}
pattern_files.put(p.getLabel(), a.file);
});
}
file_analyses.put(a.file, a);
}
entityOrder.clear();
entityOrder.addAll(entities.keySet());
Collections.sort(entityOrder);
tableModel_entities.fireTableDataChanged();
table.repaint();
}
private void redact(File file) {
// TODO Alert if redacted file already exists..
List<TextPattern> filePatterns = new ArrayList<>();
for(String key : pattern_files.keySet()) {
if(pattern_files.get(key).contains(file)) {
EntityPattern e = entities.get(key);
if(!Action.Ignore.equals(e.policy)) filePatterns.add(e);
}
}
File outFile = getOutputFile(file);
filePatterns = filePatterns.stream().filter(p -> p != null).collect(Collectors.toList());
Collections.sort(filePatterns, Comparator.comparing(x -> { return ((TextPattern)x).getLabel();}));
filePatterns.addAll(this.expressions.stream()
.filter(p -> !p.policy.equals(Action.Ignore)).collect(Collectors.toList()));
try {
this.redactDialog.startDoc(file, outFile, filePatterns);
this.redactDialog.setVisible(true);
this.redactDialog.tableModel.fireTableDataChanged();
} catch (IOException e) {
e.printStackTrace();
}
}
private File getOutputFile(File inputFile) {
File outFile = Paths.get(outPath, inputFile.getAbsolutePath()).toFile();
return outFile;
}
}
| 35,674 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
AddPDFsActionListener.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/AddPDFsActionListener.java | package bca.redact;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AddPDFsActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
| 263 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
SimpleAboutDialog.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/SimpleAboutDialog.java | package bca.redact;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.nio.charset.Charset;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.apache.commons.io.IOUtils;
public class SimpleAboutDialog extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
public SimpleAboutDialog(JFrame parent) {
super(parent, "About BitCurator PDF Redactor", true);
Box b = Box.createVerticalBox();
b.add(Box.createGlue());
String aboutHTML = null;
try {
aboutHTML = IOUtils.resourceToString("/about.html", Charset.forName("UTF-8"));
} catch (IOException e) {
throw new Error("Unexpected IO error", e);
}
b.add(new JLabel(aboutHTML));
b.add(Box.createGlue());
getContentPane().add(b, "Center");
JPanel p2 = new JPanel();
JButton ok = new JButton("Ok");
p2.add(ok);
getContentPane().add(p2, "South");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setVisible(false);
}
});
setSize(350, 250);
}
}
| 1,257 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
SpaceyAnalysisWorker.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/SpaceyAnalysisWorker.java | package bca.redact;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.log4j.Logger;
public class SpaceyAnalysisWorker extends AnalysisWorker {
private static final Logger log = Logger.getLogger(SpaceyAnalysisWorker.class);
File[] pdfs;
SpaceyAnalysisWorker(File[] pdfs) {
this.pdfs = pdfs;
}
@Override
protected Set<PDFAnalysis> doInBackground() {
Set<PDFAnalysis> analyses = new HashSet<>();
int errors = 0;
ProcessBuilder processBuilder = new ProcessBuilder("D:/test.bat", "ABC", "XYZ");
processBuilder.directory(new File("D:/"));
processBuilder.redirectErrorStream(true);
//processBuilder.
Process p;
try {
p = processBuilder.start();
p.waitFor();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (File f : pdfs) {
try {
throw new AnalysisException(f, new NotImplementedException("Not yet implemented"));
//List<String[]> pdfentities = new ArrayList<>();
//for (CoreEntityMention cem : doc.entityMentions()) {
// pdfentities.add(new String[] {cem.text(), cem.entityType()});
//}
//PDFAnalysis analysis = new PDFAnalysis(f, pdfentities.toArray(empty));
//analyses.add(analysis);
//publish(analysis);
} catch (AnalysisException e) {
PDFAnalysis analysis = new PDFAnalysis(f, e);
analyses.add(analysis);
publish(analysis);
} finally {
}
}
log.error("There were PDF Entity Analysis errors: "+errors);
return analyses;
}
}
| 1,703 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
Action.java | /FileExtraction/Java_unseen/BitCurator_bitcurator-redact-pdf/src/main/java/bca/redact/Action.java | package bca.redact;
public enum Action {
Redact, Ignore, Ask
}
| 65 | Java | .java | BitCurator/bitcurator-redact-pdf | 14 | 1 | 0 | 2018-10-22T17:55:05Z | 2023-04-11T03:13:44Z |
Sphere.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/Sphere.java | package uk.co.harryyoud.biospheres;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.math.MutableBoundingBox;
import net.minecraft.world.IWorld;
import net.minecraft.world.biome.Biome;
public class Sphere {
private final IWorld world;
private final BlockPos centre;
private final ChunkPos centreChunk;
private final Random rnd;
private final Biome biome;
static int minRadius;
static int maxRadius;
static int midY;
public final int radius;
public static final int gridSize = 15;
private HashMap<Direction, BlockPos> bridgeJoin = new HashMap<Direction, BlockPos>();
private ArrayList<MutableBoundingBox> domeCutouts = new ArrayList<MutableBoundingBox>();
@SuppressWarnings("serial")
public static Map<BlockPos, Sphere> sphereCache = new LinkedHashMap<BlockPos, Sphere>(500, 0.7f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<BlockPos, Sphere> eldest) {
return size() > 500;
}
};
private Sphere(IWorld world, BlockPos centrePos) {
this.world = world;
this.centre = centrePos;
this.centreChunk = new ChunkPos(centrePos);
this.rnd = new Random(centrePos.hashCode() * world.getSeed());
this.biome = this.getRandomBiome(this.rnd);
this.radius = this.rnd.nextInt((maxRadius - minRadius) + 1) + minRadius;
}
public static Sphere fromCentre(IWorld worldIn, BlockPos centrePos) {
if (sphereCache.containsKey(centrePos)) {
return sphereCache.get(centrePos);
}
Sphere sphere = new Sphere(worldIn, centrePos);
sphereCache.put(centrePos, sphere);
return sphere;
}
public static Sphere fromCentreChunk(IWorld worldIn, ChunkPos chunkPos) {
BlockPos pos = chunkPos.getBlock(8, Sphere.midY, 8);
return Sphere.fromCentre(worldIn, pos);
}
public static Sphere getClosest(IWorld worldIn, BlockPos pos) {
ChunkPos chunkPos = new ChunkPos(pos);
int chunkOffsetX = (int) Math.floor(Math.IEEEremainder(chunkPos.x, Sphere.gridSize));
int chunkOffsetZ = (int) Math.floor(Math.IEEEremainder(chunkPos.z, Sphere.gridSize));
return Sphere.fromCentreChunk(worldIn, new ChunkPos(chunkPos.x - chunkOffsetX, chunkPos.z - chunkOffsetZ));
}
private Biome getRandomBiome(Random rnd) {
Biome biome = BiosphereBiomeProvider.biomesArray[(rnd.nextInt(BiosphereBiomeProvider.biomesArray.length))];
return biome;
}
public int getDistanceToCenter(BlockPos pos) {
return (int) Math.floor(Math.sqrt(this.getCentre().distanceSq(pos.getX(), pos.getY(), pos.getZ(), false)));
}
public Random getRandom() {
return this.rnd;
}
public ChunkPos getCentreChunk() {
return this.centreChunk;
}
public BlockPos getCentre() {
return this.centre;
}
public Biome getBiome() {
return this.biome;
}
public BlockPos computeBridgeJoin(BiosphereChunkGenerator chunkGen, Direction dir) {
BlockPos fromCache = this.bridgeJoin.get(dir);
if (fromCache != null) {
return fromCache;
}
BlockPos.Mutable join = new BlockPos.Mutable(this.getCentre()).move(dir, this.radius);
int domeHeight;
do {
join.move(dir.getOpposite(), 1);
ChunkPos joinChunk = new ChunkPos(join);
double[][][] noisesFrom = chunkGen.getNoiseForChunk(this.world, joinChunk);
// height of dome is pythag, where radius is hyp, and dome height and horizontal
// distance from centre are sides
domeHeight = Sphere.midY + (int) Math.round(Math.sqrt(Math.abs(Math.pow(this.radius, 2) - Math
.pow(Utils.getCoord(this.getCentre(), dir.getAxis()) - Utils.getCoord(join, dir.getAxis()), 2))));
join.setY(Utils.topBlockFromNoise(noisesFrom, Math.abs(join.getX()) % 16, Math.abs(join.getZ()) % 16,
domeHeight, chunkGen.getSeaLevel(), (i) -> chunkGen.correctYValue(i)));
if (Utils.getCoord(this.getCentre(), dir.getAxis()) == Utils.getCoord(join, dir.getAxis())) {
break;
}
} while (join.getY() >= domeHeight);
join.move(dir, 1);
ChunkPos joinChunk = new ChunkPos(join);
double[][][] noisesFrom = chunkGen.getNoiseForChunk(this.world, joinChunk);
domeHeight = Sphere.midY + (int) Math.round(Math.sqrt(Math.abs(Math.pow(this.radius, 2)
- Math.pow(Utils.getCoord(this.getCentre(), dir.getAxis()) - Utils.getCoord(join, dir.getAxis()), 2))));
if (domeHeight < Sphere.midY + 3) {
domeHeight = Sphere.midY + 10;
}
join.setY(Utils.topBlockFromNoise(noisesFrom, Math.abs(join.getX()) % 16, Math.abs(join.getZ()) % 16,
domeHeight, chunkGen.getSeaLevel(), (i) -> chunkGen.correctYValue(i)));
BlockPos joinIm = join.toImmutable();
this.bridgeJoin.put(dir, joinIm);
BlockPos.Mutable one = new BlockPos.Mutable(joinIm);
BlockPos.Mutable two = new BlockPos.Mutable(joinIm);
// This will be to the side of the middle block of the bridge
one.move(dir.rotateY(), chunkGen.BRIDGE_WIDTH).move(Direction.UP);
two.move(dir.rotateYCCW(), chunkGen.BRIDGE_WIDTH);
two.move(dir.getOpposite(),
Math.abs(Utils.getCoord(joinIm, dir.getAxis()) - Utils.getCoord(this.getCentre(), dir.getAxis())));
two.move(Direction.UP, chunkGen.BRIDGE_HEIGHT);
this.domeCutouts.add(new MutableBoundingBox(one, two));
return joinIm;
}
public HashMap<Direction, BlockPos> getBridgeJoins() {
return this.getBridgeJoins();
}
public ArrayList<MutableBoundingBox> getCutouts() {
return this.domeCutouts;
}
}
| 5,430 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
Biospheres.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/Biospheres.java | package uk.co.harryyoud.biospheres;
import java.nio.file.Paths;
import java.util.Properties;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mojang.datafixers.Dynamic;
import com.mojang.datafixers.types.JsonOps;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.NBTDynamicOps;
import net.minecraft.server.dedicated.PropertyManager;
import net.minecraft.server.dedicated.ServerProperties;
import net.minecraft.world.WorldType;
import net.minecraftforge.fml.ExtensionPoint;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper.UnableToAccessFieldException;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper.UnableToFindFieldException;
import net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.network.FMLNetworkConstants;
import uk.co.harryyoud.biospheres.config.BiosphereConfig;
import uk.co.harryyoud.biospheres.config.BiosphereGenSettingsSerializer;
@Mod(Biospheres.MODID)
public class Biospheres {
public static final String MODID = "biospheres";
public static final Logger LOGGER = LogManager.getLogger(MODID);
public static final BiosphereWorldType worldType = new BiosphereWorldType();
public Biospheres() {
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::dedicatedServerSetup);
// Ignore server and client version mismatch, since mod is only relevant on
// logical server
ModLoadingContext.get().registerExtensionPoint(ExtensionPoint.DISPLAYTEST,
() -> Pair.of(() -> FMLNetworkConstants.IGNORESERVERONLY, (a, b) -> true));
BiosphereConfig.setup();
}
public void dedicatedServerSetup(FMLDedicatedServerSetupEvent event) {
ServerProperties props = event.getServerSupplier().get().getServerProperties();
if (!BiosphereConfig.shouldInjectWorldType) {
System.out.println("World type injection disabled, not injecting biospheres world type");
return;
}
if (props.worldType != WorldType.DEFAULT) {
System.out.println("World type injection enabled, but level-type is not default, aborting");
return;
}
System.out.println(String
.format("Biospheres injection is enabled, injecting biospheres level-type and generator-settings"));
System.out.println(String.format("Original level-type=\"%s\"", props.worldType.getName()));
System.out.println(String.format("Original generator-settings=\"%s\"", props.generatorSettings));
String newGenSettings = Dynamic
.convert(NBTDynamicOps.INSTANCE, JsonOps.INSTANCE,
(CompoundNBT) (new BiosphereGenSettingsSerializer()).toNBT(NBTDynamicOps.INSTANCE).getValue())
.toString();
// First, we'll override the server.properties in memory
try {
ObfuscationReflectionHelper.setPrivateValue(ServerProperties.class, props, worldType, "field_219023_q");
if (props.generatorSettings.isEmpty()) {
ObfuscationReflectionHelper.setPrivateValue(ServerProperties.class, props, newGenSettings,
"field_219024_r");
}
} catch (UnableToFindFieldException | UnableToAccessFieldException e) {
throw new Error("Reflection failed when trying to edit the level-type and generator-settings properties",
e);
}
// Then, we replace them and right them to disk
Properties p = PropertyManager.load(Paths.get("server.properties"));
p.replace("level-type", "default", worldType.getName());
p.replace("generator-settings", "", newGenSettings);
props = new ServerProperties(p);
props.save(Paths.get("server.properties"));
}
} | 3,772 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
BlockPosIterator.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/BlockPosIterator.java | package uk.co.harryyoud.biospheres;
import java.util.Iterator;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.math.SectionPos;
public class BlockPosIterator implements Iterable<BlockPos>, Iterator<BlockPos> {
private final BlockPos.Mutable pos;
private final int minX;
private final int minY;
private final int minZ;
private final int maxX;
private final int maxY;
private final int maxZ;
public BlockPosIterator(ChunkPos chunkPos) {
this.minX = chunkPos.getXStart();
this.minY = 0;
this.minZ = chunkPos.getZStart();
this.maxX = chunkPos.getXEnd();
this.maxY = 255;
this.maxZ = chunkPos.getZEnd();
this.pos = new BlockPos.Mutable(this.minX, this.minY, this.minZ);
}
public BlockPosIterator(SectionPos secPos) {
this.minX = secPos.getWorldStartX();
this.minY = secPos.getWorldStartY();
this.minZ = secPos.getWorldStartZ();
this.maxX = secPos.getWorldEndX();
this.maxY = secPos.getWorldEndY();
this.maxZ = secPos.getWorldEndZ();
this.pos = new BlockPos.Mutable(this.minX, this.minY, this.minZ);
}
@Override
public boolean hasNext() {
boolean xIsMax = this.pos.getX() == this.maxX;
boolean yIsMax = this.pos.getY() == this.maxY;
boolean zIsMax = this.pos.getZ() == this.maxZ;
return !(xIsMax && yIsMax && zIsMax);
}
@Override
public BlockPos next() {
BlockPos ret = this.pos.toImmutable();
if (this.pos.getZ() < this.maxZ) {
this.pos.setZ(this.pos.getZ() + 1);
return ret;
}
if (this.pos.getY() < this.maxY) {
this.pos.setY(this.pos.getY() + 1);
this.pos.setZ(this.minZ);
return ret;
}
if (this.pos.getX() < this.maxX) {
this.pos.setX(this.pos.getX() + 1);
this.pos.setY(this.minY);
this.pos.setZ(this.minZ);
return ret;
}
return null;
}
@Override
public Iterator<BlockPos> iterator() {
return this;
}
}
| 1,873 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
BiosphereBiomeProvider.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/BiosphereBiomeProvider.java | package uk.co.harryyoud.biospheres;
import java.util.HashSet;
import java.util.Set;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IWorld;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.provider.BiomeProvider;
import net.minecraft.world.biome.provider.OverworldBiomeProviderSettings;
import net.minecraftforge.registries.ForgeRegistries;
import uk.co.harryyoud.biospheres.config.BiosphereConfig;
public class BiosphereBiomeProvider extends BiomeProvider {
public final IWorld world;
public static final Set<Biome> biomes;
public static final Biome[] biomesArray;
static {
biomes = new HashSet<Biome>(ForgeRegistries.BIOMES.getValues());
biomes.removeIf((biome) -> BiosphereConfig.bannedBiomeCategories.contains(biome.getCategory()));
biomes.removeIf(
(biome) -> BiosphereConfig.bannedBiomes.contains(ForgeRegistries.BIOMES.getKey(biome).toString()));
biomesArray = biomes.toArray(new Biome[biomes.size()]);
}
protected BiosphereBiomeProvider(IWorld worldIn, OverworldBiomeProviderSettings settingsProvider) {
super(biomes);
this.world = worldIn;
}
@Override
public Biome getNoiseBiome(int x, int y, int z) {
// We get passed a biome coordinate, which is bitshifted to create our
// approximate block coordinate
x = (x << 2);
z = (z << 2);
BlockPos pos = new BlockPos(x, y, z);
Sphere sphere = Sphere.getClosest(this.world, pos);
return sphere.getBiome();
}
}
| 1,453 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
BiosphereWorldType.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/BiosphereWorldType.java | package uk.co.harryyoud.biospheres;
import com.mojang.datafixers.Dynamic;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screen.CreateWorldScreen;
import net.minecraft.nbt.NBTDynamicOps;
import net.minecraft.world.World;
import net.minecraft.world.WorldType;
import net.minecraft.world.biome.provider.OverworldBiomeProviderSettings;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.gen.ChunkGenerator;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import uk.co.harryyoud.biospheres.config.BiosphereConfig;
import uk.co.harryyoud.biospheres.config.BiosphereGenSettingsSerializer;
import uk.co.harryyoud.biospheres.config.BiosphereGenSettingsSerializer.BiosphereGenSettings;
import uk.co.harryyoud.biospheres.gui.CreateBiospheresWorldScreen;
public class BiosphereWorldType extends WorldType {
public BiosphereWorldType() {
super("biospheres");
}
@Override
public ChunkGenerator<?> createChunkGenerator(World world) {
if (world.getDimension().getType() != DimensionType.OVERWORLD) {
return super.createChunkGenerator(world);
}
OverworldBiomeProviderSettings biomeProvSettings = new OverworldBiomeProviderSettings(world.getWorldInfo());
BiosphereBiomeProvider biomeProv = new BiosphereBiomeProvider(world, biomeProvSettings);
BiosphereGenSettings settings = BiosphereGenSettingsSerializer
.get(new Dynamic<>(NBTDynamicOps.INSTANCE, world.getWorldInfo().getGeneratorOptions()));
return new BiosphereChunkGenerator(world, biomeProv, settings);
}
@Override
@OnlyIn(Dist.CLIENT)
public void onCustomizeButton(Minecraft mc, CreateWorldScreen gui) {
mc.displayGuiScreen(new CreateBiospheresWorldScreen(gui, gui.chunkProviderSettingsJson));
}
@Override
public String getTranslationKey() {
return "biospheres.generatorname";
}
@Override
public boolean hasCustomOptions() {
return true;
}
@Override
public float getCloudHeight() {
return BiosphereConfig.cloudHeight;
}
}
| 2,021 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
Utils.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/Utils.java | package uk.co.harryyoud.biospheres;
import java.util.function.IntFunction;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
public class Utils {
public static int topBlockFromNoise(double[][][] noise, int x, int z, int topLimit, int bottomLimit,
IntFunction<Integer> yCorrection) {
for (int y = topLimit; y >= bottomLimit; y--) {
if (noise[x][yCorrection.apply(y)][z] > 0.0D) {
return y;
}
}
return bottomLimit - 1;
}
public static int getCoord(BlockPos pos, Direction.Axis axis) {
return axis.getCoordinate(pos.getX(), pos.getY(), pos.getZ());
}
public static ChunkPos moveChunk(ChunkPos chunkPos, Direction dir, int amount) {
switch (dir) {
case NORTH:
return new ChunkPos(chunkPos.x, chunkPos.z - amount);
case SOUTH:
return new ChunkPos(chunkPos.x, chunkPos.z + amount);
case WEST:
return new ChunkPos(chunkPos.x - amount, chunkPos.z);
case EAST:
return new ChunkPos(chunkPos.x + amount, chunkPos.z);
default:
throw new IllegalStateException("Unable to get offset chunk in Y direction");
}
}
public static boolean inIncRange(int num, int range1, int range2) {
return Math.min(range1, range2) <= num && num <= Math.max(range1, range2);
}
}
| 1,279 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
BiosphereChunkGenerator.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/BiosphereChunkGenerator.java | package uk.co.harryyoud.biospheres;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.BushBlock;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.ReportedException;
import net.minecraft.tags.BlockTags;
import net.minecraft.util.Direction;
import net.minecraft.util.SharedSeedRandom;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.MutableBoundingBox;
import net.minecraft.world.IWorld;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.BiomeManager;
import net.minecraft.world.biome.provider.BiomeProvider;
import net.minecraft.world.chunk.IChunk;
import net.minecraft.world.gen.GenerationStage;
import net.minecraft.world.gen.Heightmap;
import net.minecraft.world.gen.INoiseGenerator;
import net.minecraft.world.gen.NoiseChunkGenerator;
import net.minecraft.world.gen.OverworldChunkGenerator;
import net.minecraft.world.gen.WorldGenRegion;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper.UnableToAccessFieldException;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper.UnableToFindFieldException;
import net.minecraftforge.registries.ForgeRegistries;
import uk.co.harryyoud.biospheres.config.BiosphereGenSettingsSerializer.BiosphereGenSettings;
import uk.co.harryyoud.biospheres.wrappers.IChunkWrapper;
import uk.co.harryyoud.biospheres.wrappers.IWorldWrapper;
public class BiosphereChunkGenerator extends OverworldChunkGenerator {
private final BlockState DOME_BLOCK;
private final BlockState AIR = Blocks.AIR.getDefaultState();
private final BlockState OUTSIDE_FILLER_BLOCK;
private final BlockState BRIDGE_BLOCK;
private final BlockState FENCE_BLOCK = Blocks.OAK_FENCE.getDefaultState();
private static final ArrayList<Block> BANNED_BLOCKS = new ArrayList<Block>(
Arrays.asList(Blocks.AIR, Blocks.WATER, Blocks.LAVA));
private final ArrayList<Block> ALLOWED_BLOCKS = new ArrayList<Block>(
Arrays.asList(AIR.getBlock(), FENCE_BLOCK.getBlock()));
public final int BRIDGE_WIDTH = 2;
public final int BRIDGE_HEIGHT = 4;
private final INoiseGenerator surfaceDepthNoise2;
private final BiosphereGenSettings genSettings;
private static final int noiseSizeX = 4;
private static final int noiseSizeY = 32;
private static final int noiseSizeZ = 4;
private static final int verticalNoiseGranularity = 8;
private static final int horizontalNoiseGranularity = 4;
@SuppressWarnings("serial")
private final Map<ChunkPos, double[][][]> depthNoiseCache = new LinkedHashMap<ChunkPos, double[][][]>(500, 0.7f,
true) {
@Override
protected boolean removeEldestEntry(Map.Entry<ChunkPos, double[][][]> eldest) {
return size() > 500;
}
};
public BiosphereChunkGenerator(IWorld worldIn, BiomeProvider biomeProviderIn, BiosphereGenSettings genSettings) {
super(worldIn, biomeProviderIn, genSettings);
this.genSettings = genSettings;
this.DOME_BLOCK = this.genSettings.domeBlock;
this.BRIDGE_BLOCK = this.genSettings.bridgeBlock;
this.OUTSIDE_FILLER_BLOCK = this.genSettings.outsideFillerBlock;
this.ALLOWED_BLOCKS.add(DOME_BLOCK.getBlock());
this.ALLOWED_BLOCKS.add(BRIDGE_BLOCK.getBlock());
this.ALLOWED_BLOCKS.add(OUTSIDE_FILLER_BLOCK.getBlock());
Sphere.minRadius = this.genSettings.sphereMinRadius;
Sphere.maxRadius = this.genSettings.sphereMaxRadius;
Sphere.midY = this.genSettings.sphereMidY;
try {
this.surfaceDepthNoise2 = (INoiseGenerator) ObfuscationReflectionHelper
.getPrivateValue(NoiseChunkGenerator.class, this, "field_222571_r");
} catch (UnableToAccessFieldException | UnableToFindFieldException e) {
throw new Error();
}
}
@Override
// build surface;
public void func_225551_a_(WorldGenRegion region, IChunk chunkIn) {
Sphere sphere = Sphere.getClosest(region, chunkIn.getPos().asBlockPos());
for (BlockPos pos : new BlockPosIterator(chunkIn.getPos())) {
double sphereDistance = sphere.getDistanceToCenter(pos);
if (pos.getY() == sphere.getCentre().getY() && sphereDistance <= sphere.radius) {
// Only run surface builder for each x, z once (one y value)
Biome biome = region.getBiome(pos);
biome.buildSurface(sphere.getRandom(), chunkIn, pos.getX(), pos.getZ(),
chunkIn.getTopBlockY(Heightmap.Type.WORLD_SURFACE_WG, pos.getX(), pos.getZ()),
this.getSurfaceDepthNoise(pos), this.genSettings.getDefaultBlock(),
this.genSettings.getDefaultFluid(), this.getSeaLevel(), region.getSeed());
}
}
}
@Override
public void decorate(WorldGenRegion region) {
IWorldWrapper worldWrapper = new IWorldWrapper(region, this.getSeaLevel());
worldWrapper.setBlockStatePredicate((pos) -> {
@SuppressWarnings("deprecation")
Sphere sphere = Sphere.getClosest(region.getWorld(), pos);
return sphere.getDistanceToCenter(pos) < sphere.radius;
});
// COPY PASTED FROM PARENT, with region replaced with worldWrapper
int i = region.getMainChunkX();
int j = region.getMainChunkZ();
int k = i * 16;
int l = j * 16;
BlockPos blockpos = new BlockPos(k, 0, l);
Biome biome = this.getBiome(region.getBiomeManager(), blockpos.add(8, 8, 8));
SharedSeedRandom sharedseedrandom = new SharedSeedRandom();
long i1 = sharedseedrandom.setDecorationSeed(region.getSeed(), k, l);
for (GenerationStage.Decoration generationstage$decoration : GenerationStage.Decoration.values()) {
try {
biome.decorate(generationstage$decoration, this, worldWrapper, i1, sharedseedrandom, blockpos);
} catch (Exception exception) {
CrashReport crashreport = CrashReport.makeCrashReport(exception, "Biome decoration");
crashreport.makeCategory("Generation").addDetail("CenterX", i).addDetail("CenterZ", j)
.addDetail("Step", generationstage$decoration).addDetail("Seed", i1)
.addDetail("Biome", ForgeRegistries.BIOMES.getKey(biome));
throw new ReportedException(crashreport);
}
}
// END COPY-PASTE
IChunk chunkIn = region.getChunk(region.getMainChunkX(), region.getMainChunkZ());
Sphere sphere = Sphere.getClosest(region, chunkIn.getPos().asBlockPos());
for (BlockPos pos : new BlockPosIterator(chunkIn.getPos())) {
double sphereDistance = sphere.getDistanceToCenter(pos);
BlockState prevState = region.getBlockState(pos);
BlockState state = null;
for (int d = 0; d < 4; d++) {
sphere.computeBridgeJoin(this, Direction.byHorizontalIndex(d));
}
if (sphereDistance == sphere.radius) {
if (BANNED_BLOCKS.contains(prevState.getBlock()) || prevState.isAir(region, pos)
|| prevState.isFoliage(region, pos) || prevState.getBlock() instanceof BushBlock
|| prevState.getBlock().isIn(BlockTags.LEAVES) || !prevState.isSolid()
|| (chunkIn.getTopBlockY(Heightmap.Type.WORLD_SURFACE_WG, pos.getX(), pos.getZ()) == pos.getY()
- 1) && !ALLOWED_BLOCKS.contains(region.getBlockState(pos).getBlock())) {
state = DOME_BLOCK;
}
for (MutableBoundingBox box : sphere.getCutouts()) {
if (box.isVecInside(pos) && state != null && state.getBlock() == DOME_BLOCK.getBlock()) {
state = AIR;
break;
}
}
}
if (sphereDistance > sphere.radius) {
// Don't remove blocks that have light values > 0, since the light engine gets
// annoyed
if (!ALLOWED_BLOCKS.contains(prevState.getBlock()) && !region.isAirBlock(pos)
&& prevState.getLightValue(region, pos) == 0) {
state = AIR; // Clean up anything outside the spheres that isn't meant to be there
}
}
if (state != null) {
if (state == AIR) {
region.removeBlock(pos, false);
} else {
region.setBlockState(pos, state, 3);
}
}
}
}
@SuppressWarnings("deprecation")
@Override
public void makeBase(IWorld worldIn, IChunk chunkIn) {
double[][][] noises = this.getNoiseForChunk(worldIn, chunkIn.getPos());
Sphere sphere = Sphere.getClosest(worldIn, chunkIn.getPos().asBlockPos());
for (BlockPos pos : new BlockPosIterator(chunkIn.getPos())) {
BlockState state = null;
int sphereDistance = sphere.getDistanceToCenter(pos);
if (pos.getY() < this.getSeaLevel() && sphereDistance < sphere.radius) {
state = this.genSettings.getDefaultFluid();
}
if (noises[Math.abs(pos.getX()) % 16][this.correctYValue(pos.getY())][Math.abs(pos.getZ()) % 16] > 0.0D) {
if (sphereDistance <= sphere.radius) {
state = this.genSettings.getDefaultBlock();
}
}
if (state != null && !state.isAir()) {
chunkIn.setBlockState(pos, state, false);
}
if (sphereDistance > sphere.radius) {
chunkIn.setBlockState(pos, OUTSIDE_FILLER_BLOCK, false);
}
if (sphereDistance >= sphere.radius) {
Direction dir = null;
if (Utils.inIncRange(pos.getX(), sphere.getCentre().getX() + BRIDGE_WIDTH,
sphere.getCentre().getX() - BRIDGE_WIDTH)) {
if (pos.getZ() < sphere.getCentre().getZ()) {
dir = Direction.NORTH;
} else if (pos.getZ() > sphere.getCentre().getZ()) {
dir = Direction.SOUTH;
}
}
if (Utils.inIncRange(pos.getZ(), sphere.getCentre().getZ() + BRIDGE_WIDTH,
sphere.getCentre().getZ() - BRIDGE_WIDTH)) {
if (pos.getX() < sphere.getCentre().getX()) {
dir = Direction.WEST;
} else if (pos.getX() > sphere.getCentre().getX()) {
dir = Direction.EAST;
}
}
if (dir == null) {
continue;
}
Direction.Axis axis = dir.getAxis();
Direction.Axis otherAxis = dir.rotateY().getAxis();
Sphere nextClosestSphere = Sphere.getClosest(worldIn,
Utils.moveChunk(sphere.getCentreChunk(), dir, Sphere.gridSize).asBlockPos());
BlockPos aimFor = nextClosestSphere.computeBridgeJoin(this, dir.getOpposite());
BlockPos aimFrom = sphere.computeBridgeJoin(this, dir);
int diffDenom = Utils.getCoord(aimFrom, axis) - Utils.getCoord(aimFor, axis);
if (diffDenom == 0) {
diffDenom = 1;
}
// m = Δy/Δx
double gradient = ((double) (aimFrom.getY() - aimFor.getY())) / (diffDenom);
// y = mx + c, where x is the distance from "0" (aimFrom)
double newY = Math.round(
(gradient * (Utils.getCoord(pos, axis) - Utils.getCoord(aimFrom, axis))) + aimFrom.getY());
if (Utils.inIncRange(Utils.getCoord(pos, axis), Utils.getCoord(aimFrom, axis),
Utils.getCoord(aimFor, axis))) {
if (pos.getY() == newY) {
chunkIn.setBlockState(pos, BRIDGE_BLOCK, false);
}
if (pos.getY() == newY + 1 && (Utils.getCoord(pos,
otherAxis) == Utils.getCoord(sphere.getCentre(), otherAxis) + BRIDGE_WIDTH
|| Utils.getCoord(pos, otherAxis) == Utils.getCoord(sphere.getCentre(), otherAxis)
- BRIDGE_WIDTH)) {
chunkIn.setBlockState(pos, FENCE_BLOCK, false);
chunkIn.markBlockForPostprocessing(pos);
}
}
}
}
}
// Fetch noises from the cache or calculate if not there
double[][][] getNoiseForChunk(IWorld worldIn, ChunkPos chunkPos) {
if (this.depthNoiseCache.containsKey(chunkPos)) {
return depthNoiseCache.get(chunkPos);
}
double[][][] depthNoise = this.calcNoiseForChunk(worldIn, chunkPos);
depthNoiseCache.put(chunkPos, depthNoise);
return depthNoise;
}
// This is essentially lifted from OverworldChunkGenerator, but modified to
// return a 3d matrix of noise values so we can cache them for repeated use
private double[][][] calcNoiseForChunk(IWorld worldIn, ChunkPos chunkPos) {
int chunkXPos = chunkPos.x;
int chunkXStart = chunkPos.getXStart();
int chunkZPos = chunkPos.z;
int chunkZStart = chunkPos.getZStart();
double[][][] noises = new double[2][noiseSizeZ + 1][noiseSizeY + 1];
double[][][] finalNoises = new double[16][256][16];
for (int zNoiseOffset = 0; zNoiseOffset < noiseSizeZ + 1; ++zNoiseOffset) {
noises[0][zNoiseOffset] = new double[noiseSizeY + 1];
this.fillNoiseColumn(noises[0][zNoiseOffset], chunkXPos * noiseSizeX,
chunkZPos * noiseSizeZ + zNoiseOffset);
noises[1][zNoiseOffset] = new double[noiseSizeY + 1];
}
for (int xNoiseOffset = 0; xNoiseOffset < noiseSizeX; ++xNoiseOffset) {
for (int zNoiseOffset = 0; zNoiseOffset < noiseSizeZ + 1; ++zNoiseOffset) {
this.fillNoiseColumn(noises[1][zNoiseOffset], chunkXPos * noiseSizeX + xNoiseOffset + 1,
chunkZPos * noiseSizeZ + zNoiseOffset);
}
for (int zNoiseOffset = 0; zNoiseOffset < noiseSizeZ; ++zNoiseOffset) {
for (int yNoiseOffset = noiseSizeY - 1; yNoiseOffset >= 0; --yNoiseOffset) {
double noise000 = noises[0][zNoiseOffset][yNoiseOffset];
double noise010 = noises[0][zNoiseOffset + 1][yNoiseOffset];
double noise100 = noises[1][zNoiseOffset][yNoiseOffset];
double noise110 = noises[1][zNoiseOffset + 1][yNoiseOffset];
double noise001 = noises[0][zNoiseOffset][yNoiseOffset + 1];
double noise011 = noises[0][zNoiseOffset + 1][yNoiseOffset + 1];
double noise101 = noises[1][zNoiseOffset][yNoiseOffset + 1];
double noise111 = noises[1][zNoiseOffset + 1][yNoiseOffset + 1];
for (int yGranularityOffset = verticalNoiseGranularity
- 1; yGranularityOffset >= 0; --yGranularityOffset) {
int worldY = yNoiseOffset * verticalNoiseGranularity + yGranularityOffset;
double yNoiseScale = (double) yGranularityOffset / (double) verticalNoiseGranularity;
double d6 = MathHelper.lerp(yNoiseScale, noise000, noise001);
double d7 = MathHelper.lerp(yNoiseScale, noise100, noise101);
double d8 = MathHelper.lerp(yNoiseScale, noise010, noise011);
double d9 = MathHelper.lerp(yNoiseScale, noise110, noise111);
for (int XGranularityOffset = 0; XGranularityOffset < horizontalNoiseGranularity; ++XGranularityOffset) {
int worldX = chunkXStart + xNoiseOffset * horizontalNoiseGranularity + XGranularityOffset;
double xNoiseScale = (double) XGranularityOffset / (double) horizontalNoiseGranularity;
double d11 = MathHelper.lerp(xNoiseScale, d6, d7);
double d12 = MathHelper.lerp(xNoiseScale, d8, d9);
for (int zGranularityOffset = 0; zGranularityOffset < horizontalNoiseGranularity; ++zGranularityOffset) {
int worldZ = chunkZStart + zNoiseOffset * horizontalNoiseGranularity
+ zGranularityOffset;
double zNoiseScale = (double) zGranularityOffset / (double) horizontalNoiseGranularity;
double finalNoise = MathHelper.lerp(zNoiseScale, d11, d12);
double finalNoiseClamped = MathHelper.clamp(finalNoise / 200.0D, -1.0D, 1.0D);
finalNoises[Math.abs(worldX) % 16][worldY][Math.abs(worldZ) % 16] = finalNoiseClamped;
}
}
}
}
}
double[][] temp = noises[0];
noises[0] = noises[1];
noises[1] = temp;
}
return finalNoises;
}
public double getSurfaceDepthNoise(BlockPos pos) {
double scale = 0.0625D;
return this.surfaceDepthNoise2.noiseAt(pos.getX() * scale, pos.getZ() * scale, scale, pos.getY() * scale)
* 15.0D;
}
@Override
public int getGroundHeight() {
return this.getSeaLevel() + 1;
}
@Override
public int getSeaLevel() {
return this.genSettings.sphereMidY;
}
public int correctYValue(int yIn) {
// The overworld noise generator uses loads of magic numbers, which assume the
// sea level is 63, so if we want to raise the sea level, then we need to use
// the noise values from a different height in order to raise the ground level
// up from the sea
int seaLevelDiff = this.getSeaLevel() - 63;
int newY = yIn - seaLevelDiff;
if (newY > 255) {
return 255;
}
if (newY < 0) {
return 0;
}
return newY;
}
@Override
// carve
public void func_225550_a_(BiomeManager biomeManager, IChunk chunkIn, GenerationStage.Carving genStage) {
// I can't influence where caves are going to be on a block by block basis, so
// just ignore block changes that fall outside of the spheres
Sphere sphere = Sphere.getClosest(this.world, chunkIn.getPos().asBlockPos());
IChunk newChunk = new IChunkWrapper(chunkIn, (pos) -> sphere.getDistanceToCenter(pos) > sphere.radius);
super.func_225550_a_(biomeManager, newChunk, genStage);
}
} | 16,215 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
ModEventSubscriber.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/ModEventSubscriber.java | package uk.co.harryyoud.biospheres;
import net.minecraft.block.Block;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.registries.IForgeRegistryEntry;
@EventBusSubscriber(modid = Biospheres.MODID, bus = EventBusSubscriber.Bus.MOD)
public final class ModEventSubscriber {
@SubscribeEvent
public static void onRegisterBlocks(RegistryEvent.Register<Block> event) {
}
public static <T extends IForgeRegistryEntry<T>> T setup(final T entry, final String name) {
return setup(entry, new ResourceLocation(Biospheres.MODID, name));
}
public static <T extends IForgeRegistryEntry<T>> T setup(final T entry, final ResourceLocation registryName) {
entry.setRegistryName(registryName);
return entry;
}
} | 893 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
BiosphereGenSettingsSerializer.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/config/BiosphereGenSettingsSerializer.java | package uk.co.harryyoud.biospheres.config;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
import com.google.common.collect.ImmutableMap;
import com.mojang.datafixers.Dynamic;
import com.mojang.datafixers.types.DynamicOps;
import net.minecraft.block.BlockState;
import net.minecraft.world.gen.OverworldGenSettings;
import uk.co.harryyoud.biospheres.config.serializers.BlockStateSerializer;
import uk.co.harryyoud.biospheres.config.serializers.ISerializer;
import uk.co.harryyoud.biospheres.config.serializers.IntegerSerializer;
public class BiosphereGenSettingsSerializer {
//@formatter:off
private static Map<String, ISerializer<?>> OPTIONS = ImmutableMap.<String, ISerializer<?>>builder()
.put("domeBlock", new BlockStateSerializer())
.put("bridgeBlock", new BlockStateSerializer())
.put("outsideFillerBlock", new BlockStateSerializer())
.put("sphereMidY", (new IntegerSerializer()).addInRange(0, 255))
.put("sphereMinRadius", (new IntegerSerializer()).addInRange(15, 100))
.put("sphereMaxRadius", (new IntegerSerializer()).addInRange(15, 100))
.build();
//@formatter:on
private Map<String, String> values = new HashMap<>();
public BiosphereGenSettingsSerializer() {
values.put("domeBlock", BiosphereConfig.DEFAULT_PER_WORLD.domeBlock.get());
values.put("bridgeBlock", BiosphereConfig.DEFAULT_PER_WORLD.bridgeBlock.get());
values.put("outsideFillerBlock", BiosphereConfig.DEFAULT_PER_WORLD.outsideFillerBlock.get());
values.put("sphereMidY", BiosphereConfig.DEFAULT_PER_WORLD.sphereMidY.get().toString());
values.put("sphereMinRadius", BiosphereConfig.DEFAULT_PER_WORLD.sphereMinRadius.get().toString());
values.put("sphereMaxRadius", BiosphereConfig.DEFAULT_PER_WORLD.sphereMaxRadius.get().toString());
}
public static BiosphereGenSettingsSerializer fromNBT(Dynamic<?> in) {
BiosphereGenSettingsSerializer settings = new BiosphereGenSettingsSerializer();
for (Map.Entry<String, ISerializer<?>> entry : OPTIONS.entrySet()) {
String val;
String key = entry.getKey();
ISerializer<?> serializer = entry.getValue();
if (serializer instanceof IntegerSerializer) {
val = String.valueOf(in.get(key).asInt(-1));
} else {
val = in.get(key).asString("");
}
if (serializer.validate(val)) {
settings.set(key, val);
}
}
return settings;
}
public <T> Dynamic<T> toNBT(DynamicOps<T> in) {
HashMap<T, T> map = new HashMap<>();
for (Map.Entry<String, ISerializer<?>> entry : OPTIONS.entrySet()) {
T val;
if (entry.getValue() instanceof IntegerSerializer) {
val = in.createInt(Integer.valueOf(this.get(entry.getKey())));
} else {
val = in.createString(this.get(entry.getKey()));
}
map.put(in.createString(entry.getKey()), val);
}
return new Dynamic<>(in, in.createMap(map));
}
public String get(String key) {
return this.values.get(key);
}
public Predicate<String> getValidator(String key) {
return OPTIONS.get(key)::validate;
}
public ISerializer<?> getSerializer(String key) {
return OPTIONS.get(key);
}
public Object getValue(String key) {
return this.getSerializer(key).deserialize(this.get(key));
}
public Map<String, ISerializer<?>> getSerializers() {
return OPTIONS;
}
public void set(String key, String value) {
if (!this.values.containsKey(key)) {
return;
}
this.values.put(key, value);
}
public static BiosphereGenSettings get(Dynamic<?> in) {
BiosphereGenSettingsSerializer serializer = BiosphereGenSettingsSerializer.fromNBT(in);
return serializer.new BiosphereGenSettings();
}
public class BiosphereGenSettings extends OverworldGenSettings {
public final BlockState domeBlock;
public final BlockState bridgeBlock;
public final BlockState outsideFillerBlock;
public final int sphereMidY;
public final int sphereMinRadius;
public final int sphereMaxRadius;
private BiosphereGenSettings() {
this.domeBlock = (BlockState) BiosphereGenSettingsSerializer.this.getValue("domeBlock");
this.bridgeBlock = (BlockState) BiosphereGenSettingsSerializer.this.getValue("bridgeBlock");
this.outsideFillerBlock = (BlockState) BiosphereGenSettingsSerializer.this.getValue("outsideFillerBlock");
this.sphereMidY = (Integer) BiosphereGenSettingsSerializer.this.getValue("sphereMidY");
this.sphereMinRadius = (Integer) BiosphereGenSettingsSerializer.this.getValue("sphereMinRadius");
this.sphereMaxRadius = (Integer) BiosphereGenSettingsSerializer.this.getValue("sphereMaxRadius");
}
}
}
| 4,509 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
BiosphereConfig.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/config/BiosphereConfig.java | package uk.co.harryyoud.biospheres.config;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.Biomes;
import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.common.ForgeConfigSpec.BooleanValue;
import net.minecraftforge.common.ForgeConfigSpec.ConfigValue;
import net.minecraftforge.common.ForgeConfigSpec.IntValue;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.loading.FMLPaths;
import net.minecraftforge.registries.ForgeRegistries;
import uk.co.harryyoud.biospheres.Biospheres;
import uk.co.harryyoud.biospheres.config.serializers.BlockStateSerializer;
@EventBusSubscriber(modid = Biospheres.MODID, bus = EventBusSubscriber.Bus.MOD)
public class BiosphereConfig {
public static final ForgeConfigSpec GENERAL_SPEC;
public static final GeneralConfig GENERAL;
public static final ForgeConfigSpec DEFAULT_PER_WORLD_SPEC;
public static final DefaultPerWorldConfig DEFAULT_PER_WORLD;
public static final ForgeConfigSpec CLIENT_SPEC;
public static final ClientConfig CLIENT;
static {
final Pair<GeneralConfig, ForgeConfigSpec> commonSpecPair = new ForgeConfigSpec.Builder()
.configure(GeneralConfig::new);
GENERAL = commonSpecPair.getLeft();
GENERAL_SPEC = commonSpecPair.getRight();
final Pair<ClientConfig, ForgeConfigSpec> clientSpecPair = new ForgeConfigSpec.Builder()
.configure(ClientConfig::new);
CLIENT = clientSpecPair.getLeft();
CLIENT_SPEC = clientSpecPair.getRight();
final Pair<DefaultPerWorldConfig, ForgeConfigSpec> worldGenSpecPair = new ForgeConfigSpec.Builder()
.configure(DefaultPerWorldConfig::new);
DEFAULT_PER_WORLD = worldGenSpecPair.getLeft();
DEFAULT_PER_WORLD_SPEC = worldGenSpecPair.getRight();
}
public static boolean shouldInjectWorldType;
public static float cloudHeight;
public static List<String> bannedBiomes;
public static List<Biome.Category> bannedBiomeCategories;
public static List<BlockState> bannedBlocks;
public static void setup() {
Path configPath = FMLPaths.CONFIGDIR.get();
Path ourConfigPath = Paths.get(configPath.toAbsolutePath().toString(), "biospheres");
try {
Files.createDirectory(ourConfigPath);
} catch (FileAlreadyExistsException e) {
// Do nothing
} catch (IOException e) {
System.out.println("Failed to create biospheres config directory");
}
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON,
BiosphereConfig.GENERAL_SPEC,
"biospheres/common.toml");
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, BiosphereConfig.DEFAULT_PER_WORLD_SPEC,
"biospheres/world-generation-defaults.toml");
ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, BiosphereConfig.CLIENT_SPEC,
"biospheres/client.toml");
}
@SubscribeEvent
public static void onModConfigEvent(final ModConfig.ModConfigEvent configEvent) {
if (configEvent.getConfig().getSpec() == BiosphereConfig.GENERAL_SPEC) {
bakeGeneralConfig();
}
if (configEvent.getConfig().getSpec() == BiosphereConfig.CLIENT_SPEC) {
bakeClientConfig();
}
}
@SuppressWarnings("unchecked")
public static void bakeGeneralConfig() {
shouldInjectWorldType = GENERAL.shouldInjectWorldType.get();
bannedBiomes = (List<String>) GENERAL.bannedBiomes.get();
bannedBiomeCategories = GENERAL.bannedBiomeCategories
.get()
.stream()
.map((cat) -> Biome.Category.valueOf(cat)).collect(Collectors.toList());
// We lazy calculate bannedBlocks later, once modded blocks have loaded
}
public static void bakeClientConfig() {
cloudHeight = CLIENT.cloudHeight.get();
}
public static class DefaultPerWorldConfig {
public final IntValue sphereMidY;
public final IntValue sphereMinRadius;
public final IntValue sphereMaxRadius;
public final ConfigValue<String> domeBlock;
public final ConfigValue<String> outsideFillerBlock;
public final ConfigValue<String> bridgeBlock;
public final ConfigValue<List<? extends String>> bannedBlocks;
public DefaultPerWorldConfig(ForgeConfigSpec.Builder builder) {
//@formatter:off
builder.push("spheres");
this.sphereMidY = builder
.comment("Sea level (aka vertical midpoint of spheres)\n"
+ "This should be between sphereMaxRadius and (256 - sphereMaxRadius)")
.defineInRange("sphereMidY", 63, 0, 255);
this.sphereMinRadius = builder
.comment("Minimum sphere radius")
.defineInRange("sphereMinRadius", 63, 15, 100);
this.sphereMaxRadius = builder
.comment("Maximum sphere radius")
.defineInRange("sphereMaxRadius", 100, 15, 100);
builder.pop();
builder.push("blocks");
this.domeBlock = builder
.comment("Block to use for the dome")
.define("domeBlock",
(new BlockStateSerializer()).serialize(Blocks.WHITE_STAINED_GLASS.getDefaultState()),
(new BlockStateSerializer())::validate);
this.outsideFillerBlock = builder
.comment("Block to use for outside the spheres")
.define("outsideFillerBlock",
(new BlockStateSerializer()).serialize(Blocks.AIR.getDefaultState()),
(new BlockStateSerializer())::validate);
this.bridgeBlock = builder
.comment("Block to use for the bridges between spheres")
.define("bridgeBlock",
(new BlockStateSerializer()).serialize(Blocks.OAK_PLANKS.getDefaultState()),
(new BlockStateSerializer())::validate);
this.bannedBlocks = builder
.comment("Blocks to always replace with dome blocks if at the radius")
.defineList("bannedBlocks", Arrays.asList(
(new BlockStateSerializer()).serialize(Blocks.AIR.getDefaultState()),
(new BlockStateSerializer()).serialize(Blocks.WATER.getDefaultState()),
(new BlockStateSerializer()).serialize(Blocks.LAVA.getDefaultState())
),
(new BlockStateSerializer())::validate);
//@formatter:on
builder.pop();
}
}
public static class GeneralConfig {
public final BooleanValue shouldInjectWorldType;
public final ConfigValue<List<? extends String>> bannedBiomes;
public final ConfigValue<List<? extends String>> bannedBiomeCategories;
public GeneralConfig(ForgeConfigSpec.Builder builder) {
//@formatter:off
this.shouldInjectWorldType = builder
.comment("Inject level-type on dedicated server startup. Won't do anything on a client.")
.translation(Biospheres.MODID + ".config." + "shouldInjectWorldType")
.define("shouldInjectWorldType", true);
builder.push("biomes");
this.bannedBiomes = builder
.comment("Don't use these biomes")
.defineList("bannedBiomes", Arrays.asList(Biomes.THE_VOID.getRegistryName().toString()),
(s) -> ForgeRegistries.BIOMES.containsKey(new ResourceLocation((String) s)));
this.bannedBiomeCategories = builder
.comment("Don't use these biome categories")
.defineList("bannedBiomeCategories", Arrays.asList(
Biome.Category.THEEND.toString(),
Biome.Category.NETHER.toString()
),
this::validateBiomeCategory);
builder.pop();
//@formatter:on
}
private boolean validateBiomeCategory(Object obj) {
try {
String s = (String) obj;
Biome.Category.valueOf(s);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
}
public static class ClientConfig {
public final IntValue cloudHeight;
public ClientConfig(ForgeConfigSpec.Builder builder) {
this.cloudHeight = builder.comment("Cloud height\n"
+ "Useful for when spheres are high up and/or big")
.translation(Biospheres.MODID + ".config." + "cloudHeight")
.defineInRange("cloudHeight", 255, 0, 256);
}
}
}
| 8,136 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
BlockStateSerializer.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/config/serializers/BlockStateSerializer.java | package uk.co.harryyoud.biospheres.config.serializers;
import java.util.ArrayList;
import java.util.Map;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.block.BlockState;
import net.minecraft.command.arguments.BlockStateArgument;
import net.minecraft.state.IProperty;
import net.minecraft.util.Util;
public class BlockStateSerializer implements ISerializer<BlockState> {
@Override
public String serialize(BlockState state) {
String stateString = state.getBlock().getRegistryName().toString();
final ArrayList<String> properties = new ArrayList<>();
for (Map.Entry<IProperty<?>, Comparable<?>> entry : state.getValues().entrySet()) {
final IProperty<?> property = entry.getKey();
final Comparable<?> value = entry.getValue();
properties.add(property.getName() + "=" + Util.getValueName(property, value));
}
if (!properties.isEmpty()) {
stateString += "[";
stateString += String.join(",", properties);
stateString += "]";
}
return stateString;
}
@Override
public BlockState deserialize(String s) {
try {
return new BlockStateArgument().parse(new StringReader(s)).getState();
} catch (CommandSyntaxException e) {
throw new IllegalArgumentException("Couldn't parse blockstate");
}
}
@Override
public boolean validate(String s) {
if (s == null || s.isEmpty()) {
return false;
}
try {
new BlockStateArgument().parse(new StringReader(s));
return true;
} catch (CommandSyntaxException e) {
return false;
}
}
@Override
public Object[] getInvalidString() {
return new Object[] { "biospheres.gui.block.invalid" };
}
} | 1,671 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
ISerializer.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/config/serializers/ISerializer.java | package uk.co.harryyoud.biospheres.config.serializers;
public interface ISerializer<T> {
public String serialize(T in);
public T deserialize(String in);
public boolean validate(String in);
public default boolean validate(Object in) {
if (!(in instanceof String)) {
return false;
}
return this.validate((String) in);
}
// When typing, this does "validate(newText)", so to allow putting in empty
// strings when typing in integers is useful, and to allow typing a string that
// would start off invalid, and end up valid
public default boolean validateField(String in) {
return true;
}
public default Object[] getInvalidString() {
return new Object[] { "biospheres.gui.default.label" };
}
}
| 720 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
IntegerSerializer.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/config/serializers/IntegerSerializer.java | package uk.co.harryyoud.biospheres.config.serializers;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class IntegerSerializer implements ISerializer<Integer> {
private boolean inRangeTest = false;
private boolean allowEmpty = false;
private int min;
private int max;
List<Predicate<Integer>> extraValidators = new ArrayList<>();
@Override
public String serialize(Integer i) {
return i.toString();
}
@Override
public Integer deserialize(String s) {
return Integer.parseInt(s);
}
@Override
public boolean validate(String s) {
if (s.isEmpty() && this.allowEmpty) {
return true;
}
Integer i;
try {
i = Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
}
for (Predicate<Integer> t : this.extraValidators) {
if (!t.test(i)) {
return false;
}
}
return true;
}
public IntegerSerializer allowEmpty() {
this.allowEmpty = true;
return this;
}
public IntegerSerializer addInRange(int min, int max) {
this.inRangeTest = true;
this.min = min;
this.max = max;
this.extraValidators.add((i) -> {
return i >= min && i <= max;
});
return this;
}
@Override
public boolean validateField(String s) {
if (s.isEmpty()) {
return true;
}
try {
Integer.parseInt(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}
@Override
public Object[] getInvalidString() {
if (inRangeTest) {
return new Object[] { "biospheres.gui.intRange.invalid", this.min, this.max };
}
return new Object[] { "biospheres.gui.int.invalid" };
}
}
| 1,604 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
ScrollingOptionsList.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/gui/ScrollingOptionsList.java | package uk.co.harryyoud.biospheres.gui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.INestedGuiEventHandler;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.client.gui.widget.list.AbstractList;
class ScrollingOptionsList extends AbstractList<OptionBlock> implements INestedGuiEventHandler {
private CreateBiospheresWorldScreen parent;
public ScrollingOptionsList(CreateBiospheresWorldScreen parent, Minecraft mc, int parentWidth, int parentHeight) {
super(mc, parentWidth, parentHeight, 43, parentHeight - 40, 60);
this.parent = parent;
}
public CreateBiospheresWorldScreen getParent() {
return this.parent;
}
public OptionBlock create() {
OptionBlock block = new OptionBlock(this);
int y = (this.getItemCount() + 1) * this.itemHeight;
TextFieldWidget field = new TextFieldWidget(parent.getFont(), this.width / 2 - 100, y, 200, 20, "");
block.setField(field);
this.addEntry(block);
return block;
}
@Override
public void render(int p_render_1_, int p_render_2_, float p_render_3_) {
super.render(p_render_1_, p_render_2_, p_render_3_);
}
public void tick() {
for (OptionBlock opt : this.children()) {
opt.tick();
}
}
@Override
public boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_) {
if (!this.isMouseOver(p_mouseClicked_1_, p_mouseClicked_3_)
|| this.getEntryAtPosition(p_mouseClicked_1_, p_mouseClicked_3_) == null) {
this.setFocused(null);
}
return super.mouseClicked(p_mouseClicked_1_, p_mouseClicked_3_, p_mouseClicked_5_);
}
}
| 1,598 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
CreateBiospheresWorldScreen.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/gui/CreateBiospheresWorldScreen.java | package uk.co.harryyoud.biospheres.gui;
import java.util.Map;
import com.mojang.datafixers.Dynamic;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.screen.CreateWorldScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.resources.I18n;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.NBTDynamicOps;
import net.minecraft.util.text.TranslationTextComponent;
import uk.co.harryyoud.biospheres.config.BiosphereGenSettingsSerializer;
import uk.co.harryyoud.biospheres.config.serializers.ISerializer;
public class CreateBiospheresWorldScreen extends Screen {
private BiosphereGenSettingsSerializer generatorInfo = new BiosphereGenSettingsSerializer();
private final CreateWorldScreen createWorldGui;
private ScrollingOptionsList optionsList;
public CreateBiospheresWorldScreen(CreateWorldScreen parent, CompoundNBT generatorOptions) {
super(new TranslationTextComponent("biospheres.gui.title"));
this.createWorldGui = parent;
this.loadGeneratorOptions(generatorOptions);
}
public CompoundNBT getGeneratorOptions() {
return (CompoundNBT) this.generatorInfo.toNBT(NBTDynamicOps.INSTANCE).getValue();
}
public void loadGeneratorOptions(CompoundNBT nbt) {
this.generatorInfo = BiosphereGenSettingsSerializer.fromNBT(new Dynamic<>(NBTDynamicOps.INSTANCE, nbt));
}
@Override
protected void init() {
this.optionsList = new ScrollingOptionsList(this, this.minecraft, this.width, this.height);
this.children.add(this.optionsList);
this.initOptions();
this.addButton(
new Button(this.width / 2 - 155, this.height - 28, 150, 20, I18n.format("gui.done"), (p_213010_1_) -> {
this.createWorldGui.chunkProviderSettingsJson = this.getGeneratorOptions();
this.minecraft.displayGuiScreen(this.createWorldGui);
}));
this.addButton(
new Button(this.width / 2 + 5, this.height - 28, 150, 20, I18n.format("gui.cancel"), (p_213009_1_) -> {
this.minecraft.displayGuiScreen(this.createWorldGui);
}));
}
protected void initOptions() {
for (Map.Entry<String, ISerializer<?>> entry : this.generatorInfo.getSerializers().entrySet()) {
String key = entry.getKey();
String label = "biospheres.gui." + key + ".label";
//@formatter:off
this.optionsList.create()
.setTitle(label)
.setMessage(label)
.setText(this.generatorInfo.get(key))
.setInvalidString(this.generatorInfo.getSerializer(key).getInvalidString())
.setResponder((s) -> this.generatorInfo.set(key, s))
.setValidator(this.generatorInfo.getValidator(key))
.setFieldValidator(this.generatorInfo.getSerializer(key)::validateField);
//@formatter:on
}
}
@Override
public void onClose() {
this.minecraft.displayGuiScreen(this.createWorldGui);
}
@Override
public void render(int p_render_1_, int p_render_2_, float p_render_3_) {
this.renderBackground();
this.optionsList.render(p_render_1_, p_render_2_, p_render_3_);
this.drawCenteredString(this.font, this.title.getFormattedText(), this.width / 2, 20, 16777215);
super.render(p_render_1_, p_render_2_, p_render_3_);
}
FontRenderer getFont() {
return this.font;
}
@Override
public void tick() {
this.optionsList.tick();
}
}
| 3,278 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
OptionBlock.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/gui/OptionBlock.java | package uk.co.harryyoud.biospheres.gui;
import java.util.function.Consumer;
import java.util.function.Predicate;
import com.google.common.base.Predicates;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.client.gui.widget.list.AbstractList;
import net.minecraft.client.resources.I18n;
public class OptionBlock extends AbstractList.AbstractListEntry<OptionBlock> {
private ScrollingOptionsList parent;
private String title = "Config Option";
private String validString = "";
private String invalidString = "Invalid";
private TextFieldWidget field;
private boolean valid = true;
private Predicate<String> validator = Predicates.alwaysTrue();
private static final int RED = 16711680;
private static final String CROSS_MARK = "\u274C";
public OptionBlock(ScrollingOptionsList parent) {
this.parent = parent;
}
public OptionBlock setField(TextFieldWidget field) {
this.field = field;
return this;
}
public OptionBlock setTitle(String title, Object... parameters) {
this.title = I18n.format(title, parameters);
return this;
}
public OptionBlock setInvalidString(String comment, Object... parameters) {
this.invalidString = I18n.format(comment, parameters);
return this;
}
public OptionBlock setInvalidString(Object[] args) {
if (args.length < 1) {
this.invalidString = "";
return this;
}
String comment = (String) args[0];
args[0] = CROSS_MARK;
this.invalidString = I18n.format(comment, args);
return this;
}
public OptionBlock setResponder(Consumer<String> f) {
Consumer<String> f2 = (s) -> {
this.valid = this.validator.test(s);
f.accept(s);
};
this.field.setResponder(f2);
return this;
}
public OptionBlock setText(String text) {
if (this.field == null) {
return this;
}
this.field.setText(text);
return this;
}
public OptionBlock setMessage(String message) {
if (this.field == null) {
return this;
}
this.field.setMessage(message);
return this;
}
public OptionBlock setValidator(Predicate<String> f) {
this.validator = f;
return this;
}
public OptionBlock setFieldValidator(Predicate<String> f) {
this.field.setValidator(f);
return this;
}
@Override
public void render(int p_render_1_, int p_render_2_, int p_render_3_, int p_render_4_, int p_render_5_,
int p_render_6_, int p_render_7_, boolean p_render_8_, float p_render_9_) {
this.parent.getParent().drawString(this.parent.getParent().getFont(), this.title,
this.parent.getParent().width / 2 - 100, p_render_2_ + 5, -6250336);
this.parent.getParent().drawString(this.parent.getParent().getFont(),
this.valid ? this.validString : this.invalidString, this.parent.getParent().width / 2 - 100,
p_render_2_ + 25 + 13 + 5, RED);
if (this.field == null) {
return;
}
this.field.y = p_render_2_ + 13 + 5;
this.field.setFocused2(this.parent.getFocused() == this);
this.field.render(p_render_2_, p_render_3_, p_render_9_);
}
public void tick() {
if (this.field == null) {
return;
}
// Make sure we blink the cursor
this.field.tick();
}
// Delegate methods:
// Pass IGuiEventListener methods to TextFieldWidget
@Override
public boolean changeFocus(boolean p_changeFocus_1_) {
if (this.field == null) {
return false;
}
return this.field.changeFocus(p_changeFocus_1_);
}
@Override
public void mouseMoved(double xPos, double p_212927_3_) {
if (this.field == null) {
return;
}
this.field.mouseMoved(xPos, p_212927_3_);
}
@Override
public boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_) {
if (this.field == null) {
return false;
}
return this.field.mouseClicked(p_mouseClicked_1_, p_mouseClicked_3_, p_mouseClicked_5_);
}
@Override
public boolean mouseReleased(double p_mouseReleased_1_, double p_mouseReleased_3_, int p_mouseReleased_5_) {
if (this.field == null) {
return false;
}
return this.field.mouseReleased(p_mouseReleased_1_, p_mouseReleased_3_, p_mouseReleased_5_);
}
@Override
public boolean mouseDragged(double p_mouseDragged_1_, double p_mouseDragged_3_, int p_mouseDragged_5_,
double p_mouseDragged_6_, double p_mouseDragged_8_) {
if (this.field == null) {
return false;
}
return this.field.mouseDragged(p_mouseDragged_1_, p_mouseDragged_3_, p_mouseDragged_5_, p_mouseDragged_6_,
p_mouseDragged_8_);
}
@Override
public boolean mouseScrolled(double p_mouseScrolled_1_, double p_mouseScrolled_3_, double p_mouseScrolled_5_) {
if (this.field == null) {
return false;
}
return this.field.mouseScrolled(p_mouseScrolled_1_, p_mouseScrolled_3_, p_mouseScrolled_5_);
}
@Override
public boolean keyPressed(int p_keyPressed_1_, int p_keyPressed_2_, int p_keyPressed_3_) {
if (this.field == null) {
return false;
}
return this.field.keyPressed(p_keyPressed_1_, p_keyPressed_2_, p_keyPressed_3_);
}
@Override
public boolean keyReleased(int keyCode, int scanCode, int modifiers) {
if (this.field == null) {
return false;
}
return this.field.keyReleased(keyCode, scanCode, modifiers);
}
@Override
public boolean charTyped(char p_charTyped_1_, int p_charTyped_2_) {
if (this.field == null) {
return false;
}
return this.field.charTyped(p_charTyped_1_, p_charTyped_2_);
}
} | 5,279 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
IChunkWrapper.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/wrappers/IChunkWrapper.java | package uk.co.harryyoud.biospheres.wrappers;
import java.util.BitSet;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Stream;
import it.unimi.dsi.fastutil.longs.LongSet;
import it.unimi.dsi.fastutil.shorts.ShortList;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.entity.Entity;
import net.minecraft.fluid.Fluid;
import net.minecraft.fluid.IFluidState;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.math.RayTraceContext;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.util.palette.UpgradeData;
import net.minecraft.world.ITickList;
import net.minecraft.world.IWorld;
import net.minecraft.world.biome.BiomeContainer;
import net.minecraft.world.chunk.ChunkSection;
import net.minecraft.world.chunk.ChunkStatus;
import net.minecraft.world.chunk.IChunk;
import net.minecraft.world.gen.GenerationStage.Carving;
import net.minecraft.world.gen.Heightmap;
import net.minecraft.world.gen.Heightmap.Type;
import net.minecraft.world.gen.feature.structure.StructureStart;
public class IChunkWrapper implements IChunk {
private IChunk chunk;
private Predicate<BlockPos> filter;
public IChunkWrapper(IChunk chunkIn, Predicate<BlockPos> filter) {
this.chunk = chunkIn;
this.filter = filter;
}
@Override
public BlockState setBlockState(BlockPos pos, BlockState state, boolean isMoving) {
if (this.filter.test(pos)) {
return Blocks.VOID_AIR.getDefaultState();
}
return chunk.setBlockState(pos, state, isMoving);
}
public IChunk getInnerIChunk() {
return this.chunk;
}
@Override
public boolean equals(Object objIn) {
if (objIn instanceof IChunkWrapper) {
return this.chunk == ((IChunkWrapper) objIn).getInnerIChunk();
}
return false;
}
@Override
public int hashCode() {
return this.chunk.hashCode();
}
// AUTO GENERATED ECLIPSE DELEGATED METHODS
@Override
public void addEntity(Entity entityIn) {
chunk.addEntity(entityIn);
}
@Override
public void addStructureReference(String arg0, long arg1) {
chunk.addStructureReference(arg0, arg1);
}
@Override
public BlockState getBlockState(BlockPos pos) {
return chunk.getBlockState(pos);
}
@Override
public IFluidState getFluidState(BlockPos pos) {
return chunk.getFluidState(pos);
}
@Override
public int getLightValue(BlockPos pos) {
return chunk.getLightValue(pos);
}
@Override
public int getMaxLightLevel() {
return chunk.getMaxLightLevel();
}
@Override
public int getHeight() {
return chunk.getHeight();
}
@Override
public void addTileEntity(BlockPos pos, TileEntity tileEntityIn) {
chunk.addTileEntity(pos, tileEntityIn);
}
@Override
public ChunkSection getLastExtendedBlockStorage() {
return chunk.getLastExtendedBlockStorage();
}
@Override
public ChunkSection[] getSections() {
return chunk.getSections();
}
@Override
public Collection<Entry<Type, Heightmap>> getHeightmaps() {
return chunk.getHeightmaps();
}
@Override
public Heightmap getHeightmap(Type typeIn) {
return chunk.getHeightmap(typeIn);
}
@Override
public ChunkPos getPos() {
return chunk.getPos();
}
@Override
public BiomeContainer getBiomes() {
return chunk.getBiomes();
}
@Override
public ChunkStatus getStatus() {
return chunk.getStatus();
}
@Override
public ShortList[] getPackedPositions() {
return chunk.getPackedPositions();
}
@Override
public void func_201636_b(short packedPosition, int index) {
chunk.func_201636_b(packedPosition, index);
}
@Override
public void addTileEntity(CompoundNBT nbt) {
chunk.addTileEntity(nbt);
}
@Override
public CompoundNBT getDeferredTileEntity(BlockPos pos) {
return chunk.getDeferredTileEntity(pos);
}
@Override
public Stream<BlockPos> getLightSources() {
return chunk.getLightSources();
}
@Override
public ITickList<Block> getBlocksToBeTicked() {
return chunk.getBlocksToBeTicked();
}
@Override
public ITickList<Fluid> getFluidsToBeTicked() {
return chunk.getFluidsToBeTicked();
}
@Override
public BitSet getCarvingMask(Carving type) {
return chunk.getCarvingMask(type);
}
@Override
public long getInhabitedTime() {
return chunk.getInhabitedTime();
}
@Override
public Map<String, LongSet> getStructureReferences() {
return chunk.getStructureReferences();
}
@Override
public LongSet getStructureReferences(String arg0) {
return chunk.getStructureReferences(arg0);
}
@Override
public StructureStart getStructureStart(String arg0) {
return chunk.getStructureStart(arg0);
}
@Override
public TileEntity getTileEntity(BlockPos pos) {
return chunk.getTileEntity(pos);
}
@Override
public BlockRayTraceResult rayTraceBlocks(RayTraceContext context) {
return chunk.rayTraceBlocks(context);
}
@Override
public int getTopFilledSegment() {
return chunk.getTopFilledSegment();
}
@Override
public Set<BlockPos> getTileEntitiesPos() {
return chunk.getTileEntitiesPos();
}
@Override
public void setHeightmap(Type type, long[] data) {
chunk.setHeightmap(type, data);
}
@Override
public int getTopBlockY(Type heightmapType, int x, int z) {
return chunk.getTopBlockY(heightmapType, x, z);
}
@Override
public BlockRayTraceResult rayTraceBlocks(Vec3d p_217296_1_, Vec3d p_217296_2_, BlockPos p_217296_3_,
VoxelShape p_217296_4_, BlockState p_217296_5_) {
return chunk.rayTraceBlocks(p_217296_1_, p_217296_2_, p_217296_3_, p_217296_4_, p_217296_5_);
}
@Override
public void setLastSaveTime(long saveTime) {
chunk.setLastSaveTime(saveTime);
}
@Override
public Map<String, StructureStart> getStructureStarts() {
return chunk.getStructureStarts();
}
@Override
public void setStructureStarts(Map<String, StructureStart> structureStartsIn) {
chunk.setStructureStarts(structureStartsIn);
}
@Override
public boolean isEmptyBetween(int startY, int endY) {
return chunk.isEmptyBetween(startY, endY);
}
@Override
public void setModified(boolean modified) {
chunk.setModified(modified);
}
@Override
public boolean isModified() {
return chunk.isModified();
}
@Override
public void removeTileEntity(BlockPos pos) {
chunk.removeTileEntity(pos);
}
@Override
public void markBlockForPostprocessing(BlockPos pos) {
chunk.markBlockForPostprocessing(pos);
}
@Override
public CompoundNBT getTileEntityNBT(BlockPos pos) {
return chunk.getTileEntityNBT(pos);
}
@Override
public UpgradeData getUpgradeData() {
return chunk.getUpgradeData();
}
@Override
public void setInhabitedTime(long newInhabitedTime) {
chunk.setInhabitedTime(newInhabitedTime);
}
@Override
public boolean hasLight() {
return chunk.hasLight();
}
@Override
public void setLight(boolean lightCorrectIn) {
chunk.setLight(lightCorrectIn);
}
@Override
public IWorld getWorldForge() {
return chunk.getWorldForge();
}
@Override
public void putStructureStart(String arg0, StructureStart arg1) {
chunk.putStructureStart(arg0, arg1);
}
@Override
public void setStructureReferences(Map<String, LongSet> arg0) {
chunk.setStructureReferences(arg0);
}
} | 7,411 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
IWorldWrapper.java | /FileExtraction/Java_unseen/harryyoud_biospheres/src/main/java/uk/co/harryyoud/biospheres/wrappers/IWorldWrapper.java | package uk.co.harryyoud.biospheres.wrappers;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.stream.Stream;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityPredicate;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.fluid.Fluid;
import net.minecraft.fluid.IFluidState;
import net.minecraft.particles.IParticleData;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.RayTraceContext;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.Difficulty;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.ITickList;
import net.minecraft.world.IWorld;
import net.minecraft.world.LightType;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.BiomeManager;
import net.minecraft.world.border.WorldBorder;
import net.minecraft.world.chunk.AbstractChunkProvider;
import net.minecraft.world.chunk.ChunkStatus;
import net.minecraft.world.chunk.IChunk;
import net.minecraft.world.dimension.Dimension;
import net.minecraft.world.gen.Heightmap.Type;
import net.minecraft.world.level.ColorResolver;
import net.minecraft.world.lighting.WorldLightManager;
import net.minecraft.world.storage.WorldInfo;
@SuppressWarnings("deprecation")
public class IWorldWrapper implements IWorld {
public final IWorld world;
public final int seaLevel;
private Predicate<BlockPos> blockStatePredicate;
public IWorldWrapper(IWorld world, int seaLevel) {
this.world = world;
this.seaLevel = seaLevel;
}
@Override
public int getSeaLevel() {
return this.seaLevel;
}
public void setBlockStatePredicate(Predicate<BlockPos> f) {
this.blockStatePredicate = f;
}
@Override
public boolean setBlockState(BlockPos pos, BlockState newState, int flags) {
if (!this.blockStatePredicate.test(pos)) {
return false;
}
return world.setBlockState(pos, newState, flags);
}
// ECLIPSE AUTO-GENERATE DELEGATE METHODS
@Override
public boolean hasBlockState(BlockPos p_217375_1_, Predicate<BlockState> p_217375_2_) {
return world.hasBlockState(p_217375_1_, p_217375_2_);
}
@Override
public WorldLightManager getLightManager() {
return world.getLightManager();
}
@Override
public int getMaxHeight() {
return world.getMaxHeight();
}
@Override
public int getLightFor(LightType lightTypeIn, BlockPos blockPosIn) {
return world.getLightFor(lightTypeIn, blockPosIn);
}
@Override
public TileEntity getTileEntity(BlockPos pos) {
return world.getTileEntity(pos);
}
@Override
public int getLightSubtracted(BlockPos blockPosIn, int amount) {
return world.getLightSubtracted(blockPosIn, amount);
}
@Override
public BlockState getBlockState(BlockPos pos) {
return world.getBlockState(pos);
}
@Override
public IFluidState getFluidState(BlockPos pos) {
return world.getFluidState(pos);
}
@Override
public List<Entity> getEntitiesInAABBexcluding(Entity entityIn, AxisAlignedBB boundingBox,
Predicate<? super Entity> predicate) {
return world.getEntitiesInAABBexcluding(entityIn, boundingBox, predicate);
}
@Override
public int getLightValue(BlockPos pos) {
return world.getLightValue(pos);
}
@Override
public boolean canSeeSky(BlockPos blockPosIn) {
return world.canSeeSky(blockPosIn);
}
@Override
public boolean removeBlock(BlockPos pos, boolean isMoving) {
return world.removeBlock(pos, isMoving);
}
@Override
public IChunk getChunk(int x, int z, ChunkStatus requiredStatus, boolean nonnull) {
return world.getChunk(x, z, requiredStatus, nonnull);
}
@Override
public boolean destroyBlock(BlockPos pos, boolean dropBlock) {
return world.destroyBlock(pos, dropBlock);
}
@Override
public int getMaxLightLevel() {
return world.getMaxLightLevel();
}
@Override
public int getHeight() {
return world.getHeight();
}
@Override
public WorldBorder getWorldBorder() {
return world.getWorldBorder();
}
@Override
public <T extends Entity> List<T> getEntitiesWithinAABB(Class<? extends T> clazz, AxisAlignedBB aabb,
Predicate<? super T> filter) {
return world.getEntitiesWithinAABB(clazz, aabb, filter);
}
@Override
public int getHeight(Type heightmapType, int x, int z) {
return world.getHeight(heightmapType, x, z);
}
@Override
public BlockRayTraceResult rayTraceBlocks(RayTraceContext context) {
return world.rayTraceBlocks(context);
}
@Override
public long getSeed() {
return world.getSeed();
}
@Override
public int getSkylightSubtracted() {
return world.getSkylightSubtracted();
}
@Override
public float getCurrentMoonPhaseFactor() {
return world.getCurrentMoonPhaseFactor();
}
@Override
public BiomeManager getBiomeManager() {
return world.getBiomeManager();
}
@Override
public boolean destroyBlock(BlockPos p_225521_1_, boolean p_225521_2_, Entity p_225521_3_) {
return world.destroyBlock(p_225521_1_, p_225521_2_, p_225521_3_);
}
@Override
public Biome getBiome(BlockPos p_226691_1_) {
return world.getBiome(p_226691_1_);
}
@Override
public <T extends Entity> List<T> getLoadedEntitiesWithinAABB(Class<? extends T> p_225316_1_,
AxisAlignedBB p_225316_2_, Predicate<? super T> p_225316_3_) {
return world.getLoadedEntitiesWithinAABB(p_225316_1_, p_225316_2_, p_225316_3_);
}
@Override
public boolean func_226663_a_(BlockState p_226663_1_, BlockPos p_226663_2_, ISelectionContext p_226663_3_) {
return world.func_226663_a_(p_226663_1_, p_226663_2_, p_226663_3_);
}
@Override
public boolean addEntity(Entity entityIn) {
return world.addEntity(entityIn);
}
@Override
public int getBlockColor(BlockPos blockPosIn, ColorResolver colorResolverIn) {
return world.getBlockColor(blockPosIn, colorResolverIn);
}
@Override
public float getCelestialAngle(float partialTicks) {
return world.getCelestialAngle(partialTicks);
}
@Override
public List<? extends PlayerEntity> getPlayers() {
return world.getPlayers();
}
@Override
public List<Entity> getEntitiesWithinAABBExcludingEntity(Entity entityIn, AxisAlignedBB bb) {
return world.getEntitiesWithinAABBExcludingEntity(entityIn, bb);
}
@Override
public Biome getNoiseBiome(int x, int y, int z) {
return world.getNoiseBiome(x, y, z);
}
@Override
public int getMoonPhase() {
return world.getMoonPhase();
}
@Override
public boolean checkNoEntityCollision(Entity p_226668_1_) {
return world.checkNoEntityCollision(p_226668_1_);
}
@Override
public ITickList<Block> getPendingBlockTicks() {
return world.getPendingBlockTicks();
}
@Override
public ITickList<Fluid> getPendingFluidTicks() {
return world.getPendingFluidTicks();
}
@Override
public boolean hasNoCollisions(AxisAlignedBB p_226664_1_) {
return world.hasNoCollisions(p_226664_1_);
}
@Override
public Biome getNoiseBiomeRaw(int x, int y, int z) {
return world.getNoiseBiomeRaw(x, y, z);
}
@Override
public World getWorld() {
return world.getWorld();
}
@Override
public boolean isRemote() {
return world.isRemote();
}
@Override
public WorldInfo getWorldInfo() {
return world.getWorldInfo();
}
@Override
public Dimension getDimension() {
return world.getDimension();
}
@Override
public DifficultyInstance getDifficultyForLocation(BlockPos pos) {
return world.getDifficultyForLocation(pos);
}
@Override
public boolean hasNoCollisions(Entity p_226669_1_) {
return world.hasNoCollisions(p_226669_1_);
}
@Override
public Difficulty getDifficulty() {
return world.getDifficulty();
}
@Override
public AbstractChunkProvider getChunkProvider() {
return world.getChunkProvider();
}
@Override
public boolean isAirBlock(BlockPos pos) {
return world.isAirBlock(pos);
}
@Override
public boolean hasNoCollisions(Entity p_226665_1_, AxisAlignedBB p_226665_2_) {
return world.hasNoCollisions(p_226665_1_, p_226665_2_);
}
@Override
public boolean chunkExists(int chunkX, int chunkZ) {
return world.chunkExists(chunkX, chunkZ);
}
@Override
public boolean hasNoCollisions(Entity p_226662_1_, AxisAlignedBB p_226662_2_, Set<Entity> p_226662_3_) {
return world.hasNoCollisions(p_226662_1_, p_226662_2_, p_226662_3_);
}
@Override
public Random getRandom() {
return world.getRandom();
}
@Override
public void notifyNeighbors(BlockPos pos, Block blockIn) {
world.notifyNeighbors(pos, blockIn);
}
@Override
public <T extends Entity> List<T> getEntitiesWithinAABB(Class<? extends T> p_217357_1_, AxisAlignedBB p_217357_2_) {
return world.getEntitiesWithinAABB(p_217357_1_, p_217357_2_);
}
@Override
public BlockPos getSpawnPoint() {
return world.getSpawnPoint();
}
@Override
public boolean canBlockSeeSky(BlockPos pos) {
return world.canBlockSeeSky(pos);
}
@Override
public void playSound(PlayerEntity player, BlockPos pos, SoundEvent soundIn, SoundCategory category, float volume,
float pitch) {
world.playSound(player, pos, soundIn, category, volume, pitch);
}
@Override
public BlockRayTraceResult rayTraceBlocks(Vec3d p_217296_1_, Vec3d p_217296_2_, BlockPos p_217296_3_,
VoxelShape p_217296_4_, BlockState p_217296_5_) {
return world.rayTraceBlocks(p_217296_1_, p_217296_2_, p_217296_3_, p_217296_4_, p_217296_5_);
}
@Override
public <T extends Entity> List<T> func_225317_b(Class<? extends T> p_225317_1_, AxisAlignedBB p_225317_2_) {
return world.func_225317_b(p_225317_1_, p_225317_2_);
}
@Override
public Stream<VoxelShape> getCollisionShapes(Entity p_226667_1_, AxisAlignedBB p_226667_2_,
Set<Entity> p_226667_3_) {
return world.getCollisionShapes(p_226667_1_, p_226667_2_, p_226667_3_);
}
@Override
public Stream<VoxelShape> getCollisionShapes(Entity p_226666_1_, AxisAlignedBB p_226666_2_) {
return world.getCollisionShapes(p_226666_1_, p_226666_2_);
}
@Override
public void addParticle(IParticleData particleData, double x, double y, double z, double xSpeed, double ySpeed,
double zSpeed) {
world.addParticle(particleData, x, y, z, xSpeed, ySpeed, zSpeed);
}
@Override
public void playEvent(PlayerEntity player, int type, BlockPos pos, int data) {
world.playEvent(player, type, pos, data);
}
@Override
public float getBrightness(BlockPos pos) {
return world.getBrightness(pos);
}
@Override
public void playEvent(int type, BlockPos pos, int data) {
world.playEvent(type, pos, data);
}
@Override
public int getStrongPower(BlockPos pos, Direction direction) {
return world.getStrongPower(pos, direction);
}
@Override
public Stream<VoxelShape> getEmptyCollisionShapes(Entity entityIn, AxisAlignedBB aabb,
Set<Entity> entitiesToIgnore) {
return world.getEmptyCollisionShapes(entityIn, aabb, entitiesToIgnore);
}
@Override
public IChunk getChunk(BlockPos pos) {
return world.getChunk(pos);
}
@Override
public boolean checkNoEntityCollision(Entity entityIn, VoxelShape shape) {
return world.checkNoEntityCollision(entityIn, shape);
}
@Override
public IChunk getChunk(int chunkX, int chunkZ) {
return world.getChunk(chunkX, chunkZ);
}
@Override
public PlayerEntity getClosestPlayer(double x, double y, double z, double distance, Predicate<Entity> predicate) {
return world.getClosestPlayer(x, y, z, distance, predicate);
}
@Override
public IChunk getChunk(int chunkX, int chunkZ, ChunkStatus requiredStatus) {
return world.getChunk(chunkX, chunkZ, requiredStatus);
}
@Override
public BlockPos getHeight(Type heightmapType, BlockPos pos) {
return world.getHeight(heightmapType, pos);
}
@Override
public IBlockReader getBlockReader(int chunkX, int chunkZ) {
return world.getBlockReader(chunkX, chunkZ);
}
@Override
public boolean hasWater(BlockPos pos) {
return world.hasWater(pos);
}
@Override
public boolean containsAnyLiquid(AxisAlignedBB bb) {
return world.containsAnyLiquid(bb);
}
@Override
public PlayerEntity getClosestPlayer(Entity entityIn, double distance) {
return world.getClosestPlayer(entityIn, distance);
}
@Override
public PlayerEntity getClosestPlayer(double x, double y, double z, double distance, boolean creativePlayers) {
return world.getClosestPlayer(x, y, z, distance, creativePlayers);
}
@Override
public PlayerEntity getClosestPlayer(double x, double y, double z) {
return world.getClosestPlayer(x, y, z);
}
@Override
public int getLight(BlockPos pos) {
return world.getLight(pos);
}
@Override
public int getNeighborAwareLightSubtracted(BlockPos pos, int amount) {
return world.getNeighborAwareLightSubtracted(pos, amount);
}
@Override
public boolean isPlayerWithin(double x, double y, double z, double distance) {
return world.isPlayerWithin(x, y, z, distance);
}
@Override
public boolean isBlockLoaded(BlockPos pos) {
return world.isBlockLoaded(pos);
}
@Override
public boolean isAreaLoaded(BlockPos center, int range) {
return world.isAreaLoaded(center, range);
}
@Override
public boolean isAreaLoaded(BlockPos from, BlockPos to) {
return world.isAreaLoaded(from, to);
}
@Override
public PlayerEntity getClosestPlayer(EntityPredicate predicate, LivingEntity target) {
return world.getClosestPlayer(predicate, target);
}
@Override
public boolean isAreaLoaded(int fromX, int fromY, int fromZ, int toX, int toY, int toZ) {
return world.isAreaLoaded(fromX, fromY, fromZ, toX, toY, toZ);
}
@Override
public PlayerEntity getClosestPlayer(EntityPredicate predicate, LivingEntity target, double p_217372_3_,
double p_217372_5_, double p_217372_7_) {
return world.getClosestPlayer(predicate, target, p_217372_3_, p_217372_5_, p_217372_7_);
}
@Override
public PlayerEntity getClosestPlayer(EntityPredicate predicate, double x, double y, double z) {
return world.getClosestPlayer(predicate, x, y, z);
}
@Override
public <T extends LivingEntity> T getClosestEntityWithinAABB(Class<? extends T> entityClazz,
EntityPredicate p_217360_2_, LivingEntity target, double x, double y, double z, AxisAlignedBB boundingBox) {
return world.getClosestEntityWithinAABB(entityClazz, p_217360_2_, target, x, y, z, boundingBox);
}
@Override
public <T extends LivingEntity> T func_225318_b(Class<? extends T> p_225318_1_, EntityPredicate p_225318_2_,
LivingEntity p_225318_3_, double p_225318_4_, double p_225318_6_, double p_225318_8_,
AxisAlignedBB p_225318_10_) {
return world.func_225318_b(p_225318_1_, p_225318_2_, p_225318_3_, p_225318_4_, p_225318_6_, p_225318_8_,
p_225318_10_);
}
@Override
public <T extends LivingEntity> T getClosestEntity(List<? extends T> entities, EntityPredicate predicate,
LivingEntity target, double x, double y, double z) {
return world.getClosestEntity(entities, predicate, target, x, y, z);
}
@Override
public List<PlayerEntity> getTargettablePlayersWithinAABB(EntityPredicate predicate, LivingEntity target,
AxisAlignedBB box) {
return world.getTargettablePlayersWithinAABB(predicate, target, box);
}
@Override
public <T extends LivingEntity> List<T> getTargettableEntitiesWithinAABB(Class<? extends T> p_217374_1_,
EntityPredicate p_217374_2_, LivingEntity p_217374_3_, AxisAlignedBB p_217374_4_) {
return world.getTargettableEntitiesWithinAABB(p_217374_1_, p_217374_2_, p_217374_3_, p_217374_4_);
}
@Override
public PlayerEntity getPlayerByUuid(UUID uniqueIdIn) {
return world.getPlayerByUuid(uniqueIdIn);
}
}
| 15,869 | Java | .java | harryyoud/biospheres | 9 | 3 | 2 | 2020-04-24T15:31:07Z | 2020-07-29T16:15:50Z |
WatchdogService.java | /FileExtraction/Java_unseen/Divested-Mobile_MotionLock/app/src/main/java/us/spotco/motionlock/WatchdogService.java | /*
Copyright (c) 2017 Divested Computing Group
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package us.spotco.motionlock;
import android.app.KeyguardManager;
import android.app.Service;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;
import com.github.nisrulz.sensey.FlipDetector;
import com.github.nisrulz.sensey.MovementDetector;
import com.github.nisrulz.sensey.Sensey;
public class WatchdogService extends Service {
private static final String logTag = "MotionLock";
private static long lastLockTime = SystemClock.elapsedRealtime();
private static final int lockThreshholdFaceDown = 1;
private static int lockCounterFaceDown = 0;
private static final int lockThreshholdNoMovement = 3;
private static int lockCounterNoMovement = 0;
private static BroadcastReceiver mScreenStateReceiver;
private static ComponentName mLockReceiver;
private static DevicePolicyManager mDPM;
private static KeyguardManager mKM;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "MotionLock: Service Started", Toast.LENGTH_SHORT).show();
mScreenStateReceiver = new ScreenStateReceiver();
IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, screenStateFilter);
mLockReceiver = new ComponentName(this, LockReceiver.class);
mDPM = (DevicePolicyManager)getSystemService(DEVICE_POLICY_SERVICE);
mKM = (KeyguardManager)getSystemService(KEYGUARD_SERVICE);
if(AdminHelper.getAdminHelper(this).isAdmin()) {
Sensey.getInstance().init(this, Sensey.SAMPLING_PERIOD_NORMAL);
setupLockGestures();
setWatching(true, "First start");
} else {
return START_NOT_STICKY;
}
return START_STICKY;
}
@Override
public void onDestroy() {
Toast.makeText(this, "MotionLock: Service Stopped", Toast.LENGTH_SHORT).show();
}
protected static void logAction(String action) {
Log.d(logTag, action);
}
private static void resetLockCouinters() {
lockCounterNoMovement = lockCounterFaceDown = 0;
}
private static void lock(String reason, int lockCounter, int lockThreshhold) {
if(!mKM.inKeyguardRestrictedInputMode()) {
logAction("Considering on locking! Counter: " + lockCounter + ", Threshold: " + lockThreshhold + ", Reason: " + reason);
if ((SystemClock.elapsedRealtime() - lastLockTime) >= (45 * 1000)) {
resetLockCouinters();
logAction("Timed out lock counters!");
}
if (lockCounter >= lockThreshhold) {
resetLockCouinters();
mDPM.lockNow();
logAction("Locking!");
}
lastLockTime = SystemClock.elapsedRealtime();
} else {
setWatching(false, "Screen is locked!");
}
}
private static FlipDetector.FlipListener flipListener;
private static MovementDetector.MovementListener movementListener;
private static void setupLockGestures() {
flipListener = new FlipDetector.FlipListener() {
@Override public void onFaceUp() {
lockCounterFaceDown = 0;
}
@Override public void onFaceDown() {
lockCounterFaceDown++;
lock("Facing down on table!", lockCounterFaceDown, lockThreshholdFaceDown);
}
};
movementListener = new MovementDetector.MovementListener() {
@Override public void onMovement() {
}
@Override public void onStationary() {
lockCounterNoMovement++;
lock("No movement detected!", lockCounterNoMovement, lockThreshholdNoMovement);
}
};
}
protected static void setWatching(boolean watching, String reason) {
if(watching) {
Sensey.getInstance().startFlipDetection(flipListener);
Sensey.getInstance().startMovementDetection(movementListener);
} else {
Sensey.getInstance().stopFlipDetection(flipListener);
Sensey.getInstance().stopMovementDetection(movementListener);
}
logAction((watching ? "Started" : "Stopped") + " watching sensors! Reason: " + reason);
}
}
| 5,409 | Java | .java | Divested-Mobile/MotionLock | 11 | 3 | 0 | 2020-06-02T21:02:42Z | 2024-04-21T18:26:32Z |
ScreenStateReceiver.java | /FileExtraction/Java_unseen/Divested-Mobile_MotionLock/app/src/main/java/us/spotco/motionlock/ScreenStateReceiver.java | /*
Copyright (c) 2017 Divested Computing Group
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package us.spotco.motionlock;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ScreenStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
WatchdogService.setWatching(false, "Screen is off");
} else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
WatchdogService.setWatching(true, "Screen is on");
}
}
}
| 1,222 | Java | .java | Divested-Mobile/MotionLock | 11 | 3 | 0 | 2020-06-02T21:02:42Z | 2024-04-21T18:26:32Z |
MainActivity.java | /FileExtraction/Java_unseen/Divested-Mobile_MotionLock/app/src/main/java/us/spotco/motionlock/MainActivity.java | /*
Copyright (c) 2017-2019 Divested Computing Group
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package us.spotco.motionlock;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.WindowManager;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
setTheme(android.R.style.Theme_DeviceDefault_DayNight);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!AdminHelper.getAdminHelper(this).isAdmin()) {
AdminHelper.getAdminHelper(this).requestAdmin(this);
} else {
Intent watchdog = new Intent(this, WatchdogService.class);
startService(watchdog);
finish();
}
}
}
| 1,662 | Java | .java | Divested-Mobile/MotionLock | 11 | 3 | 0 | 2020-06-02T21:02:42Z | 2024-04-21T18:26:32Z |
LockReceiver.java | /FileExtraction/Java_unseen/Divested-Mobile_MotionLock/app/src/main/java/us/spotco/motionlock/LockReceiver.java | /*
Copyright (c) 2017 Divested Computing Group
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package us.spotco.motionlock;
import android.app.admin.DeviceAdminReceiver;
public class LockReceiver extends DeviceAdminReceiver {
}
| 801 | Java | .java | Divested-Mobile/MotionLock | 11 | 3 | 0 | 2020-06-02T21:02:42Z | 2024-04-21T18:26:32Z |
AdminHelper.java | /FileExtraction/Java_unseen/Divested-Mobile_MotionLock/app/src/main/java/us/spotco/motionlock/AdminHelper.java | /*
Copyright (c) 2017 Divested Computing Group
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package us.spotco.motionlock;
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
public class AdminHelper {
private static AdminHelper adminHelper;
private static ComponentName mLockReceiver;
private static DevicePolicyManager mDPM;
public AdminHelper(Context ctx) {
mLockReceiver = new ComponentName(ctx, LockReceiver.class);
mDPM = (DevicePolicyManager) ctx.getSystemService(Context.DEVICE_POLICY_SERVICE);
}
protected static AdminHelper getAdminHelper(Context ctx) {
if(adminHelper == null) {
adminHelper = new AdminHelper(ctx);
}
return adminHelper;
}
protected static boolean isAdmin() {
return mDPM.isAdminActive(mLockReceiver);
}
protected void requestAdmin(Activity activity) {
Intent requestAdmin = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
requestAdmin.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mLockReceiver);
requestAdmin.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Required to lock the device");
activity.startActivityForResult(requestAdmin, 1);
}
}
| 1,927 | Java | .java | Divested-Mobile/MotionLock | 11 | 3 | 0 | 2020-06-02T21:02:42Z | 2024-04-21T18:26:32Z |
Test04Owner.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/Test04Owner.java | package org.woehlke.javaee7.petclinic.web;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.woehlke.javaee7.petclinic.web.pages.*;
import java.net.URL;
import java.util.Date;
import java.util.logging.Logger;
import static org.jboss.arquillian.graphene.Graphene.goTo;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 22.01.14
* Time: 19:16
* To change this template use File | Settings | File Templates.
*/
@RunWith(Arquillian.class)
public class Test04Owner {
private static Logger log = Logger.getLogger(Test04Owner.class.getName());
@Deployment(testable = false)
public static WebArchive createDeployment() {
return Deployments.createOwnerDeployment();
}
@Drone
WebDriver driver;
@ArquillianResource
URL deploymentUrl;
@Page
private HelloPage helloPage;
@Page
private FindOwnersPage findOwnersPage;
@Page
private OwnersPage ownersPage;
@Page
private NewOwnerPage newOwnerPage;
@Page
private ShowOwnerPage showOwnerPage;
@Page
private EditOwnerPage editOwnerPage;
@Page
private NewPetPage newPetPage;
@Page
private NewVisitPage newVisitPage;
@Page
private EditPetPage editPetPage;
@Page
private PetTypesPage petTypesPage;
@Page
private NewPetTypePage newPetTypePage;
@Test
@InSequence(1)
@RunAsClient
public void testOpeningHomePage() {
goTo(HelloPage.class);
helloPage.assertTitle();
}
@Test
@InSequence(2)
@RunAsClient
public void testOpenFindOwnersPage() {
goTo(FindOwnersPage.class);
findOwnersPage.assertPageIsLoaded();
}
@Test
@InSequence(3)
@RunAsClient
public void testOpenOwnersPage() {
goTo(FindOwnersPage.class);
findOwnersPage.assertPageIsLoaded();
findOwnersPage.clickSearch();
ownersPage.assertPageIsLoaded();
}
@Test
@InSequence(4)
@RunAsClient
public void testOpenNewOwnerPage() {
goTo(FindOwnersPage.class);
findOwnersPage.assertPageIsLoaded();
findOwnersPage.clickNewOwner();
newOwnerPage.assertPageIsLoaded();
}
@Test
@InSequence(5)
@RunAsClient
public void testOpenNewOwnerPageFromOwnersList() {
goTo(FindOwnersPage.class);
findOwnersPage.assertPageIsLoaded();
findOwnersPage.clickSearch();
ownersPage.assertPageIsLoaded();
ownersPage.clickNewOwner();
newOwnerPage.assertPageIsLoaded();
}
@Test
@InSequence(6)
@RunAsClient
public void testAddNewOwner() {
goTo(FindOwnersPage.class);
findOwnersPage.assertPageIsLoaded();
findOwnersPage.clickSearch();
ownersPage.assertPageIsLoaded();
ownersPage.clickNewOwner();
newOwnerPage.assertPageIsLoaded();
newOwnerPage.addNewContent("Thomas","Woehlke","Schoenhauser Allee 42","Berlin","03012345678");
ownersPage.assertPageIsLoaded();
ownersPage.assertNewContentFound("Thomas","Woehlke","Schoenhauser Allee 42","Berlin","03012345678");
}
@Test
@InSequence(7)
@RunAsClient
public void testEditOwner() {
goTo(FindOwnersPage.class);
findOwnersPage.assertPageIsLoaded();
findOwnersPage.clickSearch();
ownersPage.assertPageIsLoaded();
ownersPage.clickShowOwner();
showOwnerPage.assertPageIsLoaded();
showOwnerPage.clickEditOwner();
editOwnerPage.assertPageIsLoaded();
editOwnerPage.editContent("Willy","Wombel","Elbchaussee 242","Hamburg","04012345678");
showOwnerPage.assertPageIsLoaded();
showOwnerPage.assertContent("Willy","Wombel","Elbchaussee 242","Hamburg","04012345678");
}
@Test
@InSequence(8)
@RunAsClient
public void testAddNewPet() {
goTo(PetTypesPage.class);
petTypesPage.assertPageIsLoaded();
petTypesPage.clickAddNewPetType();
newPetTypePage.addNewContent("cat");
petTypesPage.clickAddNewPetType();
newPetTypePage.addNewContent("dog");
petTypesPage.clickAddNewPetType();
newPetTypePage.addNewContent("mouse");
goTo(FindOwnersPage.class);
findOwnersPage.assertPageIsLoaded();
findOwnersPage.clickSearch();
ownersPage.assertPageIsLoaded();
ownersPage.clickShowOwner();
showOwnerPage.assertPageIsLoaded();
showOwnerPage.clickAddNewPet();
newPetPage.assertPageIsLoaded();
Date birthDate1 = new Date(113, 04, 15); //15.05.2013
Date birthDate2 = new Date(112, 07, 03); //03.08.2012
newPetPage.setContent("Tomcat", birthDate1, "cat");
showOwnerPage.assertPageIsLoaded();
showOwnerPage.clickAddNewPet();
newPetPage.setContent("Bully", birthDate2, "dog");
showOwnerPage.assertPageIsLoaded();
showOwnerPage.assertFirstPetContent("Bully", birthDate2, "dog");
showOwnerPage.assertSecondPetContent("Tomcat", birthDate1, "cat");
}
@Test
@InSequence(9)
@RunAsClient
public void testEditPet() {
goTo(FindOwnersPage.class);
findOwnersPage.assertPageIsLoaded();
findOwnersPage.clickSearch();
ownersPage.assertPageIsLoaded();
ownersPage.clickShowOwner();
showOwnerPage.assertPageIsLoaded();
showOwnerPage.clickEditFirstPet();
editPetPage.assertPageIsLoaded();
Date birthDate = new Date(110, 05, 01); //01.06.2010
editPetPage.setContent("Speedy", birthDate, "mouse");
showOwnerPage.assertPageIsLoaded();
showOwnerPage.assertFirstPetContent("Speedy", birthDate, "mouse");
}
@Test
@InSequence(10)
@RunAsClient
public void testAddVisitToFirstPet() {
goTo(FindOwnersPage.class);
findOwnersPage.assertPageIsLoaded();
findOwnersPage.clickSearch();
ownersPage.assertPageIsLoaded();
ownersPage.clickShowOwner();
showOwnerPage.assertPageIsLoaded();
showOwnerPage.addVisitToFirstPet();
newVisitPage.assertPageIsLoaded();
Date birthDate = new Date(110, 05, 01); //01.06.2010
newVisitPage.assertOwnerContent("Willy","Wombel");
newVisitPage.assertPetContent("Speedy", birthDate, "mouse");
Date visitDate = new Date(114, 01, 16); //16.01.2014
newVisitPage.setNewContent(visitDate,"get milk");
showOwnerPage.assertFirstVisitToFirstPet(visitDate,"get milk");
}
}
| 6,954 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Deployments.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/Deployments.java | package org.woehlke.javaee7.petclinic.web;
import org.jboss.shrinkwrap.api.Filters;
import org.jboss.shrinkwrap.api.GenericArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.importer.ExplodedImporter;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.woehlke.javaee7.petclinic.dao.*;
import org.woehlke.javaee7.petclinic.entities.*;
import org.woehlke.javaee7.petclinic.services.OwnerService;
import org.woehlke.javaee7.petclinic.services.OwnerServiceImpl;
import java.io.File;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 20.01.14
* Time: 08:45
* To change this template use File | Settings | File Templates.
*/
public class Deployments {
private static final String WEBAPP_SRC = "src/main/webapp";
public static WebArchive createSpecialtiesDeployment() {
File[] deps = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile();
WebArchive war = null;
try {
war = ShrinkWrap.create(WebArchive.class, "specialties.war")
.addClasses(SpecialtyController.class, LanguageBean.class,
SpecialtyDao.class, SpecialtyDaoImpl.class,
Owner.class, Pet.class, PetType.class,
Specialty.class, Vet.class, Visit.class)
.merge(ShrinkWrap.create(GenericArchive.class).as(ExplodedImporter.class)
.importDirectory(WEBAPP_SRC).as(GenericArchive.class),
"/", Filters.include(".*\\.xhtml$|.*\\.html$"))
.addAsResource("META-INF/persistence.xml")
.addAsResource("messages_de.properties")
.addAsResource("messages_en.properties")
.addAsLibraries(deps)
.addAsWebInfResource(
new StringAsset("<faces-config version=\"2.2\"/>"),
"faces-config.xml");
} catch (Exception e) {
e.printStackTrace();
}
return war;
}
public static WebArchive createPetTypeDeployment() {
File[] deps = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile();
return ShrinkWrap.create(WebArchive.class, "pettypes.war")
.addClasses(PetTypeController.class, LanguageBean.class,
PetTypeDao.class, PetTypeDaoImpl.class,
Owner.class, Pet.class, PetType.class,
Specialty.class, Vet.class, Visit.class)
.merge(ShrinkWrap.create(GenericArchive.class).as(ExplodedImporter.class)
.importDirectory(WEBAPP_SRC).as(GenericArchive.class),
"/", Filters.include(".*\\.xhtml$|.*\\.html$"))
.addAsResource("META-INF/persistence.xml")
.addAsResource("messages_de.properties")
.addAsResource("messages_en.properties")
.addAsLibraries(deps)
.addAsWebInfResource(
new StringAsset("<faces-config version=\"2.2\"/>"),
"faces-config.xml");
}
public static WebArchive createVetDeployment() {
File[] deps = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile();
return ShrinkWrap.create(WebArchive.class, "vet.war")
.addClasses(
SpecialtyController.class, VetController.class, LanguageBean.class,
SpecialtyConverter.class,
SpecialtyDao.class, SpecialtyDaoImpl.class,
VetDao.class, VetDaoImpl.class,
Owner.class, Pet.class, PetType.class,
Specialty.class, Vet.class, Visit.class,
VetSortingBean.class)
.merge(ShrinkWrap.create(GenericArchive.class).as(ExplodedImporter.class)
.importDirectory(WEBAPP_SRC).as(GenericArchive.class),
"/", Filters.include(".*\\.xhtml$|.*\\.html$"))
.addAsResource("META-INF/persistence.xml")
.addAsResource("messages_de.properties")
.addAsResource("messages_en.properties")
.addAsLibraries(deps)
.addAsWebInfResource(
new StringAsset("<faces-config version=\"2.2\"/>"),
"faces-config.xml");
}
public static WebArchive createOwnerDeployment() {
File[] deps = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile();
WebArchive war = null;
try {
war = ShrinkWrap.create(WebArchive.class, "owner.war")
.addClasses(OwnerController.class, PetTypeController.class, LanguageBean.class,
OwnerService.class, OwnerServiceImpl.class,
OwnerDao.class, OwnerDaoImpl.class, PetDao.class, PetDaoImpl.class,
VisitDao.class, VisitDaoImpl.class,
PetTypeDao.class, PetTypeDaoImpl.class,
Owner.class, Pet.class, PetType.class,
Specialty.class, Vet.class, Visit.class)
.merge(ShrinkWrap.create(GenericArchive.class).as(ExplodedImporter.class)
.importDirectory(WEBAPP_SRC).as(GenericArchive.class),
"/", Filters.include(".*\\.xhtml$"))
.addAsResource("META-INF/persistence.xml")
.addAsResource("messages_de.properties")
.addAsResource("messages_en.properties")
.addAsLibraries(deps)
.addAsWebInfResource(
new StringAsset("<faces-config version=\"2.2\"/>"),
"faces-config.xml");
} catch (Exception e) {
e.printStackTrace();
}
return war;
}
}
| 6,174 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Test02Vet.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/Test02Vet.java | package org.woehlke.javaee7.petclinic.web;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.woehlke.javaee7.petclinic.web.pages.*;
import java.net.URL;
import java.util.logging.Logger;
import static org.jboss.arquillian.graphene.Graphene.goTo;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 21.01.14
* Time: 21:54
* To change this template use File | Settings | File Templates.
*/
@RunWith(Arquillian.class)
public class Test02Vet {
private static Logger log = Logger.getLogger(Test02Vet.class.getName());
@Deployment(testable = false)
public static WebArchive createDeployment() {
return Deployments.createVetDeployment();
}
@Drone
WebDriver driver;
@ArquillianResource
URL deploymentUrl;
@Page
private HelloPage helloPage;
@Page
private VetsPage vetsPage;
@Page
private NewVetPage newVetPage;
@Page
private EditVetPage editVetPage;
@Page
private SpecialtiesPage specialtiesPage;
@Page
private NewSpecialtiesPage newSpecialtiesPage;
@Test
@InSequence(1)
@RunAsClient
public void testOpeningHomePage() {
goTo(HelloPage.class);
helloPage.assertTitle();
}
@Test
@InSequence(2)
@RunAsClient
public void testOpeningVetPage() {
goTo(VetsPage.class);
vetsPage.assertPageIsLoaded();
}
@Test
@InSequence(3)
@RunAsClient
public void testNewVetPage() {
goTo(VetsPage.class);
vetsPage.assertPageIsLoaded();
vetsPage.clickAddNewVet();
newVetPage.assertPageIsLoaded();
newVetPage.addNewContent("Thomas","Woehlke");
vetsPage.assertPageIsLoaded();
vetsPage.assertNewContentFound("Thomas", "Woehlke");
}
@Test
@InSequence(4)
@RunAsClient
public void testEditVetPage() {
goTo(VetsPage.class);
vetsPage.assertPageIsLoaded();
vetsPage.clickEditVet();
editVetPage.assertPageIsLoaded();
editVetPage.editContent("Willy", "Wacker");
vetsPage.assertPageIsLoaded();
vetsPage.assertEditedContentFound("Willy", "Wacker");
}
@Test
@InSequence(5)
@RunAsClient
public void testDeleteVetPage() {
goTo(VetsPage.class);
vetsPage.assertPageIsLoaded();
vetsPage.clickDeleteVet();
vetsPage.assertPageIsLoaded();
vetsPage.assertDeletedContentNotFound();
}
@Test
@InSequence(6)
@RunAsClient
public void testNewVetPageWithSpecialties() {
goTo(SpecialtiesPage.class);
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.addNewContent("dentist");
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.addNewContent("anesthetist");
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.addNewContent("radiology");
goTo(VetsPage.class);
vetsPage.assertPageIsLoaded();
vetsPage.clickAddNewVet();
newVetPage.assertPageIsLoaded();
newVetPage.addNewContentWithAllSpecialties("Thomas", "Woehlke");
vetsPage.assertPageIsLoaded();
vetsPage.assertContentFoundWithSpecialties("Thomas", "Woehlke", "anesthetist dentist radiology");
}
@Test
@InSequence(7)
@RunAsClient
public void testEditVetPageWithSpecialties() {
goTo(VetsPage.class);
vetsPage.clickEditVet();
editVetPage.assertPageIsLoaded();
editVetPage.editContentWithNoneSpecialties("Henry", "Jones");
vetsPage.assertPageIsLoaded();
vetsPage.assertContentFoundWithSpecialties("Henry", "Jones", "none");
}
/**
* Test for #24 new specialties not visible in veterinarians editmode
*/
@Test
@InSequence(8)
@RunAsClient
public void testEditVetPageWithNewSpecialties(){
goTo(VetsPage.class);
vetsPage.assertPageIsLoaded();
goTo(SpecialtiesPage.class);
specialtiesPage.assertPageIsLoaded();
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.assertPageIsLoaded();
newSpecialtiesPage.addNewContent("hero");
goTo(VetsPage.class);
vetsPage.assertPageIsLoaded();
vetsPage.clickEditVet();
editVetPage.assertPageIsLoaded();
editVetPage.editContentWithAllSpecialties("Thomas", "Woehlke");
vetsPage.assertPageIsLoaded();
vetsPage.assertContentFoundWithSpecialties("Thomas", "Woehlke", "anesthetist dentist hero radiology");
}
@Test
@InSequence(9)
@RunAsClient
public void testFillNewVetPageWithSpecialties() {
goTo(SpecialtiesPage.class);
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.addNewContent("s01");
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.addNewContent("s02");
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.addNewContent("s03");
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.addNewContent("s04");
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.addNewContent("s05");
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.addNewContent("s06");
}
@Test
@InSequence(10)
@RunAsClient
public void testFillNewVetsPage() {
goTo(VetsPage.class);
vetsPage.assertPageIsLoaded();
vetsPage.clickDeleteVet();
vetsPage.assertPageIsLoaded();
vetsPage.clickAddNewVet();
newVetPage.assertPageIsLoaded();
newVetPage.addNewContentWithOneSpecialty("Vorname01", "Nachname06","s03");
vetsPage.clickAddNewVet();
newVetPage.assertPageIsLoaded();
newVetPage.addNewContentWithOneSpecialty("Vorname02", "Nachname05","s02");
vetsPage.clickAddNewVet();
newVetPage.assertPageIsLoaded();
newVetPage.addNewContentWithOneSpecialty("Vorname03", "Nachname04", "s01");
vetsPage.clickAddNewVet();
newVetPage.assertPageIsLoaded();
newVetPage.addNewContentWithOneSpecialty("Vorname04", "Nachname03", "s06");
vetsPage.clickAddNewVet();
newVetPage.assertPageIsLoaded();
newVetPage.addNewContentWithOneSpecialty("Vorname05", "Nachname02", "s05");
vetsPage.clickAddNewVet();
newVetPage.assertPageIsLoaded();
newVetPage.addNewContentWithOneSpecialty("Vorname06", "Nachname01", "s04");
vetsPage.assertPageIsLoaded();
}
@Test
@InSequence(11)
@RunAsClient
public void testVetsPager() {
vetsPage.assertPagerNextIsLoaded();
vetsPage.clickPagerNext();
vetsPage.assertPagerPrevIsLoaded();
vetsPage.clickPagerPrev();
vetsPage.assertPagerNextIsLoaded();
}
@Test
@InSequence(12)
@RunAsClient
public void testVetsSorterFirstname() {
vetsPage.assertSorterIsLoaded();
vetsPage.assertOrder();
vetsPage.clickSorterFirstname();
vetsPage.assertFirstnameOrder();
vetsPage.clickSorterFirstname();
vetsPage.assertFirstnameReverseOrder();
}
@Test
@InSequence(13)
@RunAsClient
public void testVetsSorterLastname() {
vetsPage.clickSorterLastname();
vetsPage.assertLastnameOrder();
vetsPage.clickSorterLastname();
vetsPage.assertLastnameReverseOrder();
}
@Test
@InSequence(14)
@RunAsClient
public void testVetsSorterSpecialty() {
vetsPage.clickSorterSpecialty();
vetsPage.assertSpecialtyOrder();
vetsPage.clickSorterSpecialty();
vetsPage.assertSpecialtyReverseOrder();
}
}
| 8,097 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Test03PetType.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/Test03PetType.java | package org.woehlke.javaee7.petclinic.web;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.woehlke.javaee7.petclinic.web.pages.EditPetTypePage;
import org.woehlke.javaee7.petclinic.web.pages.HelloPage;
import org.woehlke.javaee7.petclinic.web.pages.NewPetTypePage;
import org.woehlke.javaee7.petclinic.web.pages.PetTypesPage;
import java.net.URL;
import java.util.logging.Logger;
import static org.jboss.arquillian.graphene.Graphene.goTo;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 21.01.14
* Time: 12:09
* To change this template use File | Settings | File Templates.
*/
@RunWith(Arquillian.class)
public class Test03PetType {
private static Logger log = Logger.getLogger(Test03PetType.class.getName());
@Deployment(testable = false)
public static WebArchive createDeployment() {
return Deployments.createPetTypeDeployment();
}
@Drone
WebDriver driver;
@ArquillianResource
URL deploymentUrl;
@Page
private HelloPage helloPage;
@Page
private PetTypesPage petTypesPage;
@Page
private NewPetTypePage newPetTypePage;
@Page
private EditPetTypePage editPetTypePage;
@Test
@InSequence(1)
@RunAsClient
public void testOpeningHomePage() {
goTo(HelloPage.class);
helloPage.assertTitle();
}
@Test
@InSequence(2)
@RunAsClient
public void testOpeningPetTypesPage() {
goTo(PetTypesPage.class);
petTypesPage.assertPageIsLoaded();
}
@Test
@InSequence(3)
@RunAsClient
public void testNewPetTypePage() {
goTo(PetTypesPage.class);
petTypesPage.assertPageIsLoaded();
petTypesPage.clickAddNewPetType();
newPetTypePage.assertPageIsLoaded();
newPetTypePage.addNewContent("dog");
petTypesPage.assertPageIsLoaded();
petTypesPage.assertNewContentFound("dog");
}
@Test
@InSequence(4)
@RunAsClient
public void testEditPetTypePage() {
goTo(PetTypesPage.class);
petTypesPage.assertPageIsLoaded();
petTypesPage.clickEditSpecialty();
editPetTypePage.assertPageIsLoaded();
editPetTypePage.editContent("mouse");
petTypesPage.assertPageIsLoaded();
petTypesPage.assertEditedContentFound("mouse");
}
@Test
@InSequence(5)
@RunAsClient
public void testDeletePetTypePage() {
goTo(PetTypesPage.class);
petTypesPage.assertPageIsLoaded();
petTypesPage.clickDeleteSpecialty();
petTypesPage.assertPageIsLoaded();
petTypesPage.assertDeletedContentNotFound();
}
@Test
@InSequence(6)
@RunAsClient
public void testFillNewPetTypes() {
goTo(PetTypesPage.class);
petTypesPage.assertPageIsLoaded();
petTypesPage.clickAddNewPetType();
newPetTypePage.assertPageIsLoaded();
newPetTypePage.addNewContent("pet01");
petTypesPage.assertPageIsLoaded();
petTypesPage.assertNewContentFound("pet01");
petTypesPage.clickAddNewPetType();
newPetTypePage.assertPageIsLoaded();
newPetTypePage.addNewContent("pet02");
petTypesPage.assertPageIsLoaded();
petTypesPage.clickAddNewPetType();
newPetTypePage.assertPageIsLoaded();
newPetTypePage.addNewContent("pet03");
petTypesPage.assertPageIsLoaded();
petTypesPage.clickAddNewPetType();
newPetTypePage.assertPageIsLoaded();
newPetTypePage.addNewContent("pet04");
petTypesPage.assertPageIsLoaded();
petTypesPage.clickAddNewPetType();
newPetTypePage.assertPageIsLoaded();
newPetTypePage.addNewContent("pet05");
petTypesPage.assertPageIsLoaded();
petTypesPage.clickAddNewPetType();
newPetTypePage.assertPageIsLoaded();
newPetTypePage.addNewContent("pet06");
petTypesPage.assertPageIsLoaded();
}
@Test
@InSequence(7)
@RunAsClient
public void testPetTypesPager() {
petTypesPage.assertPagerNextIsLoaded();
petTypesPage.clickPagerNext();
petTypesPage.assertPagerPrevIsLoaded();
petTypesPage.clickPagerPrev();
petTypesPage.assertPagerNextIsLoaded();
}
@Test
@InSequence(8)
@RunAsClient
public void testPetTypesSorter() {
petTypesPage.assertSorterIsLoaded();
petTypesPage.assertOrder();
petTypesPage.clickSorter();
petTypesPage.assertReverseOrder();
petTypesPage.assertSorterIsLoaded();
petTypesPage.clickSorter();
petTypesPage.assertOrder();
}
}
| 5,063 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Test01Specialties.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/Test01Specialties.java | package org.woehlke.javaee7.petclinic.web;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.woehlke.javaee7.petclinic.web.pages.EditSpecialtiesPage;
import org.woehlke.javaee7.petclinic.web.pages.HelloPage;
import org.woehlke.javaee7.petclinic.web.pages.NewSpecialtiesPage;
import org.woehlke.javaee7.petclinic.web.pages.SpecialtiesPage;
import java.net.URL;
import java.util.logging.Logger;
import static org.jboss.arquillian.graphene.Graphene.goTo;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 19.01.14
* Time: 16:28
* To change this template use File | Settings | File Templates.
*/
@RunWith(Arquillian.class)
public class Test01Specialties {
private static Logger log = Logger.getLogger(Test01Specialties.class.getName());
@Deployment(testable = false)
public static WebArchive createDeployment() {
return Deployments.createSpecialtiesDeployment();
}
@Drone
private WebDriver driver;
@ArquillianResource
private URL deploymentUrl;
@Page
private HelloPage helloPage;
@Page
private SpecialtiesPage specialtiesPage;
@Page
private NewSpecialtiesPage newSpecialtiesPage;
@Page
private EditSpecialtiesPage editSpecialtiesPage;
@Test
@InSequence(1)
@RunAsClient
public void testOpeningHomePage() {
goTo(HelloPage.class);
helloPage.assertTitle();
}
@Test
@InSequence(2)
@RunAsClient
public void testOpeningSpecialtiesPage() {
goTo(SpecialtiesPage.class);
specialtiesPage.assertPageIsLoaded();
}
@Test
@InSequence(3)
@RunAsClient
public void testNewSpecialtyPage() {
goTo(SpecialtiesPage.class);
specialtiesPage.assertPageIsLoaded();
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.assertPageIsLoaded();
newSpecialtiesPage.addNewContent("dentist");
specialtiesPage.assertPageIsLoaded();
specialtiesPage.assertNewContentFound("dentist");
}
@Test
@InSequence(4)
@RunAsClient
public void testEditSpecialtyPage() {
goTo(SpecialtiesPage.class);
specialtiesPage.assertPageIsLoaded();
specialtiesPage.clickEditSpecialty();
editSpecialtiesPage.assertPageIsLoaded();
editSpecialtiesPage.editContent("specialist");
specialtiesPage.assertPageIsLoaded();
specialtiesPage.assertEditedContentFound("specialist");
}
@Test
@InSequence(5)
@RunAsClient
public void testDeleteSpecialtyPage() {
goTo(SpecialtiesPage.class);
specialtiesPage.assertPageIsLoaded();
specialtiesPage.clickDeleteSpecialty();
specialtiesPage.assertPageIsLoaded();
specialtiesPage.assertDeletedContentNotFound();
}
@Test
@InSequence(6)
@RunAsClient
public void testFillSpecialtyPager() {
goTo(SpecialtiesPage.class);
specialtiesPage.assertPageIsLoaded();
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.assertPageIsLoaded();
newSpecialtiesPage.addNewContent("specialty01");
specialtiesPage.assertPageIsLoaded();
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.assertPageIsLoaded();
newSpecialtiesPage.addNewContent("specialty02");
specialtiesPage.assertPageIsLoaded();
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.assertPageIsLoaded();
newSpecialtiesPage.addNewContent("specialty03");
specialtiesPage.assertPageIsLoaded();
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.assertPageIsLoaded();
newSpecialtiesPage.addNewContent("specialty04");
specialtiesPage.assertPageIsLoaded();
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.assertPageIsLoaded();
newSpecialtiesPage.addNewContent("specialty05");
specialtiesPage.assertPageIsLoaded();
specialtiesPage.clickAddNewSpecialty();
newSpecialtiesPage.assertPageIsLoaded();
newSpecialtiesPage.addNewContent("specialty06");
specialtiesPage.assertPageIsLoaded();
}
@Test
@InSequence(7)
@RunAsClient
public void testSpecialtyPager() {
specialtiesPage.assertPagerNextIsLoaded();
specialtiesPage.clickPagerNext();
specialtiesPage.assertPagerPrevIsLoaded();
specialtiesPage.clickPagerPrev();
specialtiesPage.assertPagerNextIsLoaded();
}
@Test
@InSequence(8)
@RunAsClient
public void testSpecialtySorter() {
specialtiesPage.assertSorterIsLoaded();
specialtiesPage.assertOrder();
specialtiesPage.clickSorter();
specialtiesPage.assertReverseOrder();
specialtiesPage.assertSorterIsLoaded();
specialtiesPage.clickSorter();
specialtiesPage.assertOrder();
}
}
| 5,346 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
NewPetTypePage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/NewPetTypePage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.jboss.arquillian.graphene.Graphene;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 26.01.14
* Time: 18:56
* To change this template use File | Settings | File Templates.
*/
public class NewPetTypePage {
@FindBy(id="addNewPetType")
private WebElement addNewPetType;
@FindBy(id="addNewPetTypeForm:name")
private WebElement name;
@FindBy(id="addNewPetTypeForm:save")
private WebElement save;
public void assertPageIsLoaded() {
Graphene.waitModel().until().element(addNewPetType).is().visible();
Assert.assertTrue(addNewPetType.isDisplayed());
}
public void addNewContent(String content) {
name.clear();
name.sendKeys(content);
Graphene.guardHttp(save).click();
}
}
| 928 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
EditSpecialtiesPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/EditSpecialtiesPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 26.01.14
* Time: 18:14
* To change this template use File | Settings | File Templates.
*/
public class EditSpecialtiesPage {
@FindBy(id="editSpecialty")
private WebElement editSpecialty;
@FindBy(id="editSpecialtyForm:name")
private WebElement name;
@FindBy(id="editSpecialtyForm:save")
private WebElement save;
public void assertPageIsLoaded() {
Assert.assertTrue(editSpecialty.isDisplayed());
}
public void editContent(String content) {
name.clear();
name.sendKeys(content);
save.click();
}
}
| 788 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
VetsPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/VetsPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.jboss.arquillian.graphene.Graphene;
import org.jboss.arquillian.graphene.page.Location;
import org.junit.Assert;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 26.01.14
* Time: 20:34
* To change this template use File | Settings | File Templates.
*/
@Location("vets.jsf")
public class VetsPage {
@FindBy(id="veterinarians")
private WebElement veterinarians;
@FindBy(id="veterinariansForm:getNewVetForm")
private WebElement getNewVetForm;
@FindBy(id="veterinariansForm:veterinariansTable:5:firstName")
private WebElement firstName5InTable;
@FindBy(id="veterinariansForm:veterinariansTable:5:lastName")
private WebElement lastName5InTable;
@FindBy(id="veterinariansForm:veterinariansTable:0:firstName")
private WebElement firstNameInTable;
@FindBy(id="veterinariansForm:veterinariansTable:0:lastName")
private WebElement lastNameInTable;
@FindBy(id="veterinariansForm:veterinariansTable:0:specialtiesAsString")
private WebElement specialtiesAsStringInTable;
@FindBy(id="veterinariansForm:veterinariansTable:2:specialtiesAsString")
private WebElement specialtiesAsString2InTable;
@FindBy(id="veterinariansForm:veterinariansTable:3:specialtiesAsString")
private WebElement specialtiesAsString3InTable;
@FindBy(id="veterinariansForm:veterinariansTable:0:edit")
private WebElement editInTable;
@FindBy(id="veterinariansForm:veterinariansTable:0:delete")
private WebElement deleteInTable;
@FindBy(id="veterinariansForm:scroller_ds_next")
private WebElement scrollerNext;
@FindBy(id="veterinariansForm:scroller_ds_prev")
private WebElement scrollerPrev;
@FindBy(id="veterinariansForm:veterinariansTable:colSurnameSort")
private WebElement colSurnameSort;
@FindBy(id="veterinariansForm:veterinariansTable:colLastnameSort")
private WebElement colLastnameSort;
@FindBy(id="veterinariansForm:veterinariansTable:colSpecialtySort")
private WebElement colSpecialtySort;
public void assertPageIsLoaded() {
Assert.assertTrue(veterinarians.isDisplayed());
}
public void clickAddNewVet() {
getNewVetForm.click();
}
public void assertNewContentFound(String firstName, String lastName) {
Assert.assertEquals(firstName,firstNameInTable.getText());
Assert.assertEquals(lastName, lastNameInTable.getText());
}
public void clickEditVet() {
editInTable.click();
}
public void assertEditedContentFound(String firstName, String lastName) {
Assert.assertEquals(firstName,firstNameInTable.getText());
Assert.assertEquals(lastName, lastNameInTable.getText());
}
public void clickDeleteVet() {
deleteInTable.click();
}
public void assertDeletedContentNotFound() {
boolean isDeletedFirstName = false;
try {
Assert.assertEquals(null,firstNameInTable);
} catch (NoSuchElementException elementException) {
isDeletedFirstName = true;
}
Assert.assertTrue(isDeletedFirstName);
boolean isDeletedLastName = false;
try {
Assert.assertEquals(null,lastNameInTable);
} catch (NoSuchElementException elementException) {
isDeletedLastName = true;
}
Assert.assertTrue(isDeletedLastName);
}
public void assertContentFoundWithSpecialties(String firstName, String lastName, String specialties) {
Assert.assertEquals(firstName, firstNameInTable.getText());
Assert.assertEquals(lastName, lastNameInTable.getText());
Assert.assertEquals(specialties, specialtiesAsStringInTable.getText());
}
public void assertPagerNextIsLoaded(){
Graphene.waitModel().until().element(scrollerNext).is().visible();
Assert.assertTrue(scrollerNext.isDisplayed());
}
public void assertPagerPrevIsLoaded(){
Graphene.waitModel().until().element(scrollerPrev).is().visible();
Assert.assertTrue(scrollerPrev.isDisplayed());
}
public void clickPagerNext() {
scrollerNext.click();
}
public void clickPagerPrev() {
scrollerPrev.click();
}
public void assertSorterIsLoaded(){
Graphene.waitModel().until().element(colSurnameSort).is().visible();
Graphene.waitModel().until().element(colLastnameSort).is().visible();
Assert.assertTrue(colSurnameSort.isDisplayed());
Assert.assertTrue(colLastnameSort.isDisplayed());
}
public void assertOrder() {
Graphene.waitModel().until().element(firstNameInTable).is().visible();
Graphene.waitModel().until().element(lastNameInTable).is().visible();
Assert.assertTrue(firstNameInTable.getText().compareTo("Vorname06") == 0);
Assert.assertTrue(lastNameInTable.getText().compareTo("Nachname01") == 0);
}
public void clickSorterFirstname() {
Graphene.waitModel().until().element(colSurnameSort).is().visible();
Graphene.guardAjax(colSurnameSort).click();
}
public void assertFirstnameOrder() {
Graphene.waitModel().until().element(firstName5InTable).is().visible();
Graphene.waitModel().until().element(lastName5InTable).is().visible();
Assert.assertTrue(firstName5InTable.getText().compareTo("Vorname01") == 0);
Assert.assertTrue(lastName5InTable.getText().compareTo("Nachname06") == 0);
}
public void assertFirstnameReverseOrder() {
Graphene.waitModel().until().element(firstNameInTable).is().visible();
Graphene.waitModel().until().element(lastNameInTable).is().visible();
Assert.assertTrue(firstNameInTable.getText().compareTo("Vorname06") == 0);
Assert.assertTrue(lastNameInTable.getText().compareTo("Nachname01") == 0);
}
public void clickSorterLastname() {
Graphene.waitModel().until().element(colLastnameSort).is().visible();
Graphene.guardAjax(colLastnameSort).click();
}
public void assertLastnameOrder() {
Graphene.waitModel().until().element(firstNameInTable).is().visible();
Graphene.waitModel().until().element(lastNameInTable).is().visible();
Assert.assertTrue(firstNameInTable.getText().compareTo("Vorname06") == 0);
Assert.assertTrue(lastNameInTable.getText().compareTo("Nachname01") == 0);
}
public void assertLastnameReverseOrder() {
Graphene.waitModel().until().element(firstName5InTable).is().visible();
Graphene.waitModel().until().element(lastName5InTable).is().visible();
Assert.assertTrue(firstName5InTable.getText().compareTo("Vorname01") == 0);
Assert.assertTrue(lastName5InTable.getText().compareTo("Nachname06") == 0);
}
public void assertSpecialtyOrder() {
Graphene.waitModel().until().element(specialtiesAsString3InTable).is().visible();
Assert.assertTrue(specialtiesAsString3InTable.getText().compareTo("s01") == 0);
}
public void assertSpecialtyReverseOrder() {
Graphene.waitModel().until().element(specialtiesAsString2InTable).is().visible();
Assert.assertTrue(specialtiesAsString2InTable.getText().compareTo("s06") == 0);
}
public void clickSorterSpecialty() {
Graphene.waitModel().until().element(colSpecialtySort).is().visible();
Graphene.guardAjax(colSpecialtySort).click();
}
}
| 7,561 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
EditVetPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/EditVetPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.richfaces.fragment.pickList.RichFacesPickList;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 26.01.14
* Time: 21:18
* To change this template use File | Settings | File Templates.
*/
public class EditVetPage {
@FindBy(id="editVeterinarian")
private WebElement editVeterinarian;
@FindBy(id="editVeterinarianForm:firstName")
private WebElement firstName;
@FindBy(id="editVeterinarianForm:lastName")
private WebElement lastName;
@FindBy(id="editVeterinarianForm:selectedSpecialtiesPickList")
private RichFacesPickList pickList;
@FindBy(id="editVeterinarianForm:save")
private WebElement save;
public void assertPageIsLoaded() {
Assert.assertTrue(editVeterinarian.isDisplayed());
}
public void editContent(String firstName,String lastName) {
this.firstName.clear();
this.firstName.sendKeys(firstName);
this.lastName.clear();
this.lastName.sendKeys(lastName);
save.click();
}
public void editContentWithNoneSpecialties(String firstName,String lastName) {
this.firstName.clear();
this.firstName.sendKeys(firstName);
this.lastName.clear();
this.lastName.sendKeys(lastName);
this.pickList.removeAll();
save.click();
}
public void editContentWithAllSpecialties(String firstName,String lastName) {
this.firstName.clear();
this.firstName.sendKeys(firstName);
this.lastName.clear();
this.lastName.sendKeys(lastName);
this.pickList.addAll();
save.click();
}
}
| 1,754 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
PetTypesPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/PetTypesPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.jboss.arquillian.graphene.Graphene;
import org.jboss.arquillian.graphene.page.Location;
import org.junit.Assert;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 26.01.14
* Time: 18:56
* To change this template use File | Settings | File Templates.
*/
@Location("petTypes.jsf")
public class PetTypesPage {
@FindBy(id="petTypes")
private WebElement petTypes;
@FindBy(id="petTypesForm:getNewPetTypeForm")
private WebElement getNewPetTypeForm;
@FindBy(id="petTypesForm:petTypesTable:5:name")
private WebElement name5InTable;
@FindBy(id="petTypesForm:petTypesTable:0:name")
private WebElement nameInTable;
@FindBy(id="petTypesForm:petTypesTable:0:edit")
private WebElement editInTable;
@FindBy(id="petTypesForm:petTypesTable:0:delete")
private WebElement deleteInTable;
@FindBy(id="petTypesForm:scroller_ds_next")
private WebElement scrollerNext;
@FindBy(id="petTypesForm:scroller_ds_prev")
private WebElement scrollerPrev;
@FindBy(id="petTypesForm:petTypesTable:colNameSort")
private WebElement colNameSort;
public void assertPageIsLoaded() {
Graphene.waitModel().until().element(petTypes).is().visible();
Assert.assertTrue(petTypes.isDisplayed());
}
public void clickAddNewPetType() {
Graphene.guardHttp(getNewPetTypeForm).click();
}
public void assertNewContentFound(String content) {
Assert.assertEquals(content, nameInTable.getText());
}
public void clickEditSpecialty() {
Graphene.guardHttp(editInTable).click();
}
public void assertEditedContentFound(String content) {
Assert.assertEquals(content, nameInTable.getText());
}
public void clickDeleteSpecialty() {
Graphene.guardHttp(deleteInTable).click();
}
public void assertDeletedContentNotFound() {
boolean isDeleted = false;
try {
Assert.assertEquals(null,nameInTable);
} catch (NoSuchElementException elementException) {
isDeleted = true;
}
Assert.assertTrue(isDeleted);
}
public void assertPagerNextIsLoaded(){
Graphene.waitModel().until().element(scrollerNext).is().visible();
Assert.assertTrue(scrollerNext.isDisplayed());
}
public void assertPagerPrevIsLoaded(){
Graphene.waitModel().until().element(scrollerPrev).is().visible();
Assert.assertTrue(scrollerPrev.isDisplayed());
}
public void clickPagerNext() {
scrollerNext.click();
}
public void clickPagerPrev() {
scrollerPrev.click();
}
public void assertSorterIsLoaded(){
Graphene.waitModel().until().element(colNameSort).is().visible();
Assert.assertTrue(colNameSort.isDisplayed());
}
public void assertOrder() {
Graphene.waitModel().until().element(nameInTable).is().visible();
Assert.assertTrue(nameInTable.getText().compareTo("pet01")==0);
}
public void clickSorter() {
Graphene.waitModel().until().element(colNameSort).is().visible();
colNameSort.click();
}
public void assertReverseOrder() {
Graphene.waitModel().until().element(name5InTable).is().visible();
Assert.assertTrue(name5InTable.getText().compareTo("pet06")==0);
}
}
| 3,502 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
HelloPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/HelloPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.graphene.page.Location;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 26.01.14
* Time: 17:05
* To change this template use File | Settings | File Templates.
*/
@Location("hello.jsf")
public class HelloPage {
@Drone
private WebDriver driver;
public void assertTitle(){
Assert.assertEquals("Java EE 7 Petclinic",driver.getTitle());
}
}
| 571 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
NewPetPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/NewPetPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.jboss.arquillian.graphene.Graphene;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.richfaces.fragment.calendar.RichFacesCalendar;
import java.util.Date;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 27.01.14
* Time: 16:49
* To change this template use File | Settings | File Templates.
*/
public class NewPetPage {
@FindBy(id="addNewPetForm")
private WebElement addNewPetForm;
@FindBy(id="addNewPetForm:petName")
private WebElement petName;
@FindBy(id="addNewPetForm:petBirthDate")
private RichFacesCalendar petBirthDate;
@FindBy(id="addNewPetForm:petType")
private WebElement petType;
@FindBy(id="addNewPetForm:add")
private WebElement add;
public void assertPageIsLoaded() {
Graphene.waitModel().until().element(addNewPetForm).is().visible();
Assert.assertTrue(addNewPetForm.isDisplayed());
}
public void setContent(String petName, Date petBirthDate, String petType){
this.petName.sendKeys(petName);
DateTime dateTime = new DateTime(petBirthDate.getTime());
this.petBirthDate.setDate(dateTime);
List<WebElement> options = this.petType.findElements(By.tagName("option"));
for(WebElement option: options){
if(option.getText().contentEquals(petType)){
option.click();
break;
}
}
Graphene.guardHttp(add).click();
}
}
| 1,638 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
EditPetTypePage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/EditPetTypePage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 26.01.14
* Time: 18:56
* To change this template use File | Settings | File Templates.
*/
public class EditPetTypePage {
@FindBy(id="editPetType")
private WebElement editPetType;
@FindBy(id="editPetTypeForm:name")
private WebElement name;
@FindBy(id="editPetTypeForm:save")
private WebElement save;
public void assertPageIsLoaded() {
Assert.assertTrue(editPetType.isDisplayed());
}
public void editContent(String content) {
name.clear();
name.sendKeys(content);
save.click();
}
}
| 775 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
NewVisitPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/NewVisitPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.jboss.arquillian.graphene.Graphene;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.richfaces.fragment.calendar.RichFacesCalendar;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 28.01.14
* Time: 13:40
* To change this template use File | Settings | File Templates.
*/
public class NewVisitPage {
@FindBy(id="addVisitForm")
private WebElement addVisitForm;
@FindBy(id="addVisitForm:petName")
private WebElement petName;
@FindBy(id="addVisitForm:petBirthDate")
private WebElement petBirthDate;
@FindBy(id="addVisitForm:petType")
private WebElement petType;
@FindBy(id="addVisitForm:ownerFirstName")
private WebElement ownerFirstName;
@FindBy(id="addVisitForm:ownerLastName")
private WebElement ownerLastName;
@FindBy(id="addVisitForm:visitDate")
private RichFacesCalendar visitDate;
@FindBy(id="addVisitForm:visitDescription")
private WebElement visitDescription;
@FindBy(id="addVisitForm:save")
private WebElement save;
public void assertPageIsLoaded() {
Assert.assertTrue(addVisitForm.isDisplayed());
}
public void assertOwnerContent(String firstName, String lastName) {
Assert.assertEquals(firstName,ownerFirstName.getText());
Assert.assertEquals(lastName,ownerLastName.getText());
}
public void assertPetContent(String petName, Date birthDate, String petType) {
Assert.assertEquals(petName,this.petName.getText());
Assert.assertEquals(petType,this.petType.getText());
Date birthDateTmp = new DateTime(birthDate.getTime()).minusDays(1).toDate();
Assert.assertEquals(DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ENGLISH).format(birthDateTmp),petBirthDate.getText());
}
public void setNewContent(Date visitDate, String description) {
DateTime dateTime = new DateTime(visitDate.getTime());
Graphene.waitModel().until().element(addVisitForm).is().visible();
this.visitDescription.sendKeys(description);
this.visitDate.setDate(dateTime);
Graphene.guardHttp(save).click();
}
}
| 2,348 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
ShowOwnerPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/ShowOwnerPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.jboss.arquillian.graphene.Graphene;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 27.01.14
* Time: 09:23
* To change this template use File | Settings | File Templates.
*/
public class ShowOwnerPage {
@FindBy(id="showOwnerForm")
private WebElement showOwnerForm;
@FindBy(id="showOwnerForm:firstName")
private WebElement firstName;
@FindBy(id="showOwnerForm:lastName")
private WebElement lastName;
@FindBy(id="showOwnerForm:address")
private WebElement address;
@FindBy(id="showOwnerForm:city")
private WebElement city;
@FindBy(id="showOwnerForm:telephone")
private WebElement telephone;
@FindBy(id="showOwnerForm:edit")
private WebElement edit;
@FindBy(id="showOwnerForm:addPet")
private WebElement addPet;
@FindBy(id="showOwnerForm:petsAndVisitsTable:0:visitsTable:editPet")
private WebElement editFirstPet;
@FindBy(id="showOwnerForm:petsAndVisitsTable:0:visitsTable:addVisit")
private WebElement newVisitForFirstPet;
@FindBy(id="showOwnerForm:petsAndVisitsTable:0:petsName")
private WebElement firstPetsName;
@FindBy(id="showOwnerForm:petsAndVisitsTable:0:petsBirthDate")
private WebElement firstPetsBirthDate;
@FindBy(id="showOwnerForm:petsAndVisitsTable:0:petsType")
private WebElement firstPetsType;
@FindBy(id="showOwnerForm:petsAndVisitsTable:1:petsName")
private WebElement secondPetsName;
@FindBy(id="showOwnerForm:petsAndVisitsTable:1:petsBirthDate")
private WebElement secondPetsBirthDate;
@FindBy(id="showOwnerForm:petsAndVisitsTable:1:petsType")
private WebElement secondPetsType;
@FindBy(id="showOwnerForm:petsAndVisitsTable:0:visitsTable:0:date")
private WebElement firstPetsFirstVisitDate;
@FindBy(id="showOwnerForm:petsAndVisitsTable:0:visitsTable:0:description")
private WebElement firstPetsFirstVisitDescription;
public void assertPageIsLoaded() {
Graphene.waitModel().until().element(showOwnerForm).is().visible();
Assert.assertTrue(showOwnerForm.isDisplayed());
}
public void clickEditOwner() {
Graphene.guardHttp(edit).click();
}
public void assertContent(String firstName,
String lastName,
String address,
String city,
String telephone) {
Assert.assertEquals(firstName,this.firstName.getText());
Assert.assertEquals(lastName,this.lastName.getText());
Assert.assertEquals(address,this.address.getText());
Assert.assertEquals(city,this.city.getText());
Assert.assertEquals(telephone,this.telephone.getText());
}
public void clickAddNewPet() {
Graphene.guardHttp(addPet).click();
}
public void clickEditFirstPet() {
Graphene.guardHttp(editFirstPet).click();
}
public void assertFirstPetContent(String petsName, Date birthDate, String petType) {
Assert.assertEquals(petsName,firstPetsName.getText());
Assert.assertEquals(petType,firstPetsType.getText());
Date birthDateTmp = new DateTime(birthDate.getTime()).minusDays(1).toDate();
Assert.assertEquals(DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ENGLISH).format(birthDateTmp),firstPetsBirthDate.getText());
}
public void assertSecondPetContent(String petsName, Date birthDate, String petType) {
Assert.assertEquals(petsName,secondPetsName.getText());
Assert.assertEquals(petType,secondPetsType.getText());
Date birthDateTmp = new DateTime(birthDate.getTime()).minusDays(1).toDate();
Assert.assertEquals(DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ENGLISH).format(birthDateTmp),secondPetsBirthDate.getText());
}
public void addVisitToFirstPet() {
Graphene.guardHttp(newVisitForFirstPet).click();
}
public void assertFirstVisitToFirstPet(Date visitDate, String description) {
Date visitDateTmp = new DateTime(visitDate.getTime()).minusDays(1).toDate();
Assert.assertEquals(DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ENGLISH).format(visitDateTmp),firstPetsFirstVisitDate.getText());
Assert.assertEquals(description,firstPetsFirstVisitDescription.getText());
}
}
| 4,591 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
NewVetPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/NewVetPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.richfaces.fragment.pickList.RichFacesPickList;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 26.01.14
* Time: 20:51
* To change this template use File | Settings | File Templates.
*/
public class NewVetPage {
@FindBy(id="addNewVeterinarian")
private WebElement addNewVeterinarian;
@FindBy(id="addNewVeterinarianForm:firstName")
private WebElement firstName;
@FindBy(id="addNewVeterinarianForm:lastName")
private WebElement lastName;
@FindBy(id="addNewVeterinarianForm:save")
private WebElement save;
@FindBy(id="addNewVeterinarianForm:selectedSpecialtiesPickList")
private RichFacesPickList pickList;
public void assertPageIsLoaded() {
Assert.assertTrue(addNewVeterinarian.isDisplayed());
}
public void addNewContent(String firstName,String lastName) {
this.firstName.clear();
this.firstName.sendKeys(firstName);
this.lastName.clear();
this.lastName.sendKeys(lastName);
save.click();
}
public void addNewContentWithAllSpecialties(String firstName, String lastName) {
this.firstName.clear();
this.firstName.sendKeys(firstName);
this.lastName.clear();
this.lastName.sendKeys(lastName);
this.pickList.addAll();
save.click();
}
public void addNewContentWithOneSpecialty(String firstName, String lastName, String specialty) {
this.firstName.clear();
this.firstName.sendKeys(firstName);
this.lastName.clear();
this.lastName.sendKeys(lastName);
this.pickList.add(specialty);
save.click();
}
}
| 1,793 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
NewSpecialtiesPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/NewSpecialtiesPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 26.01.14
* Time: 17:46
* To change this template use File | Settings | File Templates.
*/
public class NewSpecialtiesPage {
@FindBy(id="addNewSpecialty")
private WebElement addNewSpecialty;
@FindBy(id="addNewSpecialtyForm:name")
private WebElement name;
@FindBy(id="addNewSpecialtyForm:save")
private WebElement save;
public void assertPageIsLoaded(){
Assert.assertTrue(addNewSpecialty.isDisplayed());
}
public void addNewContent(String content) {
name.clear();
name.sendKeys(content);
save.click();
}
}
| 798 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
NewOwnerPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/NewOwnerPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.jboss.arquillian.graphene.Graphene;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 26.01.14
* Time: 22:48
* To change this template use File | Settings | File Templates.
*/
public class NewOwnerPage {
@FindBy(id="addNewOwner")
private WebElement addNewOwner;
@FindBy(id="addNewOwnerForm:firstName")
private WebElement firstName;
@FindBy(id="addNewOwnerForm:lastName")
private WebElement lastName;
@FindBy(id="addNewOwnerForm:address")
private WebElement address;
@FindBy(id="addNewOwnerForm:city")
private WebElement city;
@FindBy(id="addNewOwnerForm:telephone")
private WebElement telephone;
@FindBy(id="addNewOwnerForm:save")
private WebElement save;
public void assertPageIsLoaded() {
Graphene.waitModel().until().element(addNewOwner).is().visible();
Assert.assertTrue(addNewOwner.isDisplayed());
}
public void addNewContent(String firstName,
String lastName,
String address,
String city,
String telephone) {
this.firstName.sendKeys(firstName);
this.lastName.sendKeys(lastName);
this.address.sendKeys(address);
this.city.sendKeys(city);
this.telephone.sendKeys(telephone);
Graphene.guardHttp(this.save).click();
}
}
| 1,565 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
EditPetPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/EditPetPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.richfaces.fragment.calendar.RichFacesCalendar;
import java.util.Date;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 27.01.14
* Time: 19:58
* To change this template use File | Settings | File Templates.
*/
public class EditPetPage {
@FindBy(id="editPetForm")
private WebElement editPetForm;
@FindBy(id="editPetForm:petName")
private WebElement petName;
@FindBy(id="editPetForm:petBirthDate")
private RichFacesCalendar petBirthDate;
@FindBy(id="editPetForm:petType")
private WebElement petType;
@FindBy(id="editPetForm:save")
private WebElement save;
public void assertPageIsLoaded() {
Assert.assertTrue(editPetForm.isDisplayed());
}
public void setContent(String petName, Date petBirthDate, String petType) {
this.petName.clear();
this.petName.sendKeys(petName);
DateTime dateTime = new DateTime(petBirthDate.getTime());
this.petBirthDate.setDate(dateTime);
List<WebElement> options = this.petType.findElements(By.tagName("option"));
for(WebElement option: options){
if(option.getText().contentEquals(petType)){
option.click();
break;
}
}
save.click();
}
}
| 1,517 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
OwnersPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/OwnersPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.jboss.arquillian.graphene.Graphene;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 26.01.14
* Time: 22:24
* To change this template use File | Settings | File Templates.
*/
public class OwnersPage {
@FindBy(id="owners")
private WebElement owners;
@FindBy(id="ownersForm:getNewOwnerForm")
private WebElement getNewOwnerForm;
@FindBy(id="ownersForm:ownersTable:0:firstName")
private WebElement firstName;
@FindBy(id="ownersForm:ownersTable:0:lastName")
private WebElement lastName;
@FindBy(id="ownersForm:ownersTable:0:address")
private WebElement address;
@FindBy(id="ownersForm:ownersTable:0:city")
private WebElement city;
@FindBy(id="ownersForm:ownersTable:0:telephone")
private WebElement telephone;
@FindBy(id="ownersForm:ownersTable:0:showOwner")
private WebElement showOwner;
public void assertPageIsLoaded() {
Graphene.waitModel().until().element(owners).is().visible();
Assert.assertTrue(owners.isDisplayed());
}
public void clickNewOwner() {
Graphene.guardHttp(getNewOwnerForm).click();
}
public void assertNewContentFound(String firstName,
String lastName,
String address,
String city,
String telephone) {
Assert.assertEquals(firstName,this.firstName.getText());
Assert.assertEquals(lastName,this.lastName.getText());
Assert.assertEquals(address,this.address.getText());
Assert.assertEquals(city,this.city.getText());
Assert.assertEquals(telephone,this.telephone.getText());
Assert.assertTrue(showOwner.isDisplayed());
}
public void clickShowOwner() {
Graphene.guardHttp(showOwner).click();
}
}
| 2,026 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
SpecialtiesPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/SpecialtiesPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.jboss.arquillian.graphene.Graphene;
import org.jboss.arquillian.graphene.page.Location;
import org.junit.Assert;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 26.01.14
* Time: 17:23
* To change this template use File | Settings | File Templates.
*/
@Location("specialties.jsf")
public class SpecialtiesPage {
@FindBy(id="specialties")
private WebElement specialties;
@FindBy(id="specialtiesForm:addNewSpecialty")
private WebElement addNewSpecialty;
@FindBy(id="specialtiesForm:specialtiesTable:5:name")
private WebElement name5InTable;
@FindBy(id="specialtiesForm:specialtiesTable:0:name")
private WebElement nameInTable;
@FindBy(id="specialtiesForm:specialtiesTable:0:edit")
private WebElement editInTable;
@FindBy(id="specialtiesForm:specialtiesTable:0:delete")
private WebElement deleteInTable;
@FindBy(id="specialtiesForm:scroller_ds_next")
private WebElement scrollerNext;
@FindBy(id="specialtiesForm:scroller_ds_prev")
private WebElement scrollerPrev;
@FindBy(id="specialtiesForm:specialtiesTable:colNameSort")
private WebElement colNameSort;
public void assertPageIsLoaded(){
Assert.assertTrue(specialties.isDisplayed());
}
public void clickAddNewSpecialty(){
addNewSpecialty.click();
}
public void assertNewContentFound(String content) {
Assert.assertEquals(content, nameInTable.getText());
}
public void clickEditSpecialty() {
editInTable.click();
}
public void assertEditedContentFound(String content) {
Assert.assertEquals(content, nameInTable.getText());
}
public void clickDeleteSpecialty() {
deleteInTable.click();
}
public void assertDeletedContentNotFound() {
boolean isDeleted = false;
try {
Assert.assertEquals(null,nameInTable);
} catch (NoSuchElementException elementException) {
isDeleted = true;
}
Assert.assertTrue(isDeleted);
}
public void assertPagerNextIsLoaded(){
Graphene.waitModel().until().element(scrollerNext).is().visible();
Assert.assertTrue(scrollerNext.isDisplayed());
}
public void assertPagerPrevIsLoaded(){
Graphene.waitModel().until().element(scrollerPrev).is().visible();
Assert.assertTrue(scrollerPrev.isDisplayed());
}
public void clickPagerNext() {
scrollerNext.click();
}
public void clickPagerPrev() {
scrollerPrev.click();
}
public void assertSorterIsLoaded(){
Graphene.waitModel().until().element(colNameSort).is().visible();
Assert.assertTrue(colNameSort.isDisplayed());
}
public void assertOrder() {
Graphene.waitModel().until().element(nameInTable).is().visible();
Assert.assertTrue(nameInTable.getText().compareTo("specialty01")==0);
}
public void clickSorter() {
Graphene.waitModel().until().element(colNameSort).is().visible();
colNameSort.click();
}
public void assertReverseOrder() {
Graphene.waitModel().until().element(name5InTable).is().visible();
Assert.assertTrue(name5InTable.getText().compareTo("specialty06")==0);
}
}
| 3,432 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
EditOwnerPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/EditOwnerPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.jboss.arquillian.graphene.Graphene;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 27.01.14
* Time: 09:27
* To change this template use File | Settings | File Templates.
*/
public class EditOwnerPage {
@FindBy(id="editOwnerForm")
private WebElement editOwnerForm;
@FindBy(id="editOwnerForm:firstName")
private WebElement firstName;
@FindBy(id="editOwnerForm:lastName")
private WebElement lastName;
@FindBy(id="editOwnerForm:address")
private WebElement address;
@FindBy(id="editOwnerForm:city")
private WebElement city;
@FindBy(id="editOwnerForm:telephone")
private WebElement telephone;
@FindBy(id="editOwnerForm:save")
private WebElement save;
public void assertPageIsLoaded() {
Graphene.waitModel().until().element(editOwnerForm).is().visible();
Assert.assertTrue(editOwnerForm.isDisplayed());
}
public void editContent(String firstName,
String lastName,
String address,
String city,
String telephone) {
this.firstName.clear();
this.lastName.clear();
this.address.clear();
this.city.clear();
this.telephone.clear();
this.firstName.sendKeys(firstName);
this.lastName.sendKeys(lastName);
this.address.sendKeys(address);
this.city.sendKeys(city);
this.telephone.sendKeys(telephone);
Graphene.guardHttp(this.save).click();
}
}
| 1,704 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
FindOwnersPage.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/test/java/org/woehlke/javaee7/petclinic/web/pages/FindOwnersPage.java | package org.woehlke.javaee7.petclinic.web.pages;
import org.jboss.arquillian.graphene.Graphene;
import org.jboss.arquillian.graphene.page.Location;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 26.01.14
* Time: 22:12
* To change this template use File | Settings | File Templates.
*/
@Location("findOwners.jsf")
public class FindOwnersPage {
@FindBy(id="findOwners")
private WebElement findOwners;
@FindBy(id="findOwnersForm:search")
private WebElement search;
@FindBy(id="findOwnersForm:getNewOwnerForm")
private WebElement getNewOwnerForm;
public void assertPageIsLoaded() {
Graphene.waitModel().until().element(findOwners).is().visible();
Assert.assertTrue(findOwners.isDisplayed());
}
public void clickSearch() {
Graphene.guardHttp(search).click();
}
public void clickNewOwner() {
Graphene.guardHttp(getNewOwnerForm).click();
}
}
| 1,042 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
VetDaoImpl.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/dao/VetDaoImpl.java | package org.woehlke.javaee7.petclinic.dao;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.woehlke.javaee7.petclinic.entities.Vet;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
import java.util.logging.Logger;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 02.01.14
* Time: 08:30
* To change this template use File | Settings | File Templates.
*/
@Stateless
public class VetDaoImpl implements VetDao {
private static Logger log = Logger.getLogger(VetDaoImpl.class.getName());
@PersistenceContext(unitName="javaee7petclinic")
private EntityManager entityManager;
@Override
public List<Vet> getAll(){
TypedQuery<Vet> q = entityManager.createQuery("select v from Vet v order by v.lastName,v.firstName", Vet.class);
List<Vet> list = q.getResultList();
return list;
}
@Override
public void delete(long id) {
Vet vet = entityManager.find(Vet.class, id);
entityManager.remove(vet);
}
@Override
public void addNew(Vet vet) {
log.info("addNewVet: "+vet.toString());
entityManager.persist(vet);
}
@Override
public Vet findById(long id) {
Vet vet = entityManager.find(Vet.class, id);
return vet;
}
@Override
public void update(Vet vet) {
entityManager.merge(vet);
}
@Override
public List<Vet> search(String searchterm){
FullTextEntityManager fullTextEntityManager =
org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);
QueryBuilder qb = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder().forEntity( Vet.class ).get();
org.apache.lucene.search.Query query = qb
.keyword()
.onFields("firstName", "lastName")
.matching(searchterm)
.createQuery();
// wrap Lucene query in a javax.persistence.Query
javax.persistence.Query persistenceQuery =
fullTextEntityManager.createFullTextQuery(query, Vet.class);
// execute search
@SuppressWarnings("unchecked")
List<Vet> result = persistenceQuery.getResultList();
return result;
}
}
| 2,404 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
PetDaoImpl.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/dao/PetDaoImpl.java | package org.woehlke.javaee7.petclinic.dao;
import org.woehlke.javaee7.petclinic.entities.Pet;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.logging.Logger;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 06.01.14
* Time: 20:34
* To change this template use File | Settings | File Templates.
*/
@Stateless
public class PetDaoImpl implements PetDao {
private static Logger log = Logger.getLogger(PetDaoImpl.class.getName());
@PersistenceContext(unitName="javaee7petclinic")
private EntityManager entityManager;
@Override
public void addNew(Pet pet) {
log.info("addNewPet: "+pet.toString());
entityManager.persist(pet);
}
@Override
public Pet findById(long petId) {
return entityManager.find(Pet.class, petId);
}
@Override
public void update(Pet pet) {
log.info("updatePet: "+pet.toString());
pet=entityManager.merge(pet);
}
}
| 1,016 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
SpecialtyDaoImpl.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/dao/SpecialtyDaoImpl.java | package org.woehlke.javaee7.petclinic.dao;
import org.woehlke.javaee7.petclinic.entities.Specialty;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
import java.util.logging.Logger;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 04.01.14
* Time: 12:03
* To change this template use File | Settings | File Templates.
*/
@Stateless
public class SpecialtyDaoImpl implements SpecialtyDao {
private static Logger log = Logger.getLogger(SpecialtyDaoImpl.class.getName());
@PersistenceContext(unitName="javaee7petclinic")
private EntityManager entityManager;
@Override
public List<Specialty> getAll() {
TypedQuery<Specialty> q = entityManager.createQuery("select s from Specialty s order by s.name",Specialty.class);
List<Specialty> list = q.getResultList();
return list;
}
@Override
public void delete(long id) {
Specialty specialty = entityManager.find(Specialty.class, id);
entityManager.remove(specialty);
}
@Override
public void addNew(Specialty specialty) {
log.info("addNewSpecialty: "+specialty.toString());
entityManager.persist(specialty);
}
@Override
public Specialty findById(long id) {
Specialty specialty = entityManager.find(Specialty.class, id);
return specialty;
}
@Override
public void update(Specialty specialty) {
entityManager.merge(specialty);
}
}
| 1,562 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
VisitDao.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/dao/VisitDao.java | package org.woehlke.javaee7.petclinic.dao;
import org.woehlke.javaee7.petclinic.entities.Visit;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 07.01.14
* Time: 12:43
* To change this template use File | Settings | File Templates.
*/
public interface VisitDao {
void addNew(Visit visit);
void update(Visit visit);
}
| 339 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
PetTypeDao.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/dao/PetTypeDao.java | package org.woehlke.javaee7.petclinic.dao;
import org.woehlke.javaee7.petclinic.entities.PetType;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: Fert
* Date: 06.01.14
* Time: 11:51
* To change this template use File | Settings | File Templates.
*/
public interface PetTypeDao {
List<PetType> getAll();
void delete(long id);
void addNew(PetType petType);
PetType findById(long id);
void update(PetType petType);
}
| 466 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
OwnerDao.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/dao/OwnerDao.java | package org.woehlke.javaee7.petclinic.dao;
import org.woehlke.javaee7.petclinic.entities.Owner;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 06.01.14
* Time: 09:38
* To change this template use File | Settings | File Templates.
*/
public interface OwnerDao {
List<Owner> getAll();
void delete(long id);
void addNew(Owner owner);
Owner findById(long id);
void update(Owner owner);
List<Owner> search(String searchterm);
}
| 492 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
VetDao.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/dao/VetDao.java | package org.woehlke.javaee7.petclinic.dao;
import org.woehlke.javaee7.petclinic.entities.Vet;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 02.01.14
* Time: 08:37
* To change this template use File | Settings | File Templates.
*/
public interface VetDao {
List<Vet> getAll();
void delete(long id);
void addNew(Vet vet);
Vet findById(long id);
void update(Vet vet);
List<Vet> search(String searchterm);
}
| 473 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
VisitDaoImpl.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/dao/VisitDaoImpl.java | package org.woehlke.javaee7.petclinic.dao;
import org.woehlke.javaee7.petclinic.entities.Visit;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.logging.Logger;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 07.01.14
* Time: 12:43
* To change this template use File | Settings | File Templates.
*/
@Stateless
public class VisitDaoImpl implements VisitDao {
private static Logger log = Logger.getLogger(VisitDaoImpl.class.getName());
@PersistenceContext(unitName="javaee7petclinic")
private EntityManager entityManager;
@Override
public void addNew(Visit visit) {
log.info("addNewVisit: "+visit.toString());
entityManager.persist(visit);
}
@Override
public void update(Visit visit) {
visit= entityManager.merge(visit);
}
}
| 882 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
PetTypeDaoImpl.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/dao/PetTypeDaoImpl.java | package org.woehlke.javaee7.petclinic.dao;
import org.woehlke.javaee7.petclinic.entities.PetType;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
import java.util.logging.Logger;
/**
* Created with IntelliJ IDEA.
* User: Fert
* Date: 06.01.14
* Time: 11:51
* To change this template use File | Settings | File Templates.
*/
@Stateless
public class PetTypeDaoImpl implements PetTypeDao {
private static Logger log = Logger.getLogger(PetTypeDaoImpl.class.getName());
@PersistenceContext(unitName="javaee7petclinic")
private EntityManager entityManager;
@Override
public List<PetType> getAll() {
TypedQuery<PetType> q = entityManager.createQuery("select pt from PetType pt order by pt.name",PetType.class);
List<PetType> list = q.getResultList();
return list;
}
@Override
public void delete(long id) {
PetType petType = entityManager.find(PetType.class, id);
entityManager.remove(petType);
}
@Override
public void addNew(PetType petType) {
log.info("addNewPetType: "+petType.toString());
entityManager.persist(petType);
}
@Override
public PetType findById(long id) {
PetType petType = entityManager.find(PetType.class, id);
return petType;
}
@Override
public void update(PetType petType) {
entityManager.merge(petType);
}
}
| 1,516 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
PetDao.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/dao/PetDao.java | package org.woehlke.javaee7.petclinic.dao;
import org.woehlke.javaee7.petclinic.entities.Pet;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 06.01.14
* Time: 20:34
* To change this template use File | Settings | File Templates.
*/
public interface PetDao {
void addNew(Pet pet);
Pet findById(long petId);
void update(Pet pet);
}
| 358 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
OwnerDaoImpl.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/dao/OwnerDaoImpl.java | package org.woehlke.javaee7.petclinic.dao;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.woehlke.javaee7.petclinic.entities.Owner;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
import java.util.logging.Logger;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 06.01.14
* Time: 09:38
* To change this template use File | Settings | File Templates.
*/
@Stateless
public class OwnerDaoImpl implements OwnerDao {
private static Logger log = Logger.getLogger(OwnerDaoImpl.class.getName());
@PersistenceContext(unitName="javaee7petclinic")
private EntityManager entityManager;
@Override
public List<Owner> getAll() {
TypedQuery<Owner> q = entityManager.createQuery("select o from Owner o order by o.lastName,o.firstName", Owner.class);
List<Owner> list = q.getResultList();
return list;
}
@Override
public void delete(long id) {
Owner owner = entityManager.find(Owner.class, id);
entityManager.remove(owner);
}
@Override
public void addNew(Owner owner) {
log.info("addNewOwner: "+owner.toString());
entityManager.persist(owner);
}
@Override
public Owner findById(long id) {
return entityManager.find(Owner.class, id);
}
@Override
public void update(Owner owner) {
log.info("updateOwner: "+owner.toString());
owner=entityManager.merge(owner);
}
@Override
public List<Owner> search(String searchterm) {
FullTextEntityManager fullTextEntityManager =
org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);
QueryBuilder qb = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder().forEntity( Owner.class ).get();
org.apache.lucene.search.Query query = qb
.keyword()
.onFields("firstName", "lastName", "city", "pets.name")
.matching(searchterm)
.createQuery();
// wrap Lucene query in a javax.persistence.Query
javax.persistence.Query persistenceQuery =
fullTextEntityManager.createFullTextQuery(query, Owner.class);
// execute search
@SuppressWarnings("unchecked")
List<Owner> result = persistenceQuery.getResultList();
return result;
}
}
| 2,518 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
SpecialtyDao.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/dao/SpecialtyDao.java | package org.woehlke.javaee7.petclinic.dao;
import org.woehlke.javaee7.petclinic.entities.Specialty;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 04.01.14
* Time: 12:02
* To change this template use File | Settings | File Templates.
*/
public interface SpecialtyDao {
List<Specialty> getAll();
void delete(long id);
void addNew(Specialty vet);
Specialty findById(long id);
void update(Specialty vet);
}
| 467 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Owner.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/entities/Owner.java | package org.woehlke.javaee7.petclinic.entities;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.IndexedEmbedded;
import org.hibernate.search.annotations.Store;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.GeneratedValue;
import javax.validation.constraints.Digits;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 01.01.14
* Time: 21:08
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name = "owners")
@Indexed
public class Owner {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "first_name")
@NotEmpty
@Field(index= Index.YES, analyze= Analyze.YES, store= Store.NO)
private String firstName;
@Column(name = "last_name")
@NotEmpty
@Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String lastName;
@Column(name = "address")
@NotEmpty
@Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String address;
@Column(name = "city")
@NotEmpty
@Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String city;
@Column(name = "telephone")
@NotEmpty
@Digits(fraction = 0, integer = 10)
private String telephone;
@IndexedEmbedded
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner",fetch = FetchType.EAGER)
private Set<Pet> pets = new TreeSet<Pet>();
public void addPet(Pet pet){
pets.add(pet);
pet.setOwner(this);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public List<Pet> getPets() {
List<Pet> list = new ArrayList<>();
for(Pet pet:pets){
list.add(pet);
}
Collections.sort(list);
return list;
}
public void setPets(Set<Pet> pets) {
this.pets = pets;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Owner)) return false;
Owner owner = (Owner) o;
if (address != null ? !address.equals(owner.address) : owner.address != null) return false;
if (city != null ? !city.equals(owner.city) : owner.city != null) return false;
if (firstName != null ? !firstName.equals(owner.firstName) : owner.firstName != null) return false;
if (id != null ? !id.equals(owner.id) : owner.id != null) return false;
if (lastName != null ? !lastName.equals(owner.lastName) : owner.lastName != null) return false;
if (pets != null ? !pets.equals(owner.pets) : owner.pets != null) return false;
if (telephone != null ? !telephone.equals(owner.telephone) : owner.telephone != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
result = 31 * result + (address != null ? address.hashCode() : 0);
result = 31 * result + (city != null ? city.hashCode() : 0);
result = 31 * result + (telephone != null ? telephone.hashCode() : 0);
result = 31 * result + (pets != null ? pets.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Owner{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", address='" + address + '\'' +
", city='" + city + '\'' +
", telephone='" + telephone + '\'' +
", pets=" + pets +
'}';
}
}
| 5,003 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Visit.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/entities/Visit.java | package org.woehlke.javaee7.petclinic.entities;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 01.01.14
* Time: 21:10
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name = "visits")
public class Visit implements Comparable<Visit> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Column(name = "visit_date")
@Temporal( TemporalType.DATE )
private Date date;
@NotEmpty
@Column(name = "description")
private String description;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "pet_id")
private Pet pet;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Pet getPet() {
return pet;
}
public void setPet(Pet pet) {
this.pet = pet;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Visit)) return false;
Visit visit = (Visit) o;
if (date != null ? !date.equals(visit.date) : visit.date != null) return false;
if (description != null ? !description.equals(visit.description) : visit.description != null) return false;
if (id != null ? !id.equals(visit.id) : visit.id != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (date != null ? date.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Visit{" +
"id=" + id +
", date=" + date +
", description='" + description + '\'' +
'}';
}
@Override
public int compareTo(Visit o) {
return date.compareTo(o.getDate());
}
}
| 2,409 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Specialty.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/entities/Specialty.java | package org.woehlke.javaee7.petclinic.entities;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 01.01.14
* Time: 21:11
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name = "specialties")
public class Specialty implements Comparable<Specialty> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotEmpty
@Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Specialty other) {
return this.name.compareTo(other.getName());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Specialty)) return false;
Specialty specialty = (Specialty) o;
if (id != null ? !id.equals(specialty.id) : specialty.id != null) return false;
if (name != null ? !name.equals(specialty.name) : specialty.name != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Specialty{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
| 1,651 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Pet.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/entities/Pet.java | package org.woehlke.javaee7.petclinic.entities;
import org.hibernate.search.annotations.Field;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 01.01.14
* Time: 21:09
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name = "pets")
public class Pet implements Comparable<Pet> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotEmpty
@Field
@Column(name = "name")
private String name;
@NotNull
@Column(name = "birth_date")
@Temporal( TemporalType.DATE )
private Date birthDate;
@NotNull
@ManyToOne
@JoinColumn(name = "type_id")
private PetType type;
@NotNull
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "owner_id")
private Owner owner;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "pet", fetch = FetchType.EAGER)
private Set<Visit> visits = new HashSet<Visit>();
public void addVisit(Visit visit) {
visits.add(visit);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public PetType getType() {
return type;
}
public void setType(PetType type) {
this.type = type;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public List<Visit> getVisits() {
List<Visit> list = new ArrayList<>();
for(Visit visit:visits){
list.add(visit);
}
Collections.sort(list);
return list;
}
public void setVisits(Set<Visit> visits) {
this.visits = visits;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pet)) return false;
Pet pet = (Pet) o;
if (birthDate != null ? !birthDate.equals(pet.birthDate) : pet.birthDate != null) return false;
if (id != null ? !id.equals(pet.id) : pet.id != null) return false;
if (name != null ? !name.equals(pet.name) : pet.name != null) return false;
if (type != null ? !type.equals(pet.type) : pet.type != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (birthDate != null ? birthDate.hashCode() : 0);
result = 31 * result + (type != null ? type.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Pet{" +
"id=" + id +
", name='" + name + '\'' +
", birthDate=" + birthDate +
", type=" + type +
", visits=" + visits +
'}';
}
@Override
public int compareTo(Pet o) {
return name.compareTo(o.getName());
}
}
| 3,394 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
PetType.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/entities/PetType.java | package org.woehlke.javaee7.petclinic.entities;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 01.01.14
* Time: 21:12
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name = "types")
public class PetType {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotEmpty
@Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "PetType{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
| 903 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Vet.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/entities/Vet.java | package org.woehlke.javaee7.petclinic.entities;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.JoinColumn;
import javax.xml.bind.annotation.XmlElement;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 01.01.14
* Time: 21:10
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name = "vets")
@Indexed
public class Vet {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "first_name")
@NotEmpty
@Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String firstName;
@Column(name = "last_name")
@NotEmpty
@Field(index= Index.YES, analyze= Analyze.YES, store= Store.NO)
private String lastName;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "vet_specialties",
joinColumns = @JoinColumn(name = "vet_id"),
inverseJoinColumns = @JoinColumn(name = "specialty_id"))
private java.util.Set<Specialty> specialties;
protected Set<Specialty> getSpecialtiesInternal() {
if (this.specialties == null) {
this.specialties = new HashSet<Specialty>();
}
return this.specialties;
}
@XmlElement
public List<Specialty> getSpecialties() {
List<Specialty> list = new ArrayList<Specialty>();
for(Specialty s : getSpecialtiesInternal()){
list.add(s);
}
Collections.sort(list);
return list;
}
public String getSpecialtiesAsString(){
StringBuilder stringBuilder = new StringBuilder();
if(getNrOfSpecialties()==0){
stringBuilder.append("none");
} else {
for(Specialty specialty : getSpecialties()){
stringBuilder.append(specialty.getName());
stringBuilder.append(" ");
}
}
return stringBuilder.toString();
}
public int getNrOfSpecialties() {
return getSpecialtiesInternal().size();
}
public void addSpecialty(Specialty specialty) {
getSpecialtiesInternal().add(specialty);
}
public void removeSpecialties(){
this.specialties = new HashSet<Specialty>();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setSpecialties(Set<Specialty> specialties) {
this.specialties = specialties;
}
@Override
public String toString() {
return "Vet{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", specialties=" + specialties +
'}';
}
}
| 3,616 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
JaxRsActivator.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/services/JaxRsActivator.java | package org.woehlke.javaee7.petclinic.services;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 05.01.14
* Time: 09:27
* To change this template use File | Settings | File Templates.
*/
@ApplicationPath("/rest")
public class JaxRsActivator extends Application {
}
| 350 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
OwnerServiceImpl.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/services/OwnerServiceImpl.java | package org.woehlke.javaee7.petclinic.services;
import org.woehlke.javaee7.petclinic.dao.OwnerDao;
import org.woehlke.javaee7.petclinic.dao.PetDao;
import org.woehlke.javaee7.petclinic.dao.VisitDao;
import org.woehlke.javaee7.petclinic.entities.Visit;
import javax.ejb.EJB;
import javax.ejb.Stateless;
/**
* Created by tw on 10.03.14.
*/
@Stateless
public class OwnerServiceImpl implements OwnerService {
@EJB
private OwnerDao ownerDao;
@EJB
private PetDao petDao;
@EJB
private VisitDao visitDao;
@Override
public void addNewVisit(Visit visit) {
visitDao.addNew(visit);
petDao.update(visit.getPet());
ownerDao.update(visit.getPet().getOwner());
}
}
| 719 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
OwnerService.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/services/OwnerService.java | package org.woehlke.javaee7.petclinic.services;
import org.woehlke.javaee7.petclinic.entities.Visit;
/**
* Created by tw on 10.03.14.
*/
public interface OwnerService {
void addNewVisit(Visit visit);
}
| 211 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
VetWebservice.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/services/VetWebservice.java | package org.woehlke.javaee7.petclinic.services;
import org.woehlke.javaee7.petclinic.dao.VetDao;
import org.woehlke.javaee7.petclinic.entities.Specialty;
import org.woehlke.javaee7.petclinic.entities.Vet;
import org.woehlke.javaee7.petclinic.model.Vets;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 05.01.14
* Time: 09:27
* To change this template use File | Settings | File Templates.
*/
@Stateless
@Path("/vets")
public class VetWebservice {
@EJB
private VetDao vetDao;
@GET
@Produces("application/xml")
@Path("/xml")
public Vets getXml(){
Vets vets = new Vets();
vets.setVetList(vetDao.getAll());
return vets;
}
@GET
@Produces("application/json")
@Path("/json")
public Vets getJson(){
Vets vets = new Vets();
vets.setVetList(vetDao.getAll());
return vets;
}
}
| 1,008 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
OwnerController.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/web/OwnerController.java | package org.woehlke.javaee7.petclinic.web;
import org.woehlke.javaee7.petclinic.dao.OwnerDao;
import org.woehlke.javaee7.petclinic.dao.PetDao;
import org.woehlke.javaee7.petclinic.dao.PetTypeDao;
import org.woehlke.javaee7.petclinic.dao.VisitDao;
import org.woehlke.javaee7.petclinic.entities.Owner;
import org.woehlke.javaee7.petclinic.entities.Pet;
import org.woehlke.javaee7.petclinic.entities.PetType;
import org.woehlke.javaee7.petclinic.entities.Visit;
import org.woehlke.javaee7.petclinic.services.OwnerService;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Logger;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 06.01.14
* Time: 16:24
* To change this template use File | Settings | File Templates.
*/
@ManagedBean
@SessionScoped
public class OwnerController implements Serializable {
private static Logger log = Logger.getLogger(OwnerController.class.getName());
@EJB
private OwnerDao ownerDao;
@EJB
private PetDao petDao;
@EJB
private PetTypeDao petTypeDao;
@EJB
private VisitDao visitDao;
@EJB
private OwnerService ownerService;
private String searchterm;
private List<Owner> ownerList;
private Owner owner;
private Pet pet;
private long petTypeId;
private Visit visit;
private int scrollerPage;
public Visit getVisit() {
return visit;
}
public void setVisit(Visit visit) {
this.visit = visit;
}
public long getPetTypeId() {
return petTypeId;
}
public void setPetTypeId(long petTypeId) {
this.petTypeId = petTypeId;
}
public Pet getPet() {
return pet;
}
public void setPet(Pet pet) {
this.pet = pet;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public List<Owner> getOwnerList() {
return ownerList;
}
public void setOwnerList(List<Owner> ownerList) {
this.ownerList = ownerList;
}
public String getSearchterm() {
return searchterm;
}
public void setSearchterm(String searchterm) {
this.searchterm = searchterm;
}
public String search(){
if(searchterm==null || searchterm.isEmpty()){
this.ownerList = ownerDao.getAll();
} else {
try {
this.ownerList = ownerDao.search(searchterm);
} catch (Exception e){
this.ownerList = ownerDao.getAll();
}
}
return "ownerList.jsf";
}
public String getNewOwnerForm(){
this.owner = new Owner();
return "ownerNew.jsf";
}
public String saveNewOwner(){
ownerDao.addNew(this.owner);
this.ownerList = ownerDao.getAll();
return "ownerList.jsf";
}
public String showOwner(long id){
this.owner = ownerDao.findById(id);
return "ownerShow.jsf";
}
public String getEditForm(){
return "ownerEdit.jsf";
}
public String saveEditedOwner(){
ownerDao.update(this.owner);
this.ownerList = ownerDao.getAll();
return "ownerShow.jsf";
}
public String delete(long id){
ownerDao.delete(id);
this.ownerList = ownerDao.getAll();
return "ownerList.jsf";
}
public String getAddNewPetForm(){
this.pet = new Pet();
return "petNew.jsf";
}
public List<PetType> getAllPetTypes(){
return petTypeDao.getAll();
}
public String addNewPet(){
PetType petType = petTypeDao.findById(this.petTypeId);
this.pet.setType(petType);
this.owner.addPet(this.pet);
petDao.addNew(this.pet);
ownerDao.update(this.owner);
return "ownerShow.jsf";
}
public String editPetForm(long petId){
this.pet = petDao.findById(petId);
this.petTypeId = this.pet.getType().getId();
return "petEdit.jsf";
}
public String saveEditedPet(){
PetType petType = petTypeDao.findById(this.petTypeId);
this.pet.setType(petType);
petDao.update(this.pet);
long ownerId = this.owner.getId();
this.owner = this.ownerDao.findById(ownerId);
return "ownerShow.jsf";
}
public String addVisitToPetForm(long petId){
this.pet = petDao.findById(petId);
this.petTypeId = this.pet.getType().getId();
this.visit = new Visit();
return "petAddVisit.jsf";
}
public String saveVisit(){
this.visit.setPet(this.pet);
this.pet.addVisit(this.visit);
ownerService.addNewVisit(this.visit);
log.info("owner1: " + this.owner.toString());
long ownerId = this.owner.getId();
this.owner = this.ownerDao.findById(ownerId);
log.info("owner2: "+this.owner.toString());
return "ownerShow.jsf";
}
public void setScrollerPage(int scrollerPage) {
this.scrollerPage = scrollerPage;
}
public int getScrollerPage() {
return scrollerPage;
}
}
| 5,182 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
SpecialtyController.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/web/SpecialtyController.java | package org.woehlke.javaee7.petclinic.web;
import org.richfaces.component.SortOrder;
import org.woehlke.javaee7.petclinic.dao.SpecialtyDao;
import org.woehlke.javaee7.petclinic.entities.Specialty;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import java.io.Serializable;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 04.01.14
* Time: 12:00
* To change this template use File | Settings | File Templates.
*/
@ManagedBean
@SessionScoped
public class SpecialtyController implements Serializable {
@EJB
private SpecialtyDao specialtyDao;
private Specialty specialty;
private SortOrder specialtySortOrder=SortOrder.ascending;
@ManagedProperty(value = "#{language}")
private LanguageBean languageBean;
private int scrollerPage;
public Specialty getSpecialty() {
return specialty;
}
public void setSpecialty(Specialty specialty) {
this.specialty = specialty;
}
public LanguageBean getLanguageBean() {
return languageBean;
}
public void setLanguageBean(LanguageBean languageBean) {
this.languageBean = languageBean;
}
public List<Specialty> getSpecialties(){
return specialtyDao.getAll();
}
public String getNewSpecialtyForm(){
specialty = new Specialty();
return "specialtyNew.jsf";
}
public String saveNewSpecialty(){
specialtyDao.addNew(this.specialty);
return "specialtyList.jsf";
}
public String getEditForm(long id){
this.specialty = specialtyDao.findById(id);
return "specialtyEdit.jsf";
}
public String saveEditedSpecialty(){
specialtyDao.update(this.specialty);
return "specialtyList.jsf";
}
public String delete(long id){
try {
specialtyDao.delete(id);
} catch (EJBException e) {
FacesContext ctx = FacesContext.getCurrentInstance();
ctx.addMessage(null, new FacesMessage(languageBean.getMsgCantDeleteSpecialty()));
}
return "specialtyList.jsf";
}
public SortOrder getSpecialtySortOrder() {
return specialtySortOrder;
}
public void setSpecialtySortOrder(SortOrder specialtySortOrder) {
this.specialtySortOrder = specialtySortOrder;
}
public void switchSortOrder(){
if(specialtySortOrder==SortOrder.ascending){
specialtySortOrder=SortOrder.descending;
} else {
specialtySortOrder=SortOrder.ascending;
}
}
public void setScrollerPage(int scrollerPage) {
this.scrollerPage = scrollerPage;
}
public int getScrollerPage() {
return scrollerPage;
}
}
| 2,917 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
VetSortingBean.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/web/VetSortingBean.java | package org.woehlke.javaee7.petclinic.web;
import org.richfaces.component.SortOrder;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
/**
* Created by tw on 13.03.14.
*/
@ManagedBean
@SessionScoped
public class VetSortingBean implements Serializable {
private static final long serialVersionUID = 1L;
private SortOrder sortOrderFirstName = SortOrder.unsorted;
private SortOrder sortOrderLastName = SortOrder.unsorted;
private SortOrder sortOrderSpecialties = SortOrder.unsorted;
public void setSortOrderToFirstName() {
if (SortOrder.ascending == sortOrderFirstName) {
sortOrderFirstName = SortOrder.descending;
} else {
sortOrderFirstName = SortOrder.ascending;
}
sortOrderLastName = SortOrder.unsorted;
sortOrderSpecialties = SortOrder.unsorted;
}
public void setSortOrderToLastName() {
sortOrderFirstName = SortOrder.unsorted;
if (SortOrder.ascending==sortOrderLastName) {
sortOrderLastName = SortOrder.descending;
} else {
sortOrderLastName = SortOrder.ascending;
}
sortOrderSpecialties = SortOrder.unsorted;
}
public void setSortOrderToSpecialties() {
sortOrderFirstName = SortOrder.unsorted;
sortOrderLastName = SortOrder.unsorted;
if (SortOrder.ascending==sortOrderSpecialties) {
sortOrderSpecialties = SortOrder.descending;
} else {
sortOrderSpecialties = SortOrder.ascending;
}
}
public SortOrder getSortOrderFirstName() {
return sortOrderFirstName;
}
public void setSortOrderFirstName(SortOrder sortOrderFirstName) {
this.sortOrderFirstName = sortOrderFirstName;
}
public SortOrder getSortOrderLastName() {
return sortOrderLastName;
}
public void setSortOrderLastName(SortOrder sortOrderLastName) {
this.sortOrderLastName = sortOrderLastName;
}
public SortOrder getSortOrderSpecialties() {
return sortOrderSpecialties;
}
public void setSortOrderSpecialties(SortOrder sortOrderSpecialties) {
this.sortOrderSpecialties = sortOrderSpecialties;
}
}
| 2,256 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
LanguageBean.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/web/LanguageBean.java | package org.woehlke.javaee7.petclinic.web;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 14.01.14
* Time: 21:14
* To change this template use File | Settings | File Templates.
*/
@ManagedBean(name="language")
@SessionScoped
public class LanguageBean implements Serializable {
private static final long serialVersionUID = 1L;
private String localeCode = Locale.ENGLISH.toString();
private static Map<String,Object> countries;
static{
countries = new LinkedHashMap<String,Object>();
countries.put("English", Locale.ENGLISH);
countries.put("Deutsch", Locale.GERMAN);
}
public Map<String, Object> getCountriesInMap() {
return countries;
}
public String getLocaleCode() {
return localeCode;
}
public void setLocaleCode(String localeCode) {
this.localeCode = localeCode;
}
//value change event listener
public void countryLocaleCodeChanged(ValueChangeEvent e){
String newLocaleValue = e.getNewValue().toString();
//loop country map to compare the locale code
for (Map.Entry<String, Object> entry : countries.entrySet()) {
if(entry.getValue().toString().equals(newLocaleValue)){
FacesContext.getCurrentInstance()
.getViewRoot().setLocale((Locale)entry.getValue());
}
}
}
public String getMsgCantDeleteSpecialty() {
String msg = "";
if(localeCode.equals(Locale.ENGLISH.toString())){
msg = "cannot delete, Specialty still in use";
} else if(localeCode.equals(Locale.GERMAN.toString())){
msg = "löschen nicht möglich, Fachrichtung wird noch ausgeübt";
}
return msg;
}
}
| 2,034 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
OwnerSortingBean.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/web/OwnerSortingBean.java | package org.woehlke.javaee7.petclinic.web;
import org.richfaces.component.SortOrder;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
/**
* Created by tw on 13.03.14.
*/
@ManagedBean
@SessionScoped
public class OwnerSortingBean implements Serializable {
private SortOrder sortOrderName = SortOrder.unsorted;
private SortOrder sortOrderAddress = SortOrder.unsorted;
private SortOrder sortOrderCity = SortOrder.unsorted;
private SortOrder sortOrderTelephone = SortOrder.unsorted;
public void setSortOrderToName(){
sortOrderAddress = SortOrder.unsorted;
sortOrderCity = SortOrder.unsorted;
sortOrderTelephone = SortOrder.unsorted;
if(sortOrderName==SortOrder.ascending){
sortOrderName = SortOrder.descending;
} else {
sortOrderName = SortOrder.ascending;
}
}
public void setSortOrderToAddress(){
sortOrderName = SortOrder.unsorted;
sortOrderCity = SortOrder.unsorted;
sortOrderTelephone = SortOrder.unsorted;
if(sortOrderAddress == SortOrder.ascending){
sortOrderAddress = SortOrder.descending;
} else {
sortOrderAddress = SortOrder.ascending;
}
}
public void setSortOrderToCity(){
sortOrderName = SortOrder.unsorted;
sortOrderAddress = SortOrder.unsorted;
sortOrderTelephone = SortOrder.unsorted;
if(sortOrderCity == SortOrder.ascending){
sortOrderCity = SortOrder.descending;
} else {
sortOrderCity = SortOrder.ascending;
}
}
public void setSortOrderToTelephone(){
sortOrderName = SortOrder.unsorted;
sortOrderAddress = SortOrder.unsorted;
sortOrderCity = SortOrder.unsorted;
if(sortOrderTelephone == SortOrder.ascending){
sortOrderTelephone = SortOrder.descending;
} else {
sortOrderTelephone = SortOrder.ascending;
}
}
public SortOrder getSortOrderName() {
return sortOrderName;
}
public void setSortOrderName(SortOrder sortOrderName) {
this.sortOrderName = sortOrderName;
}
public SortOrder getSortOrderAddress() {
return sortOrderAddress;
}
public void setSortOrderAddress(SortOrder sortOrderAddress) {
this.sortOrderAddress = sortOrderAddress;
}
public SortOrder getSortOrderCity() {
return sortOrderCity;
}
public void setSortOrderCity(SortOrder sortOrderCity) {
this.sortOrderCity = sortOrderCity;
}
public SortOrder getSortOrderTelephone() {
return sortOrderTelephone;
}
public void setSortOrderTelephone(SortOrder sortOrderTelephone) {
this.sortOrderTelephone = sortOrderTelephone;
}
}
| 2,834 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
SpecialtyConverter.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/web/SpecialtyConverter.java | package org.woehlke.javaee7.petclinic.web;
import org.woehlke.javaee7.petclinic.entities.Specialty;
import javax.el.ELContext;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 04.01.14
* Time: 12:44
* To change this template use File | Settings | File Templates.
*/
@FacesConverter("SpecialtyConverter")
public class SpecialtyConverter implements Converter {
private VetController vetController;
public Object getAsObject(FacesContext facesContext, UIComponent component, String s) {
for (Specialty specialty : getCapitalsParser(facesContext).getSpecialties()) {
if (specialty.getName().equals(s)) {
return specialty;
}
}
return null;
}
public String getAsString(FacesContext facesContext, UIComponent component, Object o) {
if (o == null) return null;
return ((Specialty) o).getName();
}
private VetController getCapitalsParser(FacesContext facesContext) {
if (vetController == null) {
ELContext elContext = facesContext.getELContext();
vetController = (VetController) elContext.getELResolver().getValue(elContext, null, "vetController");
}
return vetController;
}
}
| 1,408 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
PetTypeController.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/web/PetTypeController.java | package org.woehlke.javaee7.petclinic.web;
import org.richfaces.component.SortOrder;
import org.woehlke.javaee7.petclinic.dao.PetTypeDao;
import org.woehlke.javaee7.petclinic.entities.PetType;
import javax.ejb.EJB;
import javax.ejb.EJBTransactionRolledbackException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import java.io.Serializable;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: Fert
* Date: 06.01.14
* Time: 11:49
* To change this template use File | Settings | File Templates.
*/
@ManagedBean
@SessionScoped
public class PetTypeController implements Serializable {
@EJB
private PetTypeDao petTypeDao;
private PetType petType;
private SortOrder petTypeSortOrder = SortOrder.ascending;
private int scrollerPage;
public SortOrder getPetTypeSortOrder() {
return petTypeSortOrder;
}
public void setPetTypeSortOrder(SortOrder petTypeSortOrder) {
this.petTypeSortOrder = petTypeSortOrder;
}
public void switchSortOrder(){
if(petTypeSortOrder == SortOrder.ascending){
petTypeSortOrder = SortOrder.descending;
} else {
petTypeSortOrder = SortOrder.ascending;
}
}
public PetType getPetType() {
return petType;
}
public void setPetType(PetType petType) {
this.petType = petType;
}
public List<PetType> getPetTypes(){
return petTypeDao.getAll();
}
public String getNewPetTypeForm(){
petType = new PetType();
return "petTypeNew.jsf";
}
public String saveNewPetType(){
petTypeDao.addNew(this.petType);
return "petTypeList.jsf";
}
public String getEditForm(long id){
this.petType = petTypeDao.findById(id);
return "petTypeEdit.jsf";
}
public String saveEditedPetType(){
petTypeDao.update(this.petType);
return "petTypeList.jsf";
}
public String delete(long id){
try {
petTypeDao.delete(id);
} catch (EJBTransactionRolledbackException e) {
FacesContext ctx = FacesContext.getCurrentInstance();
ctx.addMessage(null, new FacesMessage("cannot delete, object still in use"));
}
return "petTypeList.jsf";
}
public void setScrollerPage(int scrollerPage) {
this.scrollerPage = scrollerPage;
}
public int getScrollerPage() {
return scrollerPage;
}
}
| 2,558 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
VetController.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/web/VetController.java | package org.woehlke.javaee7.petclinic.web;
import org.woehlke.javaee7.petclinic.dao.SpecialtyDao;
import org.woehlke.javaee7.petclinic.dao.VetDao;
import org.woehlke.javaee7.petclinic.entities.Specialty;
import org.woehlke.javaee7.petclinic.entities.Vet;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 01.01.14
* Time: 22:59
* To change this template use File | Settings | File Templates.
*/
@ManagedBean
@SessionScoped
public class VetController implements Serializable {
@EJB
private VetDao vetDao;
@EJB
private SpecialtyDao specialtyDao;
private Vet vet;
private String searchterm;
private List<Vet> vets;
private List<Specialty> specialties;
private List<Specialty> selectedSpecialties;
private int scrollerPage = 1;
public List<Specialty> getSpecialties() {
specialties = specialtyDao.getAll();
return specialties;
}
public void setSpecialties(List<Specialty> specialties) {
this.specialties = specialties;
}
public List<Specialty> getSelectedSpecialties() {
return selectedSpecialties;
}
public void setSelectedSpecialties(List<Specialty> selectedSpecialties) {
this.selectedSpecialties = selectedSpecialties;
}
public Vet getVet() {
return vet;
}
public void setVet(Vet vet) {
this.vet = vet;
}
public String getNewVetForm() {
this.vet = new Vet();
this.specialties = specialtyDao.getAll();
this.selectedSpecialties = new ArrayList<Specialty>();
return "vetNew.jsf";
}
public String saveNewVet() {
for (Specialty specialty : selectedSpecialties) {
this.vet.addSpecialty(specialty);
}
vetDao.addNew(this.vet);
this.vets = vetDao.getAll();
return "vetList.jsf";
}
public List<Vet> getVets() {
if (this.vets == null) {
this.vets = vetDao.getAll();
}
return this.vets;
}
public String getEditForm(long id) {
this.vet = vetDao.findById(id);
selectedSpecialties = vet.getSpecialties();
return "vetEdit.jsf";
}
public String saveEditedVet() {
this.vet.removeSpecialties();
for (Specialty specialty : selectedSpecialties) {
this.vet.addSpecialty(specialty);
}
vetDao.update(this.vet);
this.vets = vetDao.getAll();
return "vetList.jsf";
}
public String deleteVet(long id) {
this.vet = vetDao.findById(id);
this.vet.removeSpecialties();
vetDao.update(this.vet);
vetDao.delete(id);
this.vets = vetDao.getAll();
return "vetList.jsf";
}
public String getSearchterm() {
return searchterm;
}
public void setSearchterm(String searchterm) {
this.searchterm = searchterm;
}
public String search() {
if (searchterm == null || searchterm.isEmpty()) {
this.vets = vetDao.getAll();
} else {
try {
this.vets = vetDao.search(searchterm);
} catch (Exception e) {
this.vets = vetDao.getAll();
}
}
return "vetList.jsf";
}
public int getScrollerPage() {
return scrollerPage;
}
public void setScrollerPage(int scrollerPage) {
this.scrollerPage = scrollerPage;
}
}
| 3,588 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Vets.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/src/main/java/org/woehlke/javaee7/petclinic/model/Vets.java | package org.woehlke.javaee7.petclinic.model;
import org.woehlke.javaee7.petclinic.entities.Vet;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: tw
* Date: 01.01.14
* Time: 21:37
* To change this template use File | Settings | File Templates.
*/
@XmlRootElement
public class Vets {
private List<Vet> vetList;
@XmlElement
public List<Vet> getVetList() {
if (vetList == null) {
vetList = new ArrayList<Vet>();
}
return vetList;
}
public void setVetList(List<Vet> vetList) {
this.vetList = vetList;
}
}
| 718 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__org_seleniumhq_selenium_selenium_java_2_53_1.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__org_seleniumhq_selenium_selenium_java_2_53_1.xml | <component name="libraryTable">
<library name="Maven: org.seleniumhq.selenium:selenium-java:2.53.1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/seleniumhq/selenium/selenium-java/2.53.1/selenium-java-2.53.1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/seleniumhq/selenium/selenium-java/2.53.1/selenium-java-2.53.1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/seleniumhq/selenium/selenium-java/2.53.1/selenium-java-2.53.1-sources.jar!/" />
</SOURCES>
</library>
</component> | 585 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__javax_servlet_javax_servlet_api_3_1_0.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__javax_servlet_javax_servlet_api_3_1_0.xml | <component name="libraryTable">
<library name="Maven: javax.servlet:javax.servlet-api:3.1.0">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/javax/servlet/javax.servlet-api/3.1.0/javax.servlet-api-3.1.0.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/javax/servlet/javax.servlet-api/3.1.0/javax.servlet-api-3.1.0-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/javax/servlet/javax.servlet-api/3.1.0/javax.servlet-api-3.1.0-sources.jar!/" />
</SOURCES>
</library>
</component> | 566 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__net_java_dev_jna_jna_platform_4_1_0.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__net_java_dev_jna_jna_platform_4_1_0.xml | <component name="libraryTable">
<library name="Maven: net.java.dev.jna:jna-platform:4.1.0">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/net/java/dev/jna/jna-platform/4.1.0/jna-platform-4.1.0.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/net/java/dev/jna/jna-platform/4.1.0/jna-platform-4.1.0-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/net/java/dev/jna/jna-platform/4.1.0/jna-platform-4.1.0-sources.jar!/" />
</SOURCES>
</library>
</component> | 543 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__com_googlecode_javaewah_JavaEWAH_1_1_12.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__com_googlecode_javaewah_JavaEWAH_1_1_12.xml | <component name="libraryTable">
<library name="Maven: com.googlecode.javaewah:JavaEWAH:1.1.12">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/googlecode/javaewah/JavaEWAH/1.1.12/JavaEWAH-1.1.12.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/googlecode/javaewah/JavaEWAH/1.1.12/JavaEWAH-1.1.12-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/googlecode/javaewah/JavaEWAH/1.1.12/JavaEWAH-1.1.12-sources.jar!/" />
</SOURCES>
</library>
</component> | 550 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__org_codehaus_plexus_plexus_compiler_javac_2_3.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__org_codehaus_plexus_plexus_compiler_javac_2_3.xml | <component name="libraryTable">
<library name="Maven: org.codehaus.plexus:plexus-compiler-javac:2.3">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/codehaus/plexus/plexus-compiler-javac/2.3/plexus-compiler-javac-2.3.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/codehaus/plexus/plexus-compiler-javac/2.3/plexus-compiler-javac-2.3-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/codehaus/plexus/plexus-compiler-javac/2.3/plexus-compiler-javac-2.3-sources.jar!/" />
</SOURCES>
</library>
</component> | 604 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.