answer
stringlengths 17
10.2M
|
|---|
package org.zeromq;
import zmq.ZError;
public class ZMQException extends RuntimeException
{
public static class IOException extends RuntimeException
{
private static final long serialVersionUID = 8440355423370109164L;
public IOException(java.io.IOException cause)
{
super(cause);
}
}
private static final long serialVersionUID = 5957233088499712341L;
private final int code;
public ZMQException(int errno)
{
super("Errno " + errno);
code = errno;
}
public ZMQException(String message, int errno)
{
super(message);
code = errno;
}
public ZMQException(ZMQException cause)
{
super(cause.getMessage(), cause);
code = cause.code;
}
public int getErrorCode()
{
return code;
}
@Override
public String toString()
{
return super.toString() + " : " + ZError.toString(code);
}
}
|
package roart.client;
import roart.model.ResultItem;
import java.util.List;
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.Map;
import java.util.Date;
//import roart.beans.session.misc.Unit;
import roart.beans.session.comic.Unit;
import roart.beans.session.comic.UnitBuy;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Table;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.Component;
import com.vaadin.ui.Layout;
import com.vaadin.ui.Link;
import com.vaadin.server.ExternalResource;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.ListSelect;
import com.vaadin.ui.TextField;
import com.vaadin.ui.InlineDateField;
import com.vaadin.ui.PopupDateField;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Container;
import com.vaadin.data.Container.ItemSetChangeListener;
import com.vaadin.ui.Notification;
import com.vaadin.ui.TabSheet;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//@Theme("mytheme")
@Theme("valo")
@SuppressWarnings("serial")
public class MyVaadinUI extends UI
{
private Log log = LogFactory.getLog(this.getClass());
//private static final Logger log = LoggerFactory.getLogger(MyVaadinUI.class);
/*
Button button = new Button("Click Me");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
layout.addComponent(new Label("Thank you for clicking"));
}
});
*/
// layout.addComponent(tf);
TabSheet tabsheet = new TabSheet();
layout.addComponent(tabsheet);
// Create the first tab
searchTab = getSearchTab();
// This tab gets its caption from the component caption
controlPanelTab = getControlPanelTab();
miscTab = getMiscTab();
comicsTab = getComicsTab();
trainingTab = getTrainingTab();
tabsheet.addTab(searchTab);
// This tab gets its caption from the component caption
tabsheet.addTab(controlPanelTab);
tabsheet.addTab(miscTab);
tabsheet.addTab(comicsTab);
tabsheet.addTab(trainingTab);
}
private VerticalLayout getSearchTab() {
VerticalLayout tab = new VerticalLayout();
//tab.addComponent(tf);
tab.setCaption("Search");
tab.addComponent(getSearch("Search plain", 0));
tab.addComponent(getSearch("Search analyzing", 1));
tab.addComponent(getSearch("Search complex", 2));
tab.addComponent(getSearch("Search extendable", 3));
tab.addComponent(getSearch("Search multi", 4));
tab.addComponent(getSearch("Search simple", 5));
return tab;
}
private VerticalLayout getControlPanelTab() {
VerticalLayout tab = new VerticalLayout();
tab.setCaption("Control Panel");
tab.addComponent(getFsIndexNew());
tab.addComponent(getFsAddNew());
tab.addComponent(getIndexNew());
tab.addComponent(getFsIndexNewPath());
tab.addComponent(getFsAddNewPath());
tab.addComponent(getIndexNewPath());
tab.addComponent(getNotIndexed());
/*
tab.addComponent(getCleanup());
tab.addComponent(getCleanup2());
tab.addComponent(getCleanupfs());
*/
tab.addComponent(getMemoryUsage());
tab.addComponent(getOverlapping());
tab.addComponent(getReindex());
tab.addComponent(getReindexDate());
tab.addComponent(getFsIndexNewMd5());
tab.addComponent(getIndexSuffix());
return tab;
}
private VerticalLayout getMiscTab() {
VerticalLayout tab = new VerticalLayout();
//tab.addComponent(tf2);
tab.setCaption("Misc");
HorizontalLayout cdTab = new HorizontalLayout();
cdTab.addComponent(getMiscCreator("cd"));
cdTab.addComponent(getMiscYear("cd"));
cdTab.addComponent(getMiscSearch("cd"));
HorizontalLayout dvdTab = new HorizontalLayout();
dvdTab.addComponent(getMiscCreator("dvd"));
dvdTab.addComponent(getMiscYear("dvd"));
dvdTab.addComponent(getMiscSearch("dvd"));
HorizontalLayout bookTab = new HorizontalLayout();
bookTab.addComponent(getMiscCreator("book"));
bookTab.addComponent(getMiscYear("book"));
bookTab.addComponent(getMiscSearch("book"));
HorizontalLayout book0Tab = new HorizontalLayout();
book0Tab.addComponent(getMiscCreator("book0"));
book0Tab.addComponent(getMiscYear("book0"));
book0Tab.addComponent(getMiscSearch("book0"));
HorizontalLayout bookuTab = new HorizontalLayout();
bookuTab.addComponent(getMiscCreator("booku"));
bookuTab.addComponent(getMiscYear("booku"));
bookuTab.addComponent(getMiscSearch("booku"));
tab.addComponent(cdTab);
tab.addComponent(dvdTab);
tab.addComponent(bookTab);
tab.addComponent(bookuTab);
tab.addComponent(bookuTab);
return tab;
}
private VerticalLayout getComicsTab() {
VerticalLayout tab = new VerticalLayout();
//tab.addComponent(tf2);
tab.setCaption("Comics");
tab.addComponent(getComicTitles());
tab.addComponent(getComicLetters());
tab.addComponent(getComicAll());
tab.addComponent(getComicSearch());
tab.addComponent(getComicYear());
return tab;
}
private VerticalLayout getTrainingTab() {
VerticalLayout tab = new VerticalLayout();
//tab.addComponent(tf2);
tab.setCaption("Training");
tab.addComponent(getTrainingYear());
return tab;
}
private Button getFsIndexNew() {
Button button = new Button("Index filesystem new items");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
roart.beans.session.control.Main maininst = new roart.beans.session.control.Main();
List<String> strarr = null;
try {
strarr = maininst.filesystemlucenenew();
} catch (Exception e) {
log.error("Exception", e);
}
VerticalLayout result = getResultTemplate();
addList(result, strarr);
setContent(result);
}
});
return button;
}
private Button getFsAddNew() {
Button button = new Button("Filesystem add new");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
roart.beans.session.control.Main maininst = new roart.beans.session.control.Main();
List<String> strarr = null;
try {
strarr =maininst.traverse();
} catch (Exception e) {
log.error("Exception", e);
}
VerticalLayout result = getResultTemplate();
addList(result, strarr);
setContent(result);
}
});
return button;
}
private Button getIndexNew() {
Button button = new Button("Index non-indexed items");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
roart.beans.session.control.Main maininst = new roart.beans.session.control.Main();
List<String> strarr = null;
try {
strarr = maininst.index(null);
} catch (Exception e) {
log.error("Exception", e);
}
VerticalLayout result = getResultTemplate();
addList(result, strarr);
setContent(result);
}
});
return button;
}
private Button getMemoryUsage() {
Button button = new Button("Memory usage");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
roart.beans.session.control.Main maininst = new roart.beans.session.control.Main();
List<String> strarr = maininst.memoryusage();
VerticalLayout result = getResultTemplate();
addList(result, strarr);
setContent(result);
}
});
return button;
}
private Button getNotIndexed() {
Button button = new Button("Get not yet indexed");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
roart.beans.session.control.Main maininst = new roart.beans.session.control.Main();
List<String> strarr = null;
try {
strarr = maininst.notindexed();
} catch (Exception e) {
log.error("Exception", e);
}
VerticalLayout result = getResultTemplate();
addList(result, strarr);
setContent(result);
}
});
return button;
}
private Button getOverlapping() {
Button button = new Button("Overlapping");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
roart.beans.session.control.Main maininst = new roart.beans.session.control.Main();
List<String> strarr = maininst.overlapping();
VerticalLayout result = getResultTemplate();
addList(result, strarr);
setContent(result);
}
});
return button;
}
private TextField getFsIndexNewPath() {
TextField tf = new TextField("Index filesystem new items");
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
roart.beans.session.control.Main maininst = new roart.beans.session.control.Main();
List<String> strarr = null;
try {
strarr = maininst.filesystemlucenenew(value, false);
} catch (Exception e) {
log.error("Exception", e);
}
VerticalLayout result = getResultTemplate();
addList(result, strarr);
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getFsAddNewPath() {
TextField tf = new TextField("Filesystem add new");
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
roart.beans.session.control.Main maininst = new roart.beans.session.control.Main();
List<String> strarr = null;
try {
strarr = maininst.traverse(value);
} catch (Exception e) {
log.error("Exception", e);
}
VerticalLayout result = getResultTemplate();
addList(result, strarr);
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getIndexNewPath() {
TextField tf = new TextField("Index non-indexed items");
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
roart.beans.session.control.Main maininst = new roart.beans.session.control.Main();
List<String> strarr = null;
try {
strarr = maininst.index(value, false);
} catch (Exception e) {
log.error("Exception", e);
}
VerticalLayout result = getResultTemplate();
addList(result, strarr);
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getCleanup() {
TextField tf = new TextField("Cleanup");
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getCleanup2() {
TextField tf = new TextField("Cleanup2");
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getCleanupfs() {
TextField tf = new TextField("Cleanupfs");
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getReindex() {
TextField tf = new TextField("Reindex");
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
roart.beans.session.control.Main maininst = new roart.beans.session.control.Main();
List<String> strarr = null;
try {
strarr = maininst.index(value, true);
} catch (Exception e) {
log.error("Exception", e);
}
VerticalLayout result = getResultTemplate();
addList(result, strarr);
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private InlineDateField getReindexDate() {
InlineDateField tf = new InlineDateField("Reindex on date");
// Create a DateField with the default style
// Set the date and time to present
Date date = new Date();
// temp fix
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
tf.setValue(date);
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
Date date = (Date) event.getProperty().getValue();
// Do something with the value
roart.beans.session.control.Main maininst = new roart.beans.session.control.Main();
long time = date.getTime();
List<String> strarr = null;
try {
strarr = maininst.indexdate("" + time, true);
} catch (Exception e) {
log.error("Exception", e);
}
VerticalLayout result = getResultTemplate();
addList(result, strarr);
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getIndexSuffix() {
TextField tf = new TextField("Index on suffix");
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
roart.beans.session.control.Main maininst = new roart.beans.session.control.Main();
List<String> strarr = null;
try {
strarr = maininst.index(value);
} catch (Exception e) {
log.error("Exception", e);
}
VerticalLayout result = getResultTemplate();
addList(result, strarr);
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getFsIndexNewMd5() {
TextField tf = new TextField("Filesystem index on md5");
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
roart.beans.session.control.Main maininst = new roart.beans.session.control.Main();
List<String> strarr = null;
try {
strarr = maininst.filesystemlucenenew(value, true);
} catch (Exception e) {
log.error("Exception", e);
}
VerticalLayout result = getResultTemplate();
addList(result, strarr);
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getMiscSearch(final String type) {
TextField tf = new TextField("Search " + type);
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
roart.beans.session.misc.Main maininst = new roart.beans.session.misc.Main();
List<ResultItem> strarr = maininst.searchme(type, value);
VerticalLayout result = getResultTemplate();
addListTable(result, strarr);
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getSearch(String caption, final int type) {
TextField tf = new TextField(caption);
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
roart.beans.session.misc.Main maininst = new roart.beans.session.misc.Main();
List<ResultItem> strarr = maininst.searchme2(value, "" + type);
VerticalLayout result = getResultTemplate();
addListTable(result, strarr);
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private ListSelect getMiscCreator(String type) {
return getMiscYearOrCreator(type, "creator");
}
private ListSelect getMiscYear(String type) {
return getMiscYearOrCreator(type, "year");
}
private ListSelect getMiscYearOrCreator(final String type, final String yc) {
ListSelect ls = new ListSelect("Search " + type + " " + yc);
// Add some items (here by the item ID as the caption)
final roart.beans.session.misc.Main maininst = new roart.beans.session.misc.Main();
if (yc.equals("year")) {
ls.addItems(maininst.getYears(type));
ls.setWidth("200");
} else {
ls.addItems(maininst.getCreators(type));
ls.setWidth("400");
}
ls.setNullSelectionAllowed(false);
// Show 5 items and a scrollbar if there are more
ls.setRows(5);
// Handle changes in the value
ls.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
List<roart.beans.session.misc.Unit> myunits = null;
if (yc.equals("year")) {
myunits = maininst.searchyear(type, value);
} else {
myunits = maininst.searchcreator(type, value);
}
Integer count = new Integer (0);
Float price = new Float (0);
Table table = new Table(type);
table.setWidth("800");
table.addContainerProperty("Date", String.class, null);
table.addContainerProperty("Count", String.class, null);
table.addContainerProperty("Type", String.class, null);
table.addContainerProperty("Price", String.class, null);
table.addContainerProperty("Creator", String.class, null);
table.addContainerProperty("Title", String.class, null);
if (type.startsWith("book")) {
table.addContainerProperty("Isbn 1", Link.class, null);
table.addContainerProperty("Isbn 2", Link.class, null);
table.addContainerProperty("Isbn 3", Link.class, null);
table.addContainerProperty("Isbn 4", Link.class, null);
}
for (int i=0; i<myunits.size(); i++) {
count += new Integer(myunits.get(i).getCount());
if (!myunits.get(i).getPrice().substring(0,1).equals("D") && !myunits.get(i).getPrice().substring(0,1).equals("L") && !myunits.get(i).getPrice().substring(0,1).equals("g") ) {
price += new Float(myunits.get(i).getPrice());
}
String isbn = myunits.get(i).getIsbn();
String str = "";
Link link1 = null, link2 = null, link3 = null, link4 = null;
if (isbn != null && !isbn.equals("0")) {
link1 = new Link("US " + isbn, new ExternalResource("http:
link2 = new Link("US " + isbn, new ExternalResource("http:
link3 = new Link("SE " + isbn, new ExternalResource("http://libris.kb.se/hitlist?d=libris&q=numm%3a" + isbn));
link4 = new Link("G " + isbn, new ExternalResource("https:
}
table.addItem(new Object[]{myunits.get(i).getDate(), myunits.get(i).getCount(), myunits.get(i).getType(), myunits.get(i).getPrice(), myunits.get(i).getCreator(), myunits.get(i).getTitle(), link1, link2, link3, link4}, i);
}
table.setPageLength(table.size());
VerticalLayout result = getResultTemplate();
result.addComponent(table);
result.addComponent(new Label("Size count price " + myunits.size() + " " + count + " " + price));
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
ls.setImmediate(true);
return ls;
}
void addListTable(VerticalLayout ts, List<ResultItem> strarr) {
Table table = new Table("Table");
table.setWidth("800");
int max = 0;
for (int i=0; i<strarr.size(); i++) {
if (strarr.get(i).get().size() > max) {
max = strarr.get(i).get().size();
}
}
for (int i = 0; i < max; i++) {
table.addContainerProperty(strarr.get(0).get().get(i), String.class, null);
}
for (int i = 1; i < strarr.size(); i++) {
ResultItem str = strarr.get(i);
table.addItem(str.getarr(), i);
}
table.setPageLength(table.size());
ts.addComponent(table);
}
void addList(VerticalLayout ts, List<String> strarr) {
for (int i=0; i<strarr.size(); i++) {
String str = strarr.get(i);
ts.addComponent(new Label(str));
}
}
private ListSelect getComicTitles() {
final ListSelect ls = new ListSelect("Search titles");
// Add some items (here by the item ID as the caption)
roart.beans.session.comic.Main maininst = new roart.beans.session.comic.Main();
ls.addItems(maininst.getTitles("comic"));
ls.setNullSelectionAllowed(false);
// Show 5 items and a scrollbar if there are more
ls.setRows(5);
// Handle changes in the value
ls.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
int pos = -1;
int j = -1;
for (Object o : ls.getItemIds()) {
j = j + 1;
if(ls.isSelected(o)) {
if (pos < 0) {
pos = j;
} else {
log.error("double pos");
}
}
}
roart.beans.session.comic.Main maininst = new roart.beans.session.comic.Main();
List<roart.beans.session.comic.Unit> myunits = maininst.searchtitle("comic", pos);
VerticalLayout result = getResultTemplate();
addListComic(result, myunits);
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
ls.setImmediate(true);
return ls;
}
private ListSelect getComicLetters() {
ListSelect ls = new ListSelect("Search letters");
// Add some items (here by the item ID as the caption)
roart.beans.session.comic.Main maininst = new roart.beans.session.comic.Main();
String[] items2 = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
ls.addItems(items2);
ls.setNullSelectionAllowed(false);
// Show 5 items and a scrollbar if there are more
ls.setRows(5);
// Handle changes in the value
ls.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
String letter = value;
roart.beans.session.comic.Main maininst = new roart.beans.session.comic.Main();
List<roart.beans.session.comic.Unit> myunits = maininst.searchtitle("comic", letter);
VerticalLayout result = getResultTemplate();
addListComic(result, myunits);
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
ls.setImmediate(true);
return ls;
}
private ListSelect getComicYear() {
ListSelect ls = new ListSelect("Search years");
// Add some items (here by the item ID as the caption)
roart.beans.session.comic.Main maininst = new roart.beans.session.comic.Main();
ls.addItems(maininst.getYears("com"));
ls.setNullSelectionAllowed(false);
// Show 5 items and a scrollbar if there are more
ls.setRows(5);
// Handle changes in the value
ls.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
roart.beans.session.comic.Main maininst = new roart.beans.session.comic.Main();
Table table = new Table("Comics year 20" + value);
int count = 0;
int sum = 0;
String year = value;
TreeMap<String, Integer> mysums = new TreeMap<String, Integer>();
List<UnitBuy> myunits = maininst.searchyear(mysums, "com", year);
for (int i=0; i<myunits.size(); i++) {
UnitBuy myunit = myunits.get(i);
//String strcount = myunit.getCount();
int prc = ((new Integer(myunit.getPriceInt())).intValue());
sum += prc;
table.addItem(new Object[]{myunits.get(i).getDate(), myunits.get(i).getPrice(), myunits.get(i).getData1() , ":", myunits.get(i).getData2()}, i);
}
table.setPageLength(myunits.size());
VerticalLayout result = getResultTemplate();
result.addComponent(table);
for (String key : mysums.keySet()) {
Integer i = mysums.get(key);
count += i.intValue();
result.addComponent(new Label("key " + key + " " + i.intValue()));
}
result.addComponent(new Label("size count sum " + myunits.size() + " " + count + " " + sum));
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
ls.setImmediate(true);
return ls;
}
private Button getComicAll() {
Button button = new Button("Get all comics");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
roart.beans.session.comic.Main maininst = new roart.beans.session.comic.Main();
List<roart.beans.session.comic.Unit> myunits = maininst.searchtitle("comic");
VerticalLayout result = getResultTemplate();
addListComic(result, myunits);
setContent(result);
}
});
return button;
}
private TextField getComicSearch() {
TextField tf = new TextField("Search comics");
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
VerticalLayout result = getResultTemplate();
result.addComponent(new Label("unknown"));
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
void addListComic(VerticalLayout ts, List<roart.beans.session.comic.Unit> myunits) {
//Table table = new Table(type);
int count = 0;
int sum = 0;
for (int i=0; i<myunits.size(); i++) {
roart.beans.session.comic.Unit myunit = myunits.get(i);
String strcount = myunit.getCount();
int cnt = ((new Integer(strcount)).intValue());
int prc = ((new Integer(myunit.getPrice())).intValue());
count += cnt;
sum += cnt * prc;
ts.addComponent(new Label(myunits.get(i).getTitle()));
List<String> lines = myunits.get(i).getContent();
for (int j=0; j<lines.size(); j++) {
ts.addComponent(new Label(lines.get(j)));
}
}
ts.addComponent(new Label("size count sum " + myunits.size() + " " + count + " " + sum));
//table.setPageLength(myunits.size());
//miscTab.addComponent(table);
}
private ListSelect getTrainingYear() {
ListSelect ls = new ListSelect("Training years");
// Add some items (here by the item ID as the caption)
roart.beans.session.training.Main maininst = new roart.beans.session.training.Main();
ls.addItems(maininst.getYears("tren"));
ls.setNullSelectionAllowed(false);
// Show 5 items and a scrollbar if there are more
ls.setRows(5);
// Handle changes in the value
ls.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
VerticalLayout result = getResultTemplate();
roart.beans.session.training.Main maininst = new roart.beans.session.training.Main();
int count = 0;
int sum = 0;
TreeMap<String, Integer> mysums = new TreeMap<String, Integer>();
String type = "tren";
String year = value;
List<roart.beans.session.training.Unit> myunits = maininst.searchyear(mysums, type, year);
for (int i=0; i<myunits.size(); i++) {
roart.beans.session.training.Unit myunit = myunits.get(i);
result.addComponent(new Label("t " + myunits.get(i).getDate() + " " + myunits.get(i).getData()));
}
for (String key : mysums.keySet()) {
Integer i = mysums.get(key);
count += i.intValue();
result.addComponent(new Label("key " + i.intValue()));
}
result.addComponent(new Label("size count sum " + myunits.size() + " " + count + " " + sum));
setContent(result);
}
});
// Fire value changes immediately when the field loses focus
ls.setImmediate(true);
return ls;
}
private VerticalLayout getResultTemplate() {
final Component content = getContent();
VerticalLayout res = new VerticalLayout();
res.addComponent(new Label("Search results"));
Button button = new Button("Back to main page");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
setContent(content);
}
});
res.addComponent(button);
return res;
}
}
|
package sc.iview.vector;
import net.imglib2.Localizable;
import net.imglib2.RealLocalizable;
import net.imglib2.RealPositionable;
/**
* Interface for 3D vectors.
*
* @author Kyle Harrington
* @author Curtis Rueden
*/
public interface Vector3 extends RealLocalizable, RealPositionable {
// -- Vector3 methods --
float xf();
float yf();
float zf();
default void moveX(float distance) { setX( xf() + distance ); }
default void moveY(float distance) { setY( yf() + distance ); }
default void moveZ(float distance) { setZ( zf() + distance ); }
default void move( float xDist, float yDist, float zDist ) {
moveX( xDist );
moveY( yDist );
moveZ( zDist );
}
void setX(float position);
void setY(float position);
void setZ(float position);
default void setPosition( float x, float y, float z ) {
setX( x );
setY( y );
setZ( z );
}
default double xd() { return xf(); }
default double yd() { return yf(); }
default double zd() { return zf(); }
default void moveX(double distance) { setX( xd() + distance ); }
default void moveY(double distance) { setY( yd() + distance ); }
default void moveZ(double distance) { setZ( zd() + distance ); }
default void move( double xDist, double yDist, double zDist ) {
moveX( xDist );
moveY( yDist );
moveZ( zDist );
}
default void setX(double position) { setX((float) position); }
default void setY(double position) { setY((float) position); }
default void setZ(double position) { setZ((float) position); }
default void setPosition( double x, double y, double z ) {
setX( x );
setY( y );
setZ( z );
}
// -- RealLocalizable methods --
@Override
default void localize( float[] position ) {
position[0] = xf();
position[1] = yf();
position[2] = zf();
}
@Override
default void localize( double[] position ) {
position[0] = xd();
position[1] = yd();
position[2] = zd();
}
@Override
default float getFloatPosition( int d ) {
if( d == 0 ) return xf();
if( d == 1 ) return yf();
if( d == 2 ) return zf();
throw new IndexOutOfBoundsException( "" + d );
}
@Override
default double getDoublePosition( int d ) {
if( d == 0 ) return xd();
if( d == 1 ) return yd();
if( d == 2 ) return zd();
throw new IndexOutOfBoundsException( "" + d );
}
// -- RealPositionable methods --
@Override
default void move( float distance, int d ) {
if( d == 0 ) moveX( distance );
else if( d == 1 ) moveY( distance );
else if( d == 2 ) moveZ( distance );
else throw new IndexOutOfBoundsException( "" + d );
}
@Override
default void move( double distance, int d ) {
if( d == 0 ) moveX( distance );
else if( d == 1 ) moveY( distance );
else if( d == 2 ) moveZ( distance );
else throw new IndexOutOfBoundsException( "" + d );
}
@Override
default void move( RealLocalizable distance ) {
moveX( distance.getDoublePosition( 0 ) );
moveY( distance.getDoublePosition( 1 ) );
moveZ( distance.getDoublePosition( 2 ) );
}
@Override
default void move( float[] distance ) {
moveX( distance[0] );
moveY( distance[1] );
moveZ( distance[2] );
}
@Override
default void move( double[] distance ) {
moveX( distance[0] );
moveY( distance[1] );
moveZ( distance[2] );
}
@Override
default void setPosition( RealLocalizable localizable ) {
setX( localizable.getDoublePosition( 0 ) );
setY( localizable.getDoublePosition( 1 ) );
setZ( localizable.getDoublePosition( 2 ) );
}
@Override
default void setPosition( float[] position ) {
setX( position[0] );
setY( position[1] );
setZ( position[2] );
}
@Override
default void setPosition( double[] position ) {
setX( position[0] );
setY( position[1] );
setZ( position[2] );
}
@Override
default void setPosition( float position, int d ) {
if( d == 0 ) setX( position );
else if( d == 1 ) setY( position );
else if( d == 2 ) setZ( position );
else throw new IndexOutOfBoundsException( "" + d );
}
@Override
default void setPosition( double position, int d ) {
if( d == 0 ) setX( position );
else if( d == 1 ) setY( position );
else if( d == 2 ) setZ( position );
else throw new IndexOutOfBoundsException( "" + d );
}
// -- Positionable methods --
@Override
default void fwd( int d ) { move( 1, d ); }
@Override
default void bck( int d ) { move( 1, d ); }
@Override
default void move( int distance, int d ) {
move( ( double ) distance, d );
}
@Override
default void move( long distance, int d ) {
move( ( double ) distance, d );
}
@Override
default void move( Localizable distance ) {
moveX( distance.getDoublePosition( 0 ) );
moveY( distance.getDoublePosition( 1 ) );
moveZ( distance.getDoublePosition( 2 ) );
}
@Override
default void move( int[] distance ) {
moveX( (double) distance[0] );
moveY( (double) distance[1] );
moveZ( (double) distance[2] );
}
@Override
default void move( long[] distance ) {
moveX( (double) distance[0] );
moveY( (double) distance[1] );
moveZ( (double) distance[2] );
}
@Override
default void setPosition( Localizable localizable ) {
setX( localizable.getDoublePosition( 0 ) );
setY( localizable.getDoublePosition( 1 ) );
setZ( localizable.getDoublePosition( 2 ) );
}
@Override
default void setPosition( int[] position ) {
setX( (double) position[0] );
setY( (double) position[1] );
setZ( (double) position[2] );
}
@Override
default void setPosition( long[] position ) {
setX( (double) position[0] );
setY( (double) position[1] );
setZ( (double) position[2] );
}
@Override
default void setPosition( int position, int d ) {
setPosition( ( double ) position, d );
}
@Override
default void setPosition( long position, int d ) {
setPosition( ( double ) position, d );
}
// -- EuclideanSpace methods --
@Override
default int numDimensions() { return 3; }
// Extra convenience methods
default double getLength() {
return Math.sqrt( getDoublePosition(0) * getDoublePosition(0) + getDoublePosition(1) * getDoublePosition(1) + getDoublePosition(2) * getDoublePosition(2) );
}
default Vector3 minus(Vector3 p2) {
Vector3 result = this.copy();
result.moveX(-p2.getDoublePosition(0));
result.moveY(-p2.getDoublePosition(1));
result.moveZ(-p2.getDoublePosition(2));
return result;
}
default Vector3 multiply(float s) {
Vector3 result = this.copy();
result.setPosition( result.getDoublePosition(0) * s, 0 );
result.setPosition( result.getDoublePosition(1) * s, 1 );
result.setPosition( result.getDoublePosition(2) * s, 2 );
return result;
}
default float[] asFloatArray() {
float[] a = new float[3];
a[0] = xf();
a[1] = yf();
a[2] = zf();
return a;
}
default double[] asDoubleArray() {
double[] a = new double[3];
a[0] = xd();
a[1] = yd();
a[2] = zd();
return a;
}
default Vector3 cross(Vector3 v2) {
ClearGLVector3 v = new ClearGLVector3(ClearGLVector3.convert(this));
return v.cross(v2);
}
default Vector3 elmul(Vector3 v2) {
Vector3 r = this.copy();
r.setX( r.xf() * v2.xf() );
r.setY( r.yf() * v2.yf() );
r.setZ( r.zf() * v2.zf() );
return r;
}
default float dot(Vector3 v2) {
return ( this.xf() * v2.xf() + this.yf() * v2.yf() + this.zf() * v2.zf() );
}
default Vector3 normalize() {
Vector3 r = this.copy();
double f = 1 / this.getLength();
r.setX(r.xf() * f);
r.setY(r.yf() * f);
r.setZ(r.zf() * f);
return r;
}
Vector3 copy();
}
|
// Triple Play - utilities for use in PlayN-based games
package tripleplay.anim;
import pythagoras.f.MathUtil;
import react.Signal;
import playn.core.Game;
import playn.core.Pointer;
/**
* Implements click, and scroll/flick gestures for a single variable (y position by default). When
* the pointer is pressed and dragged, the scroll position is updated to track the pointer. If the
* last two pointer events describe a motion of sufficiently high velocity, the scroll position is
* "flicked" and undergoes (friction decelerated) motion. If the pointer is pressed and released
* without scrolling or flicking, the {@link #clicked} signal is emitted.
*
* <p>To use: create a flicker, configure it as a pointer listener on a layer that represents your
* touchable area, then use {@link Flicker#position} to position your flickable layer (or to offset
* your hand-drawn flickable elements) on every frame tick. You must also call {@link
* Flicker#update} on every frame tick (to process changes due to acceleration and velocity).</p>
*
* <p>Various flick parameters can be customized by overriding the appropriate method: {@link
* #friction}, {@link #maxFlickVel}, etc.</p>
*
* <p><em>Note:</em> the flicker does not currently implement the iOS-style "bounce" that happens
* when an entity is flicked hard against its upper or lower bounds. The flicker simply stops when
* it reaches its bounds.</p>
*/
public class Flicker extends Pointer.Adapter
{
/** The current position value. */
public float position;
/** A signal that is emitted (with the pointer end event) on click. */
public Signal<Pointer.Event> clicked = Signal.create();
/**
* Creates a flicker with the specified initial, minimum and maximum values.
*/
public Flicker (float initial, float min, float max) {
this.position = initial;
_min = min;
_max = max;
}
/** This must be called every frame with {@link Game#update}'s delta. */
public void update (float delta) {
if (_vel != 0) {
float prev = position;
position = MathUtil.clamp(position + _vel * delta, _min, _max);
if (position == prev) _vel = 0; // for now stop when we hit the edge
float prevVel = _vel;
_vel += _accel * delta;
// if we decelerate past zero velocity, stop
if (Math.signum(prevVel) != Math.signum(_vel)) _vel = 0;
}
}
@Override public void onPointerStart (Pointer.Event event) {
_vel = 0;
_maxDelta = 0;
_origPos = position;
_start = _prev = _cur = getPosition(event);
_curStamp = _prevStamp = event.time();
}
@Override public void onPointerDrag (Pointer.Event event) {
_prev = _cur;
_prevStamp = _curStamp;
_cur = getPosition(event);
_curStamp = event.time();
float delta = _cur - _start;
position = MathUtil.clamp(_origPos + delta, _min, _max);
_maxDelta = Math.max(Math.abs(delta), _maxDelta);
}
@Override public void onPointerEnd (Pointer.Event event) {
// check whether we should call onClick
if (_maxDelta < maxClickDelta()) clicked.emit(event);
// if not, determine whether we should impart velocity to the tower
else {
float dragTime = (float)(_curStamp - _prevStamp);
float delta = _cur - _prev;
float signum = Math.signum(delta);
float dragVel = Math.abs(delta) / dragTime;
if (dragVel > flickVelThresh()) {
_vel = signum * Math.min(maxFlickVel(), dragVel * flickXfer());
_accel = -signum * friction();
}
}
}
/**
* Extracts the desired position from the pointer event. The default is to use the y-position.
*/
protected float getPosition (Pointer.Event event) {
return event.localY();
}
/**
* Returns the deceleration (in pixels per ms per ms) applied to non-zero velocity.
*/
protected float friction () {
return 0.004f;
}
/**
* Returns the minimum (positive) velocity (in pixels per millisecond) at time of touch release
* required to initiate a flick (i.e. transfer the flick velocity to the entity).
*/
protected float flickVelThresh () {
return 0.5f;
}
/**
* Returns the fraction of flick velocity that is transfered to the entity (a value between 0
* and 1).
*/
protected float flickXfer () {
return 0.7f;
}
/**
* Returns the maximum flick velocity that will be transfered to the entity; limits the actual
* flick velocity at time of release. This value is not adjusted by {@link #flickXfer}.
*/
protected float maxFlickVel () {
return 1.2f; // pixels/ms
}
/**
* Returns the maximum distance (in pixels) the pointer is allowed to travel while pressed and
* still register as a click.
*/
protected float maxClickDelta () {
return 5;
}
protected final float _min, _max;
protected float _vel, _accel;
protected float _origPos, _start, _cur, _prev;
protected double _curStamp, _prevStamp;
protected float _maxDelta;
}
|
package org.webrtc;
import java.nio.ByteBuffer;
/** Java wrapper for a C++ DataChannelInterface. */
public class DataChannel {
/** Java wrapper for WebIDL RTCDataChannel. */
public static class Init {
public boolean ordered = true;
// Optional unsigned short in WebIDL, -1 means unspecified.
public int maxRetransmitTimeMs = -1;
// Optional unsigned short in WebIDL, -1 means unspecified.
public int maxRetransmits = -1;
public String protocol = "";
public boolean negotiated = true;
// Optional unsigned short in WebIDL, -1 means unspecified.
public int id = -1;
public Init() {}
// Called only by native code.
private Init(
boolean ordered, int maxRetransmitTimeMs, int maxRetransmits,
String protocol, boolean negotiated, int id) {
this.ordered = ordered;
this.maxRetransmitTimeMs = maxRetransmitTimeMs;
this.maxRetransmits = maxRetransmits;
this.protocol = protocol;
this.negotiated = negotiated;
this.id = id;
}
}
/** Java version of C++ DataBuffer. The atom of data in a DataChannel. */
public static class Buffer {
/** The underlying data. */
public final ByteBuffer data;
/**
* Indicates whether |data| contains UTF-8 text or "binary data"
* (i.e. anything else).
*/
public final boolean binary;
public Buffer(ByteBuffer data, boolean binary) {
this.data = data;
this.binary = binary;
}
}
/** Java version of C++ DataChannelObserver. */
public interface Observer {
/** The data channel state has changed. */
public void onStateChange();
/**
* A data buffer was successfully received. NOTE: |buffer.data| will be
* freed once this function returns so callers who want to use the data
* asynchronously must make sure to copy it first.
*/
public void onMessage(Buffer buffer);
}
/** Keep in sync with DataChannelInterface::DataState. */
public enum State { CONNECTING, OPEN, CLOSING, CLOSED };
private final long nativeDataChannel;
private long nativeObserver;
public DataChannel(long nativeDataChannel) {
this.nativeDataChannel = nativeDataChannel;
}
/** Register |observer|, replacing any previously-registered observer. */
public void registerObserver(Observer observer) {
if (nativeObserver != 0) {
unregisterObserverNative(nativeObserver);
}
nativeObserver = registerObserverNative(observer);
}
private native long registerObserverNative(Observer observer);
/** Unregister the (only) observer. */
public void unregisterObserver() {
unregisterObserverNative(nativeObserver);
}
private native void unregisterObserverNative(long nativeObserver);
public native String label();
public native State state();
/**
* Return the number of bytes of application data (UTF-8 text and binary data)
* that have been queued using SendBuffer but have not yet been transmitted
* to the network.
*/
public native long bufferedAmount();
/** Close the channel. */
public native void close();
/** Send |data| to the remote peer; return success. */
public boolean send(Buffer buffer) {
// TODO(fischman): this could be cleverer about avoiding copies if the
// ByteBuffer is direct and/or is backed by an array.
byte[] data = new byte[buffer.data.remaining()];
buffer.data.get(data);
return sendNative(data, buffer.binary);
}
private native boolean sendNative(byte[] data, boolean binary);
/** Dispose of native resources attached to this channel. */
public native void dispose();
};
|
package net.genesishub.gFeatures.Feature.gWarsSuite.Multiplayer;
import net.genesishub.gFeatures.Feature.gWarsSuite.Statistics;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
public class CompassLoop {
Statistics stats = new Statistics();
public void updateAll(){
for(Player p : BlueTeam.getList()){
updatePlayer(p);
}
for(Player p : OrangeTeam.getList()){
updatePlayer(p);
}
}
public void updatePlayer(Player p){
for(ItemStack st : p.getInventory().getContents()){
try{
if(st.getType().equals(Material.COMPASS)){
p.getInventory().remove(st);
Player playerget = getNearest(p, 1000.0);
p.setCompassTarget(playerget.getLocation());
ItemMeta im = st.getItemMeta();
im.setDisplayName(ChatColor.AQUA + "Compass: " + ChatColor.GOLD + "" + playerget.getName());
st.setItemMeta(im);
p.getInventory().addItem(st);
}
}
catch(Exception e){
continue;
}
}
}
public Player getNearest(Player p, Double range) {
double distance = Double.POSITIVE_INFINITY; // To make sure the first
// player checked is closest
Player target = p;
for (Entity e : p.getNearbyEntities(range, range, range)) {
if (!(e instanceof Player))
continue;
double distanceto = p.getLocation().distance(e.getLocation());
if (distanceto > distance)
continue;
distance = distanceto;
if(stats.getStringTeam((Player) e).equals(ChatColor.DARK_AQUA + "Innisfil") && stats.getStringTeam((Player) e).equals(ChatColor.GOLD + "Kloyne")){
target = (Player) e;
}
else if(stats.getStringTeam((Player) e).equals(ChatColor.GOLD + "Kloyne") && stats.getStringTeam((Player) e).equals(ChatColor.DARK_AQUA + "Innisfil")){
target = (Player) e;
}
}
return target;
}
}
|
package net.java.sip.communicator.plugin.provisioning;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import net.java.sip.communicator.service.configuration.*;
import net.java.sip.communicator.service.credentialsstorage.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.httputil.*;
import net.java.sip.communicator.service.netaddr.*;
import net.java.sip.communicator.service.provdisc.*;
import net.java.sip.communicator.service.resources.*;
import net.java.sip.communicator.util.*;
import org.osgi.framework.*;
/**
* Activator the provisioning system. It will gather provisioning URL depending
* on the configuration (DHCP, manual, ...), retrieve configuration file and
* push properties to the <tt>ConfigurationService</tt>.
*/
public class ProvisioningActivator
implements BundleActivator
{
/**
* Logger of this class
*/
private static final Logger logger
= Logger.getLogger(ProvisioningActivator.class);
/**
* The current BundleContext.
*/
private static BundleContext bundleContext = null;
/**
* Name of the provisioning URL in the configuration service.
*/
private static final String PROPERTY_PROVISIONING_URL
= "net.java.sip.communicator.plugin.provisioning.URL";
/**
* Name of the provisioning username in the configuration service
* authentication).
*/
private static final String PROPERTY_PROVISIONING_USERNAME
= "net.java.sip.communicator.plugin.provisioning.auth.USERNAME";
/**
* Name of the provisioning password in the configuration service (HTTP
* authentication).
*/
private static final String PROPERTY_PROVISIONING_PASSWORD
= "net.java.sip.communicator.plugin.provisioning.auth";
/**
* Name of the property that contains the provisioning method (i.e. DHCP,
* DNS, manual, ...).
*/
private static final String PROVISIONING_METHOD_PROP
= "net.java.sip.communicator.plugin.provisioning.METHOD";
/**
* Name of the property that contains enforce prefix list (separated by
* pipe) for the provisioning. The retrieved configuration properties will
* be checked against these prefixes to avoid having incorrect content in
* the configuration file (such as HTML content resulting of HTTP error).
*/
private static final String PROVISIONING_ALLOW_PREFIX_PROP
= "provisioning.ALLOW_PREFIX";
/**
* Name of the enforce prefix property.
*/
private static final String PROVISIONING_ENFORCE_PREFIX_PROP
= "provisioning.ENFORCE_PREFIX";
/**
* Name of the UUID property.
*/
public static final String PROVISIONING_UUID_PROP
= "net.java.sip.communicator.UUID";
/**
* A reference to the ConfigurationService implementation instance that
* is currently registered with the bundle context.
*/
private static ConfigurationService configurationService = null;
/**
* A reference to the CredentialsStorageService implementation instance
* that is registered with the bundle context.
*/
private static CredentialsStorageService credentialsService = null;
/**
* A reference to the NetworkAddressManagerService implementation instance
* that is registered with the bundle context.
*/
private static NetworkAddressManagerService netaddrService = null;
/**
* The user interface service.
*/
private static UIService uiService;
/**
* The resource service.
*/
private static ResourceManagementService resourceService;
/**
* List of allowed configuration prefixes.
*/
private List<String> allowedPrefixes = new ArrayList<String>();
/**
* Starts this bundle
*
* @param bundleContext BundleContext
* @throws Exception if anything goes wrong during the start of the bundle
*/
public void start(BundleContext bundleContext) throws Exception
{
String url = null;
if (logger.isDebugEnabled())
logger.debug("Provisioning discovery [STARTED]");
ProvisioningActivator.bundleContext = bundleContext;
String uuid = (String)getConfigurationService().getProperty(
PROVISIONING_UUID_PROP);
if(uuid == null || uuid.equals(""))
{
uuid = UUID.randomUUID().toString();
getConfigurationService().setProperty(PROVISIONING_UUID_PROP, uuid);
}
Dictionary<String, String> properties = new Hashtable<String, String>();
properties.put( ConfigurationForm.FORM_TYPE,
ConfigurationForm.ADVANCED_TYPE);
bundleContext.registerService(
ConfigurationForm.class.getName(),
new LazyConfigurationForm(
"net.java.sip.communicator.plugin.provisioning.ProvisioningForm",
getClass().getClassLoader(),
"plugin.provisioning.PLUGIN_ICON",
"plugin.provisioning.PROVISIONING",
2000, true),
properties);
String method = getProvisioningMethod();
if(method == null || method.equals("NONE"))
{
return;
}
ServiceReference serviceReferences[] = bundleContext.
getServiceReferences(ProvisioningDiscoveryService.class.getName(),
null);
/* search the provisioning discovery implementation that correspond to
* the method name
*/
if(serviceReferences != null)
{
for(ServiceReference ref : serviceReferences)
{
ProvisioningDiscoveryService provdisc =
(ProvisioningDiscoveryService)bundleContext.getService(ref);
if(provdisc.getMethodName().equals(method))
{
/* may block for sometime depending on the method used */
url = provdisc.discoverURL();
break;
}
}
}
if(url == null)
{
/* try to see if provisioning URL is stored in properties */
url = getProvisioningUri();
}
if(url != null)
{
File file = retrieveConfigurationFile(url);
if(file != null)
{
updateConfiguration(file);
/* store the provisioning URL in local configuration in case
* the provisioning discovery failed (DHCP/DNS unavailable, ...)
*/
getConfigurationService().setProperty(
PROPERTY_PROVISIONING_URL, url);
}
}
if (logger.isDebugEnabled())
logger.debug("Provisioning discovery [REGISTERED]");
}
/**
* Stops this bundle
*
* @param bundleContext BundleContext
* @throws Exception if anything goes wrong during the stop of the bundle
*/
public void stop(BundleContext bundleContext) throws Exception
{
ProvisioningActivator.bundleContext = null;
if (logger.isDebugEnabled())
logger.debug("Provisioning discovery [STOPPED]");
}
/**
* Indicates if the provisioning has been enabled.
*
* @return <tt>true</tt> if the provisioning is enabled, <tt>false</tt> -
* otherwise
*/
public static String getProvisioningMethod()
{
String provMethod
= getConfigurationService().getString(PROVISIONING_METHOD_PROP);
if (provMethod == null || provMethod.length() <= 0)
{
provMethod = getResourceService().getSettingsString(
"plugin.provisioning.DEFAULT_PROVISIONING_METHOD");
if (provMethod != null && provMethod.length() > 0)
setProvisioningMethod(provMethod);
}
return provMethod;
}
/**
* Enables the provisioning with the given method. If the provisioningMethod
* is null disables the provisioning.
*
* @param provisioningMethod the provisioning method
*/
public static void setProvisioningMethod(String provisioningMethod)
{
getConfigurationService().setProperty(
PROVISIONING_METHOD_PROP, provisioningMethod);
}
/**
* Returns the provisioning URI.
*
* @return the provisioning URI
*/
public static String getProvisioningUri()
{
String provUri
= getConfigurationService().getString(PROPERTY_PROVISIONING_URL);
if (provUri == null || provUri.length() <= 0)
{
provUri = getResourceService().getSettingsString(
"plugin.provisioning.DEFAULT_PROVISIONING_URI");
if (provUri != null && provUri.length() > 0)
setProvisioningUri(provUri);
}
return provUri;
}
/**
* Sets the provisioning URI.
*
* @param uri the provisioning URI to set
*/
public static void setProvisioningUri(String uri)
{
getConfigurationService().setProperty(
PROPERTY_PROVISIONING_URL, uri);
}
/**
* Returns the <tt>UIService</tt> obtained from the bundle context.
*
* @return the <tt>UIService</tt> obtained from the bundle context
*/
public static UIService getUIService()
{
if (uiService == null)
{
ServiceReference uiReference =
bundleContext.getServiceReference(UIService.class.getName());
uiService =
(UIService) bundleContext
.getService(uiReference);
}
return uiService;
}
/**
* Returns the <tt>ResourceManagementService</tt> obtained from the
* bundle context.
*
* @return the <tt>ResourceManagementService</tt> obtained from the
* bundle context
*/
public static ResourceManagementService getResourceService()
{
if (resourceService == null)
{
ServiceReference resourceReference
= bundleContext.getServiceReference(
ResourceManagementService.class.getName());
resourceService =
(ResourceManagementService) bundleContext
.getService(resourceReference);
}
return resourceService;
}
/**
* Retrieve configuration file from provisioning URL.
* This method is blocking until configuration file is retrieved from the
* network or if an exception happen
*
* @param url provisioning URL
* @return provisioning file downloaded
*/
private File retrieveConfigurationFile(String url)
{
File tmpFile = null;
try
{
String arg = null;
String args[] = null;
final File temp = File.createTempFile("provisioning",
".properties");
tmpFile = temp;
URL u = new URL(url);
InetAddress ipaddr = getNetworkAddressManagerService().
getLocalHost(InetAddress.getByName(u.getHost()));
if(url.indexOf("${uuid}") != -1)
{
url = url.replace("${uuid}", (String)getConfigurationService()
.getProperty(PROVISIONING_UUID_PROP));
}
if(url.indexOf("${osname}") != -1)
{
url = url.replace("${osname}", System.getProperty("os.name"));
}
if(url.indexOf("${build}") != -1)
{
url = url.replace("${build}",
System.getProperty("sip-communicator.version"));
}
if(url.indexOf("${ipaddr}") != -1)
{
url = url.replace("${ipaddr}", ipaddr.getHostAddress());
}
if(url.indexOf("${hwaddr}") != -1)
{
if(ipaddr != null)
{
/* find the hardware address of the interface
* that has this IP address
*/
Enumeration<NetworkInterface> en =
NetworkInterface.getNetworkInterfaces();
while(en.hasMoreElements())
{
NetworkInterface iface = en.nextElement();
Enumeration<InetAddress> enInet =
iface.getInetAddresses();
while(enInet.hasMoreElements())
{
InetAddress inet = enInet.nextElement();
if(inet.equals(ipaddr))
{
byte hw[] =
getNetworkAddressManagerService().
getHardwareAddress(iface);
StringBuffer buf =
new StringBuffer();
for(byte h : hw)
{
int hi = h >= 0 ? h : h + 256;
String t = new String(
(hi <= 0xf) ? "0" : "");
t += Integer.toHexString(hi);
buf.append(t);
buf.append(":");
}
buf.deleteCharAt(buf.length() - 1);
url = url.replace("${hwaddr}",
buf.toString());
break;
}
}
}
}
}
if(url.contains("?"))
{
if((url.indexOf('?') + 1) != url.length())
{
arg = url.substring(url.indexOf('?') + 1);
args = arg.split("&");
}
url = url.substring(0, url.indexOf('?'));
}
String[] paramNames = null;
String[] paramValues = null;
int usernameIx = -1;
int passwordIx = -1;
if(args != null && args.length > 0)
{
paramNames = new String[args.length];
paramValues = new String[args.length];
for(int i = 0; i < args.length; i++)
{
String s = args[i];
if(s.startsWith("username="))
{
paramNames[i] = "username";
paramValues[i] = "";
usernameIx = i;
}
else if(s.startsWith("password="))
{
paramNames[i] = "password";
paramValues[i] = "";
passwordIx = i;
}
else if(s.startsWith("uuid="))
{
paramNames[i] = "uuid";
paramValues[i] = s.substring(s.indexOf("=") + 1);
}
else if(s.startsWith("osname="))
{
paramNames[i] = "osname";
paramValues[i] = s.substring(s.indexOf("=") + 1);
}
else if(s.startsWith("build="))
{
paramNames[i] = "build";
paramValues[i] = s.substring(s.indexOf("=") + 1);
}
else if(s.startsWith("ipaddr="))
{
paramNames[i] = "ipaddr";
paramValues[i] = s.substring(s.indexOf("=") + 1);
}
else if(s.startsWith("hwaddr="))
{
paramNames[i] = "hwaddr";
paramValues[i] = s.substring(s.indexOf("=") + 1);
}
else
{
paramNames[i] = "";
paramValues[i] = "";
}
}
}
HttpUtils.HTTPResponseResult res =
HttpUtils.postForm(
url,
PROPERTY_PROVISIONING_USERNAME,
PROPERTY_PROVISIONING_PASSWORD,
paramNames,
paramValues,
usernameIx,
passwordIx);
// if there was an error in retrieving stop
if(res == null)
return null;
InputStream in = res.getContent();
// Chain a ProgressMonitorInputStream to the
// URLConnection's InputStream
final ProgressMonitorInputStream pin
= new ProgressMonitorInputStream(null, u.toString(), in);
// Set the maximum value of the ProgressMonitor
ProgressMonitor pm = pin.getProgressMonitor();
pm.setMaximum((int)res.getContentLength());
final BufferedOutputStream bout
= new BufferedOutputStream(new FileOutputStream(temp));
try
{
int read = -1;
byte[] buff = new byte[1024];
while((read = pin.read(buff)) != -1)
{
bout.write(buff, 0, read);
}
pin.close();
bout.flush();
bout.close();
return temp;
}
catch (Exception e)
{
logger.error("Error saving", e);
try
{
pin.close();
bout.close();
}
catch (Exception e1)
{
}
return null;
}
}
catch (Exception e)
{
if (logger.isInfoEnabled())
logger.info("Error retrieving provisioning file!", e);
tmpFile.delete();
return null;
}
}
/**
* Update configuration with properties retrieved from provisioning URL.
*
* @param file provisioning file
*/
private void updateConfiguration(final File file)
{
Properties fileProps = new OrderedProperties();
InputStream in = null;
try
{
in = new BufferedInputStream(new FileInputStream(file));
fileProps.load(in);
Iterator<Map.Entry<Object, Object> > it
= fileProps.entrySet().iterator();
while(it.hasNext())
{
Map.Entry<Object, Object> entry = it.next();
String key = (String)entry.getKey();
Object value = entry.getValue();
if(key.equals(PROVISIONING_ALLOW_PREFIX_PROP))
{
String prefixes[] = ((String)value).split("\\|");
/* updates allowed prefixes list */
for(String s : prefixes)
{
allowedPrefixes.add(s);
}
continue;
}
else if(key.equals(PROVISIONING_ENFORCE_PREFIX_PROP))
{
checkEnforcePrefix((String)value);
continue;
}
/* check that properties is allowed */
if(!isPrefixAllowed(key))
{
continue;
}
processProperty(key, value);
}
try
{
/* save and reload the "new" configuration */
getConfigurationService().storeConfiguration();
getConfigurationService().reloadConfiguration();
}
catch(Exception e)
{
logger.error("Cannot reload configuration");
}
}
catch(IOException e)
{
logger.warn("Error during load of provisioning file");
}
finally
{
try
{
in.close();
file.delete();
}
catch(IOException e)
{
}
}
}
/**
* Check if a property name belongs to the allowed prefixes.
*
* @param key property key name
* @return true if key is allowed, false otherwise
*/
private boolean isPrefixAllowed(String key)
{
if(allowedPrefixes.size() > 0)
{
for(String s : allowedPrefixes)
{
if(key.startsWith(s))
{
return true;
}
}
/* current property prefix is not allowed */
return false;
}
else
{
/* no allowed prefixes configured so key is valid by default */
return true;
}
}
/**
* Process a new property. If value equals "${null}", it means to remove the
* property in the configuration service. If the key name end with
* "PASSWORD", its value is encrypted through credentials storage service,
* otherwise the property is added/updated in the configuration service.
*
* @param key property key name
* @param value property value
*/
private void processProperty(String key, Object value)
{
if((value instanceof String) && ((String)value).equals("${null}"))
{
getConfigurationService().removeProperty(key);
}
else if(key.endsWith(".PASSWORD"))
{
/* password => credentials storage service */
getCredentialsStorageService().storePassword(
key.substring(0, key.lastIndexOf(".")),
(String)value);
}
else
{
getConfigurationService().setProperty(key, value);
}
}
/**
* Walk through all properties and make sure all properties keys match
* a specific set of prefixes defined in configuration.
*
* @param enforcePrefix list of enforce prefix.
*/
private void checkEnforcePrefix(String enforcePrefix)
{
ConfigurationService config = getConfigurationService();
String prefixes[] = null;
if(enforcePrefix == null)
{
return;
}
/* must escape the | character */
prefixes = enforcePrefix.split("\\|");
/* get all properties */
for (String key : config.getAllPropertyNames())
{
boolean isValid = false;
for(String k : prefixes)
{
if(key.startsWith(k))
{
isValid = true;
break;
}
}
/* property name does is not in the enforce prefix list
* so remove it
*/
if(!isValid)
{
config.removeProperty(key);
}
}
}
/**
* Returns a reference to a ConfigurationService implementation currently
* registered in the bundle context or null if no such implementation was
* found.
*
* @return a currently valid implementation of the ConfigurationService.
*/
public static ConfigurationService getConfigurationService()
{
if (configurationService == null)
{
ServiceReference confReference
= bundleContext.getServiceReference(
ConfigurationService.class.getName());
configurationService
= (ConfigurationService)bundleContext.getService(confReference);
}
return configurationService;
}
/**
* Returns a reference to a CredentialsStorageService implementation
* currently registered in the bundle context or null if no such
* implementation was found.
*
* @return a currently valid implementation of the
* CredentialsStorageService.
*/
public static CredentialsStorageService getCredentialsStorageService()
{
if (credentialsService == null)
{
ServiceReference credentialsReference
= bundleContext.getServiceReference(
CredentialsStorageService.class.getName());
credentialsService
= (CredentialsStorageService) bundleContext
.getService(credentialsReference);
}
return credentialsService;
}
/**
* Returns a reference to a NetworkAddressManagerService implementation
* currently registered in the bundle context or null if no such
* implementation was found.
*
* @return a currently valid implementation of the
* NetworkAddressManagerService.
*/
public static NetworkAddressManagerService getNetworkAddressManagerService()
{
if (netaddrService == null)
{
ServiceReference netaddrReference
= bundleContext.getServiceReference(
NetworkAddressManagerService.class.getName());
netaddrService
= (NetworkAddressManagerService) bundleContext
.getService(netaddrReference);
}
return netaddrService;
}
}
|
package org.ensembl.healthcheck.testcase.generic;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
/**
* Base class to compare a certain set of things (e.g. biotypes, xrefs) from one database with the equivalent things in the previous
* database.
*
* Extending classes should implement the description, threshold and getCounts() methods. See individual Javadocs for details.
*/
public abstract class ComparePreviousVersionBase extends SingleDatabaseTestCase {
/**
* Run the test.
*
* @param dbre
* The database to use.
* @return true if the test passed.
*
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
if (System.getProperty("ignore.previous.checks") != null) {
logger.finest("ignore.previous.checks is set in database.properties, skipping this test");
return true;
}
DatabaseRegistryEntry sec = getEquivalentFromSecondaryServer(dbre);
if (sec == null) {
logger.warning("Can't get equivalent database for " + dbre.getName());
return true;
}
logger.finest("Equivalent database on secondary server is " + sec.getName());
Map currentCounts = getCounts(dbre);
Map secondaryCounts = getCounts(sec);
// compare each of the secondary (previous release, probably) with current
Set externalDBs = secondaryCounts.keySet();
Iterator it = externalDBs.iterator();
String successText = "";
// show % tolerance here?
double tolerance = (100 - ((threshold() / 1) * 100));
if (testUpperThreshold()) {
successText = " - within tolerance +/-" + tolerance + "%";
} else {
successText = " - greater or within tolerance";
}
while (it.hasNext()) {
String key = (String) it.next();
int secondaryCount = ((Integer) (secondaryCounts.get(key))).intValue();
if (secondaryCount == 0) {
continue;
}
// check it exists at all
if (currentCounts.containsKey(key)) {
int currentCount = ((Integer) (currentCounts.get(key))).intValue();
if (((double) currentCount / (double) secondaryCount) < threshold()) {
ReportManager.problem(this, dbre.getConnection(), sec.getName() + " has " + secondaryCount + " " + entityDescription() + " " + key + " but " + dbre.getName() + " only has " + currentCount);
result = false;
} else if (testUpperThreshold() &&
// ((1 -(double) secondaryCount / (double) currentCount)) > threshold()) {
(((double) currentCount / (double) secondaryCount)) > (1 / threshold())) {
ReportManager.problem(this, dbre.getConnection(), sec.getName() + " only has " + secondaryCount + " " + entityDescription() + " " + key + " but " + dbre.getName() + " has " + currentCount);
result = false;
} else {
ReportManager.correct(this, dbre.getConnection(), sec.getName() + " has " + secondaryCount + " " + entityDescription() + " " + key + " and " + dbre.getName() + " has " + currentCount
+ successText);
}
} else {
ReportManager.problem(this, dbre.getConnection(), sec.getName() + " has " + secondaryCount + " " + entityDescription() + " " + key + " but " + dbre.getName() + " has none");
result = false;
}
}
return result;
} // run
protected Map<String, Integer> getCountsBySQL(DatabaseRegistryEntry dbre, String sql) {
Map<String, Integer> result = new HashMap<String, Integer>();
try {
Statement stmt = dbre.getConnection().createStatement();
logger.finest("Getting " + entityDescription() + " counts for " + dbre.getName());
ResultSet rs = stmt.executeQuery(sql);
while (rs != null && rs.next()) {
result.put(rs.getString(1), rs.getInt(2));
logger.finest(rs.getString(1) + " " + rs.getInt(2));
}
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
/**
* Should return a map where the keys are the names of the entities being tested (e.g. biotypes) and the values are the counts of
* each type.
*/
protected abstract Map getCounts(DatabaseRegistryEntry dbre);
/**
* Should return a description of what's being tested.
*/
protected abstract String entityDescription();
/**
* Should return the fraction (0-1) of old/new below which a warning is generated.
*/
protected abstract double threshold();
protected boolean testUpperThreshold() {
return false;
}
} // ComparePreviousVersionBase
|
package de.terrestris.shogun2.util.http;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import de.terrestris.shogun2.util.model.Response;
/**
*
* @author Daniel Koch
* @author Andre Henn
* @author terrestris GmbH & Co. KG
*
*/
@Component
public class HttpUtil {
/**
* The Logger.
*/
private static final Logger LOG = Logger.getLogger(HttpUtil.class);
/**
* The timeout for all outgoing HTTP connections.
*/
private static int httpTimeout;
/**
* Performs an HTTP GET on the given URL <i>without authentication</i>
*
* @param url The URL to connect to.
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response get(String url) throws URISyntaxException, HttpException {
return send(new HttpGet(url), null, null);
}
/**
* Performs an HTTP GET on the given URL <i>without authentication</i> and
* additional HTTP request headers.
*
* @param url The URL to connect to.
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response get(String url, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return send(new HttpGet(url), null, requestHeaders);
}
/**
* Performs an HTTP GET on the given URL.
*
* @param url The URL to connect to.
* @param credentials instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response get(String url, Credentials credentials)
throws URISyntaxException, HttpException {
return send(new HttpGet(url), credentials, null);
}
/**
* Performs an HTTP GET on the given URL.
*
* @param url The URL to connect to.
* @param credentials instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response get(String url, Credentials credentials, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return send(new HttpGet(url), credentials, requestHeaders);
}
/**
* Performs an HTTP GET on the given URL
*
* @param url The URL to connect to.
* @param username Credentials - username
* @param password Credentials - password
* @throws HttpException
* @throws URISyntaxException
*/
public static Response get(String url, String username, String password) throws URISyntaxException, HttpException {
return send(new HttpGet(url), new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP GET on the given URL
*
* @param url The URL to connect to.
* @param username Credentials - username
* @param password Credentials - password
* @param requestHeaders Additional HTTP headers added to the request
*
* @throws HttpException
* @throws URISyntaxException
*/
public static Response get(String url, String username, String password, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return send(new HttpGet(url), new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Performs an HTTP GET on the given URI.
* No credentials needed.
*
* @param uri The URI to connect to.
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response get(URI uri) throws URISyntaxException, HttpException {
return send(new HttpGet(uri), null, null);
}
/**
* Performs an HTTP GET on the given URI.
* No credentials needed.
*
* @param uri The URI to connect to.
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response get(URI uri, Header[] requestHeaders) throws URISyntaxException, HttpException {
return send(new HttpGet(uri), null, requestHeaders);
}
/**
* Performs an HTTP GET on the given URI.
* Basic auth is used if both username and password are not null.
*
* @param uri The URI to connect to.
* @param username Credentials - username
* @param password Credentials - password
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response get(URI uri, String username, String password)
throws URISyntaxException, HttpException {
return send(new HttpGet(uri), new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP GET on the given URI.
* Basic auth is used if both username and password are not null.
*
* @param uri The URI to connect to.
* @param username Credentials - username
* @param password Credentials - password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response get(URI uri, String username, String password, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return send(new HttpGet(uri), new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Performs an HTTP GET on the given URI.
* Basic auth is used if both username and pw are not null.
*
* @param uri The URI to connect to.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response get(URI uri, Credentials credentials)
throws URISyntaxException, HttpException {
return send(new HttpGet(uri), credentials, null);
}
/**
* Performs an HTTP GET on the given URI.
* Basic auth is used if both username and pw are not null.
*
* @param uri The URI to connect to.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response get(URI uri, Credentials credentials, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return send(new HttpGet(uri), credentials, requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param url The URL to connect to.
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(String url)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), new ArrayList<NameValuePair>(), null, null);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param url The URL to connect to.
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(String url, Header[] requestHeaders)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), new ArrayList<NameValuePair>(), null, requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if both and password are not null.
*
* @param uri The URI to connect to.
* @param username Credentials - username
* @param password Credentials - password
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(String url, String password, String username)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), new ArrayList<NameValuePair>(), new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if both and password are not null.
*
* @param uri The URI to connect to.
* @param username Credentials - username
* @param password Credentials - password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(String url, String password, String username, Header[] requestHeaders)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), new ArrayList<NameValuePair>(), new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if credentials object is not null
*
* @param url The URL to connect to.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(String url, Credentials credentials)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), new ArrayList<NameValuePair>(), credentials, null);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if credentials object is not null
*
* @param url The URL to connect to.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(String url, Credentials credentials, Header[] requestHeaders)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), new ArrayList<NameValuePair>(), credentials,requestHeaders);
}
/**
* Performs an HTTP POST on the given URI.
*
* @param uri The URI to connect to.
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(URI uri)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), new ArrayList<NameValuePair>(), null, null);
}
/**
* Performs an HTTP POST on the given URI.
*
* @param uri The URI to connect to.
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(URI uri, Header[] requestHeaders)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), new ArrayList<NameValuePair>(), null, requestHeaders);
}
/**
* Performs an HTTP POST on the given URI.
* Basic auth is used if both and password are not null.
*
* @param uri The URI to connect to.
* @param username Credentials - username
* @param password Credentials - password
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(URI uri, String username, String password)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), new ArrayList<NameValuePair>(), new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP POST on the given URI.
* Basic auth is used if both and password are not null.
*
* @param uri The URI to connect to.
* @param username Credentials - username
* @param password Credentials - password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(URI uri, String username, String password, Header[] requestHeaders)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), new ArrayList<NameValuePair>(), new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Performs an HTTP POST on the given URI.
* Basic auth is used if credentials object is not null
*
* @param uri The URI to connect to.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(URI uri, Credentials credentials)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), new ArrayList<NameValuePair>(), credentials, null);
}
/**
* Performs an HTTP POST on the given URI.
* Basic auth is used if credentials object is not null
*
* @param uri The URI to connect to.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(URI uri, Credentials credentials, Header[] requestHeaders)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), new ArrayList<NameValuePair>(), credentials, requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param url The URL to connect to.
* @param queryParams The list of NameValuePairs.
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(String url, List<NameValuePair> queryParams)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), queryParams, null, null);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param url The URL to connect to.
* @param queryParams The list of NameValuePairs.
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(String url, List<NameValuePair> queryParams, Header[] requestHeaders)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), queryParams, null, requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if both and password are not null.
*
* @param url The URL to connect to.
* @param queryParams The list of NameValuePairs.
* @param username Credentials - username
* @param password Credentials - password
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(String url, List<NameValuePair> queryParams, String username, String password) throws URISyntaxException,
UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), queryParams, new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if both and password are not null.
*
* @param url The URL to connect to.
* @param queryParams The list of NameValuePairs.
* @param username Credentials - username
* @param password Credentials - password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(String url, List<NameValuePair> queryParams, String username, String password, Header[] requestHeaders) throws URISyntaxException,
UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), queryParams, new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param url The URL to connect to.
* @param queryParams The list of NameValuePairs.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(String url, List<NameValuePair> queryParams, Credentials credentials) throws URISyntaxException,
UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), queryParams, credentials, null);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param url The URL to connect to.
* @param queryParams The list of NameValuePairs.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(String url, List<NameValuePair> queryParams, Credentials credentials, Header[] requestHeaders) throws URISyntaxException,
UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), queryParams, credentials, requestHeaders);
}
/**
* Performs an HTTP POST on the given URI.
*
* @param uri The URI to connect to.
* @param queryParams The list of NameValuePairs.
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(URI uri, List<NameValuePair> queryParams)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), queryParams, null, null);
}
/**
* Performs an HTTP POST on the given URI.
*
* @param uri The URI to connect to.
* @param queryParams The list of NameValuePairs.
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(URI uri, List<NameValuePair> queryParams, Header[] requestHeaders)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), queryParams, null, requestHeaders);
}
/**
* Performs an HTTP POST on the given URI.
* Basic auth is used if both and password are not null.
*
* @param uri The URI to connect to.
* @param queryParams The list of NameValuePairs.
* @param username Credentials - username
* @param password Credentials - password
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(URI uri, List<NameValuePair> queryParams, String username, String password) throws URISyntaxException,
UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), queryParams, new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP POST on the given URI.
* Basic auth is used if both and password are not null.
*
* @param uri The URI to connect to.
* @param queryParams The list of NameValuePairs.
* @param username Credentials - username
* @param password Credentials - password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(URI uri, List<NameValuePair> queryParams, String username, String password, Header[] requestHeaders) throws URISyntaxException,
UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), queryParams, new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Performs an HTTP POST on the given URI.
*
* @param uri The URI to connect to.
* @param queryParams The list of NameValuePairs.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(URI uri, List<NameValuePair> queryParams, Credentials credentials) throws URISyntaxException,
UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), queryParams, credentials, null);
}
/**
* Performs an HTTP POST on the given URI.
*
* @param uri The URI to connect to.
* @param queryParams The list of NameValuePairs.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
public static Response post(URI uri, List<NameValuePair> queryParams, Credentials credentials, Header[] requestHeaders) throws URISyntaxException,
UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), queryParams, credentials, requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param url The URL to connect to.
* @param body The POST body.
* @param contentType The ContentType of the POST body.
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(String url, String body, ContentType contentType)
throws URISyntaxException, HttpException {
return postBody(new HttpPost(url), body, contentType, null, null);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param url The URL to connect to.
* @param body The POST body.
* @param contentType The ContentType of the POST body.
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(String url, String body, ContentType contentType, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return postBody(new HttpPost(url), body, contentType, null, requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used is both username and password are not null
*
* @param url The URL to connect to.
* @param body The POST body.
* @param contentType The ContentType of the POST body
* @param username Credentials - username
* @param password Credentials - password
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(String url, String body, ContentType contentType, String username, String password) throws URISyntaxException, HttpException {
return postBody(new HttpPost(url), body, contentType, new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used is both username and password are not null
*
* @param url The URL to connect to.
* @param body The POST body.
* @param contentType The ContentType of the POST body
* @param username Credentials - username
* @param password Credentials - password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(String url, String body, ContentType contentType, String username, String password, Header[] requestHeaders) throws URISyntaxException, HttpException {
return postBody(new HttpPost(url), body, contentType, new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param url The URL to connect to.
* @param body The POST body.
* @param contentType The ContentType of the POST body.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(String url, String body, ContentType contentType,
Credentials credentials) throws URISyntaxException, HttpException {
return postBody(new HttpPost(url), body, contentType, credentials, null);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param url The URL to connect to.
* @param body The POST body.
* @param contentType The ContentType of the POST body.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(String url, String body, ContentType contentType,
Credentials credentials, Header[] requestHeaders) throws URISyntaxException, HttpException {
return postBody(new HttpPost(url), body, contentType, credentials, requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param uri The URI to connect to.
* @param body The POST body.
* @param contentType The ContentType of the POST body.
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
* @throws UnsupportedEncodingException
*/
public static Response post(URI uri, String body, ContentType contentType)
throws URISyntaxException, HttpException {
return postBody(new HttpPost(uri), body, contentType, null, null);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param uri The URI to connect to.
* @param body The POST body.
* @param contentType The ContentType of the POST body.
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
* @throws UnsupportedEncodingException
*/
public static Response post(URI uri, String body, ContentType contentType, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return postBody(new HttpPost(uri), body, contentType, null, requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if both username and password are not null
*
* @param uri The URI to connect to.
* @param body The POST body.
* @param contentType The ContentType of the POST body.
* @param username Credentials - username
* @param password Credentials - password
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(URI uri, String body, ContentType contentType,
String username, String password) throws URISyntaxException, HttpException {
return postBody(new HttpPost(uri), body, contentType, new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if both username and password are not null
*
* @param uri The URI to connect to.
* @param body The POST body.
* @param contentType The ContentType of the POST body.
* @param username Credentials - username
* @param password Credentials - password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(URI uri, String body, ContentType contentType,
String username, String password, Header[] requestHeaders) throws URISyntaxException, HttpException {
return postBody(new HttpPost(uri), body, contentType, new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param uri The URI to connect to.
* @param body The POST body.
* @param contentType The ContentType of the POST body.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(URI uri, String body, ContentType contentType,
Credentials credentials) throws URISyntaxException, HttpException {
return postBody(new HttpPost(uri), body, contentType, credentials, null);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param uri The URI to connect to.
* @param body The POST body.
* @param contentType The ContentType of the POST body.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(URI uri, String body, ContentType contentType,
Credentials credentials, Header[] requestHeaders) throws URISyntaxException, HttpException {
return postBody(new HttpPost(uri), body, contentType, credentials, requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param url The URL to connect to.
* @param file The file to send as MultiPartFile.
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(String url, File file) throws URISyntaxException, HttpException {
return postMultiPart(new HttpPost(url), new FileBody(file), null, null);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param url The URL to connect to.
* @param file The file to send as MultiPartFile.
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(String url, File file, Header[] requestHeaders) throws URISyntaxException, HttpException {
return postMultiPart(new HttpPost(url), new FileBody(file), null, requestHeaders);
}
/**
*
* Performs an HTTP POST on the given URL.
* Basic auth is used if both username and password are not null
*
* @param url The URL to connect to.
* @param file The file to send as MultiPartFile.
* @param username username
* @param password password
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(String url, File file, String username, String password) throws URISyntaxException, HttpException {
return postMultiPart(new HttpPost(url), new FileBody(file), new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if both username and password are not null
*
* @param url The URL to connect to.
* @param file The file to send as MultiPartFile.
* @param username username
* @param password password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(String url, File file, String username, String password, Header[] requestHeaders) throws URISyntaxException, HttpException {
return postMultiPart(new HttpPost(url), new FileBody(file), new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
*
* Performs an HTTP POST on the given URL.
* Basic auth is used if credentials object is not null.
*
* @param url The URL to connect to.
* @param file The file to send as MultiPartFile.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(String url, File file, Credentials credentials) throws URISyntaxException, HttpException {
return postMultiPart(new HttpPost(url), new FileBody(file), credentials, null);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if credentials object is not null.
*
* @param url The URL to connect to.
* @param file The file to send as MultiPartFile.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(String url, File file, Credentials credentials, Header[] requestHeaders) throws URISyntaxException, HttpException {
return postMultiPart(new HttpPost(url), new FileBody(file), credentials, requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param uri The URI to connect to.
* @param file The file to send as MultiPartFile.
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(URI uri, File file) throws URISyntaxException, HttpException {
return postMultiPart(new HttpPost(uri), new FileBody(file), null, null);
}
/**
* Performs an HTTP POST on the given URL.
*
* @param uri The URI to connect to.
* @param file The file to send as MultiPartFile.
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(URI uri, File file, Header[] requestHeaders) throws URISyntaxException, HttpException {
return postMultiPart(new HttpPost(uri), new FileBody(file), null, requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if both username and password are not null.
*
* @param uri The URI to connect to.
* @param file The file to send as MultiPartFile.
* @param username username
* @param password password
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(URI uri, File file, String username, String password) throws URISyntaxException, HttpException {
return postMultiPart(new HttpPost(uri), new FileBody(file), new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if both username and password are not null.
*
* @param uri The URI to connect to.
* @param file The file to send as MultiPartFile.
* @param username username
* @param password password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(URI uri, File file, String username, String password, Header[] requestHeaders) throws URISyntaxException, HttpException {
return postMultiPart(new HttpPost(uri), new FileBody(file), new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if credentials object is not null.
*
* @param uri The URI to connect to.
* @param file The file to send as MultiPartFile.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(URI uri, File file, Credentials credentials) throws URISyntaxException, HttpException {
return postMultiPart(new HttpPost(uri), new FileBody(file), credentials, null);
}
/**
* Performs an HTTP POST on the given URL.
* Basic auth is used if credentials object is not null.
*
* @param uri The URI to connect to.
* @param file The file to send as MultiPartFile.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response post(URI uri, File file, Credentials credentials, Header[] requestHeaders) throws URISyntaxException, HttpException {
return postMultiPart(new HttpPost(uri), new FileBody(file), credentials, requestHeaders);
}
/**
*
* @param httpRequest
* @param file
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
private static Response postMultiPart(HttpPost httpRequest, FileBody file, Credentials credentials, Header[] requestHeaders) throws URISyntaxException, HttpException {
HttpEntity multiPartEntity = MultipartEntityBuilder.create()
.addPart("file", file)
.build();
httpRequest.setEntity(multiPartEntity);
return send(httpRequest, credentials, requestHeaders);
}
/**
*
* @param httpRequest
* @param body
* @param contentType
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
private static Response postBody(HttpPost httpRequest, String body, ContentType contentType, Credentials credentials, Header[] requestHeaders)
throws URISyntaxException, HttpException {
StringEntity stringEntity = new StringEntity(body, contentType);
stringEntity.setChunked(true);
httpRequest.setEntity(stringEntity);
return send(httpRequest, credentials, requestHeaders);
}
/**
*
* @param httpRequest
* @param queryParams
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws UnsupportedEncodingException
* @throws HttpException
*/
private static Response postParams(HttpPost httpRequest, List<NameValuePair> queryParams, Credentials credentials, Header[] requestHeaders)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
if (!queryParams.isEmpty()) {
HttpEntity httpEntity = new UrlEncodedFormEntity(queryParams);
httpRequest.setEntity(httpEntity);
}
return send(httpRequest, credentials, requestHeaders);
}
/**
* Perform HTTP PUT with empty body
*
* @param uri
* @return
* @throws HttpException
* @throws URISyntaxException
*/
public static Response put(URI uri) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uri), null, null, null, null);
}
/**
* Perform HTTP PUT with empty body
*
* @param uri
* @param requestHeaders Additional HTTP headers added to the request
* @return
* @throws HttpException
* @throws URISyntaxException
*/
public static Response put(URI uri, Header[] requestHeaders) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uri), null, null, null, requestHeaders);
}
/**
* Perform HTTP PUT with empty body
*
* @param uriString
* @return
* @throws HttpException
* @throws URISyntaxException
*/
public static Response put(String uriString) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uriString), null, null, null, null);
}
/**
* Perform HTTP PUT with empty body
*
* @param uriString
* @param requestHeaders Additional HTTP headers added to the request
* @return
* @throws HttpException
* @throws URISyntaxException
*/
public static Response put(String uriString, Header[] requestHeaders) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uriString), null, null, null, requestHeaders);
}
/**
* Perform HTTP PUT with empty body
* Basic auth will be used if both username and password are not null
*
* @param uri URI to connect to
* @param username username
* @param password password
*
* @return
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(URI uri, String username, String password) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uri), null, null, new UsernamePasswordCredentials(username, password), null);
}
/**
* Perform HTTP PUT with empty body
* Basic auth will be used if both username and password are not null
*
* @param uri URI to connect to
* @param username username
* @param password password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(URI uri, String username, String password, Header[] requestHeaders) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uri), null, null, new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Perform HTTP PUT with empty body
*
* @param uri URI to connect to
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(URI uri, Credentials credentials) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uri), null, null, credentials, null);
}
/**
* Perform HTTP PUT with empty body
*
* @param uri URI to connect to
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(URI uri, Credentials credentials, Header[] requestHeaders) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uri), null, null, credentials, requestHeaders);
}
/**
* Perform HTTP PUT with empty body
*
* @param uriString String representing the URI to connect to
* @param username username
* @param password password
*
* @return
* @throws HttpException
* @throws URISyntaxException
*/
public static Response put(String uriString, String username, String password) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uriString), null, null, new UsernamePasswordCredentials(username, password), null);
}
/**
* Perform HTTP PUT with empty body
*
* @param uriString String representing the URI to connect to
* @param username username
* @param password password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return
* @throws HttpException
* @throws URISyntaxException
*/
public static Response put(String uriString, String username, String password, Header[] requestHeaders) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uriString), null, null, new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Perform HTTP PUT with empty body
*
* @param uriString String representing the URI to connect to
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return
* @throws HttpException
* @throws URISyntaxException
*/
public static Response put(String uriString, Credentials credentials) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uriString), null, null, credentials, null);
}
/**
* Perform HTTP PUT with empty body
*
* @param uriString String representing the URI to connect to
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return
* @throws HttpException
* @throws URISyntaxException
*/
public static Response put(String uriString, Credentials credentials, Header[] requestHeaders) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uriString), null, null, credentials, requestHeaders);
}
/**
* Performs an HTTP PUT on the given URL.
* (without BasicAuth)
*
* @param uriString String representing the URI to connect to
* @param body
* @param contentType
*
* @return
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(String uriString, String body, ContentType contentType) throws URISyntaxException, HttpException{
return putBody(new HttpPut(uriString), body, contentType, null, null);
}
/**
* Performs an HTTP PUT on the given URL.
* (without BasicAuth)
*
* @param uriString String representing the URI to connect to
* @param body
* @param contentType
* @param requestHeaders Additional HTTP headers added to the request
*
* @return
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(String uriString, String body, ContentType contentType, Header[] requestHeaders) throws URISyntaxException, HttpException{
return putBody(new HttpPut(uriString), body, contentType, null, requestHeaders);
}
/**
* Performs an HTTP PUT on the given URL.
*
* @param uriString String representing the URI to connect to
* @param body
* @param contentType
* @param username
* @param password
*
* @return
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(String uriString, String body, ContentType contentType, String username, String password) throws URISyntaxException, HttpException{
return putBody(new HttpPut(uriString), body, contentType, new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP PUT on the given URL.
*
* @param uriString String representing the URI to connect to
* @param body
* @param contentType
* @param username
* @param password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(String uriString, String body, ContentType contentType, String username, String password, Header[] requestHeaders) throws URISyntaxException, HttpException{
return putBody(new HttpPut(uriString), body, contentType, new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Performs an HTTP PUT on the given URL.
*
* @param uriString
* @param body
* @param contentType
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(String uriString, String body, ContentType contentType, Credentials credentials) throws URISyntaxException, HttpException{
return putBody(new HttpPut(uriString), body, contentType, credentials, null);
}
/**
* Performs an HTTP PUT on the given URL.
*
* @param uriString
* @param body
* @param contentType
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(String uriString, String body, ContentType contentType, Credentials credentials, Header[] requestHeaders) throws URISyntaxException, HttpException{
return putBody(new HttpPut(uriString), body, contentType, credentials, requestHeaders);
}
/**
* Performs an HTTP PUT on the given URL.
* without BasicAuth
*
* @param uri
* @param body
* @param contentType
* @return
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(URI uri, String body, ContentType contentType) throws URISyntaxException, HttpException{
return putBody(new HttpPut(uri), body, contentType, null, null);
}
/**
* Performs an HTTP PUT on the given URL.
* without BasicAuth
*
* @param uri
* @param body
* @param contentType
* @param requestHeaders Additional HTTP headers added to the request
* @return
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(URI uri, String body, ContentType contentType, Header[] requestHeaders) throws URISyntaxException, HttpException{
return putBody(new HttpPut(uri), body, contentType, null, requestHeaders);
}
/**
* Performs an HTTP PUT on the given URL.
*
* @param uri
* @param body
* @param contentType
* @param username
* @param password
* @return
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(URI uri, String body, ContentType contentType, String username, String password) throws URISyntaxException, HttpException{
return putBody(new HttpPut(uri), body, contentType, new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP PUT on the given URL.
*
* @param uri
* @param body
* @param contentType
* @param username
* @param password
* @param requestHeaders Additional HTTP headers added to the request
* @return
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(URI uri, String body, ContentType contentType, String username, String password, Header[] requestHeaders) throws URISyntaxException, HttpException{
return putBody(new HttpPut(uri), body, contentType, new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Performs an HTTP PUT on the given URL.
*
* @param uri
* @param body
* @param contentType
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(URI uri, String body, ContentType contentType, Credentials credentials) throws URISyntaxException, HttpException{
return putBody(new HttpPut(uri), body, contentType, credentials, null);
}
/**
* Performs an HTTP PUT on the given URL.
*
* @param uri
* @param body
* @param contentType
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
* @throws URISyntaxException
* @throws HttpException
*/
public static Response put(URI uri, String body, ContentType contentType, Credentials credentials, Header[] requestHeaders) throws URISyntaxException, HttpException{
return putBody(new HttpPut(uri), body, contentType, credentials, requestHeaders);
}
/**
* Performs an HTTP DELETE on the given URL.
*
* @param url The URL to connect to.
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response delete(String url) throws URISyntaxException, HttpException {
return send(new HttpDelete(url), null, null);
}
/**
* Performs an HTTP DELETE on the given URL.
*
* @param url The URL to connect to.
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response delete(String url, Header[] requestHeaders) throws URISyntaxException, HttpException {
return send(new HttpDelete(url), null, requestHeaders);
}
/**
* Performs an HTTP DELETE on the given URL.
*
* @param url The URL to connect to.
* @param username username
* @param password password
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response delete(String url, String username, String password)
throws URISyntaxException, HttpException {
return send(new HttpDelete(url), new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP DELETE on the given URL.
*
* @param url The URL to connect to.
* @param username username
* @param password password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response delete(String url, String username, String password, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return send(new HttpDelete(url), new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Performs an HTTP DELETE on the given URL.
*
* @param url The URL to connect to.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response delete(String url, Credentials credentials)
throws URISyntaxException, HttpException {
return send(new HttpDelete(url), credentials, null);
}
/**
* Performs an HTTP DELETE on the given URL.
*
* @param url The URL to connect to.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response delete(String url, Credentials credentials, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return send(new HttpDelete(url), credentials, requestHeaders);
}
/**
* Performs an HTTP DELETE on the given URI.
*
* @param uri The URI to connect to.
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response delete(URI uri) throws URISyntaxException, HttpException {
return send(new HttpDelete(uri), null, null);
}
/**
* Performs an HTTP DELETE on the given URI.
*
* @param uri The URI to connect to.
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response delete(URI uri, Header[] requestHeaders) throws URISyntaxException, HttpException {
return send(new HttpDelete(uri), null, requestHeaders);
}
/**
* Performs an HTTP DELETE on the given URI.
* Basic auth is used if both username and pw are not null.
*
* @param uri The URI to connect to.
* @param username username
* @param password password
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response delete(URI uri, String username, String password) throws URISyntaxException, HttpException {
return send(new HttpDelete(uri), new UsernamePasswordCredentials(username, password), null);
}
/**
* Performs an HTTP DELETE on the given URI.
* Basic auth is used if both username and pw are not null.
*
* @param uri The URI to connect to.
* @param username username
* @param password password
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response delete(URI uri, String username, String password, Header[] requestHeaders) throws URISyntaxException, HttpException {
return send(new HttpDelete(uri), new UsernamePasswordCredentials(username, password), requestHeaders);
}
/**
* Performs an HTTP DELETE on the given URI.
* Basic auth is used if both username and pw are not null.
*
* @param uri The URI to connect to.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response delete(URI uri, Credentials credentials)
throws URISyntaxException, HttpException {
return send(new HttpDelete(uri), credentials, null);
}
/**
* Performs an HTTP DELETE on the given URI.
* Basic auth is used if both username and pw are not null.
*
* @param uri The URI to connect to.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
public static Response delete(URI uri, Credentials credentials, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return send(new HttpDelete(uri), credentials, requestHeaders);
}
/**
*
* @param httpRequest
* @param body
* @param contentType
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
* @throws URISyntaxException
* @throws HttpException
*/
private static Response putBody(HttpPut httpRequest, String body, ContentType contentType, Credentials credentials, Header[] requestHeaders) throws URISyntaxException, HttpException {
if (contentType != null && !StringUtils.isEmpty(body)) {
StringEntity stringEntity = new StringEntity(body, contentType);
stringEntity.setChunked(true);
httpRequest.setEntity(stringEntity);
}
return send(httpRequest, credentials, requestHeaders);
}
/**
* Performs an HTTP operation on the given URL.
* Basic auth is used if both username and pw are not null.
*
* @param httpRequest The HttpRequest to connect to.
* @param credentials Instance implementing {@link Credentials} interface holding a set of credentials
* @param requestHeaders Additional HTTP headers added to the request
*
* @return The HTTP response as Response object.
*
* @throws URISyntaxException
* @throws HttpException
*/
private static Response send(HttpRequestBase httpRequest, Credentials credentials,
Header[] requestHeaders) throws URISyntaxException, HttpException {
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
Response response = new Response();
HttpClientContext httpContext = HttpClientContext.create();
URI uri = httpRequest.getURI();
HttpHost systemProxy = null;
try {
systemProxy = getSystemProxy(uri);
} catch (UnknownHostException e) {
LOG.error("Error while detecting system wide proxy: " + e.getMessage());
}
// set the request configuration that will passed to the httpRequest
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(httpTimeout)
.setConnectTimeout(httpTimeout)
.setSocketTimeout(httpTimeout)
.setProxy(systemProxy)
.build();
// set (preemptive) authentication if credentials are given
if (credentials != null) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
credentials
);
HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(),
uri.getScheme());
AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
httpContext.setCredentialsProvider(credentialsProvider);
httpContext.setAuthCache(authCache);
httpClient = HttpClients.custom()
// TODO Temporarily workaround!
.disableContentCompression()
.setDefaultCredentialsProvider(credentialsProvider)
.build();
} else {
httpClient = HttpClients.createDefault();
}
try {
HttpHeaders headersMap = new HttpHeaders();
httpRequest.setConfig(requestConfig);
// apply HTTP header
if (requestHeaders != null) {
httpRequest.setHeaders(requestHeaders);
}
httpResponse = httpClient.execute(httpRequest, httpContext);
HttpStatus httpStatus = HttpStatus.valueOf(
httpResponse.getStatusLine().getStatusCode());
Header[] headers = httpResponse.getAllHeaders();
HttpEntity httpResponseEntity = httpResponse.getEntity();
response.setStatusCode(httpStatus);
for (Header header : headers) {
if (header.getName().equalsIgnoreCase("Transfer-Encoding") &&
header.getValue().equalsIgnoreCase("chunked")) {
LOG.debug("Removed the header 'Transfer-Encoding:chunked'" +
" from a response, as its handled by the http-client");
} else {
headersMap.set(header.getName(), header.getValue());
}
}
response.setHeaders(headersMap);
if (httpResponseEntity != null) {
response.setBody(EntityUtils.toByteArray(httpResponseEntity));
}
} catch (IOException e) {
throw new HttpException("Error while getting a response from " + uri +
": " + e.getMessage());
} finally {
// cleanup
httpRequest.reset();
IOUtils.closeQuietly(httpResponse);
IOUtils.closeQuietly(httpClient);
}
return response;
}
/**
* If the JVM knows about a HTTP proxy, e.g. by specifying
*
* <pre>
* -Dhttp.proxyHost=schwatzgelb.de -Dhttp.proxyPort=8080
* </pre>
*
* as startup parameters, this method will correctly detect them and return
* an InetSocketAddress ready to be used to pass the proxy to the
* DefaultHttpClient.
*
* @param url
* @return
* @throws UnknownHostException
*/
private static HttpHost getSystemProxy(URI uri) throws UnknownHostException {
// We do not set the java.net.useSystemProxies property here as it may
// lead to problems in certain scenarios, e.g. when testing with OpenJDK
// on VMs with an insufficient dependency management (see the failing
// If it is necessary that this property is set to true, it should be
// configured on the JVM via -Djava.net.useSystemProxies=true
// System.setProperty("java.net.useSystemProxies", "true");
HttpHost systemProxy = null;
List<Proxy> proxyList = ProxySelector.getDefault().select(uri);
for (Iterator<Proxy> iterator = proxyList.iterator(); iterator.hasNext();) {
Proxy proxy = iterator.next();
InetSocketAddress address = (InetSocketAddress) proxy.address();
if (address != null) {
LOG.debug("Detected a system wide proxy: " +
" * Host: " + address.getHostName() +
" * Port: " + address.getPort()
);
systemProxy = new HttpHost(InetAddress.getByName(address.getHostName()),
address.getPort(), "http");
break;
}
}
return systemProxy;
}
/**
* Note: The value annotation is set to the setter of httpTimeout here as
* we can't autowire any value to its static field (but the field has to be
* static itself).
*
* @param httpTimeout the httpTimeout to set
*/
@Value("${http.timeout}")
@SuppressWarnings("static-method")
public void setHttpTimeout(int httpTimeout) {
HttpUtil.httpTimeout = httpTimeout;
}
}
|
package com.basho.riak.client.api.commands.itest;
import com.basho.riak.client.api.RiakClient;
import com.basho.riak.client.api.commands.kv.BatchDelete;
import com.basho.riak.client.api.commands.kv.FetchValue;
import com.basho.riak.client.api.commands.kv.StoreValue;
import com.basho.riak.client.core.RiakFuture;
import com.basho.riak.client.core.operations.itest.ITestBase;
import com.basho.riak.client.core.query.Location;
import com.basho.riak.client.core.query.Namespace;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertNull;
public class ITestBatchDelete extends ITestBase
{
@Test
public void testBatchDelete() throws ExecutionException, InterruptedException
{
RiakClient client = new RiakClient(cluster);
// Insert Data
Location[] bookLocations = insertBookData(client);
// Verify Data was inserted
FetchValue[] fetchCmds = verifyInsert(client, bookLocations);
// Delete Data
BatchDelete.Builder batchDeleteBuilder = new BatchDelete.Builder();
batchDeleteBuilder.withTimeout(3000).addLocations(bookLocations);
BatchDelete batchDelete = batchDeleteBuilder.build();
RiakFuture<BatchDelete.Response, List<Location>> future = client.executeAsync(batchDelete);
future.await(10, TimeUnit.SECONDS);
// Verify Deleted Data
verifyDeletedData(client, fetchCmds);
}
private Location[] insertBookData(RiakClient client)
throws ExecutionException, InterruptedException
{
final Namespace booksBucket = new Namespace("books");
Location[] bookLocations = new Location[] {
new Location(booksBucket, "moby_dick"),
new Location(booksBucket, "moby_dick_2")
};
Book mobyDick = new Book();
mobyDick.title = "Moby Dick";
mobyDick.author = "Herman Melville";
mobyDick.body = "Call me Ishmael. Some years ago...";
mobyDick.isbn = "1111979723";
mobyDick.copiesOwned = 3;
Book mobyDick2 = new Book();
mobyDick2.title = "Moby Dick 2";
mobyDick2.author = "Herman Melville 2";
mobyDick2.body = "Call me Ishmael. Some years ago... 2";
mobyDick2.isbn = "1111979723 2";
mobyDick2.copiesOwned = 2;
StoreValue storeBookOp = new StoreValue.Builder(mobyDick).withLocation(bookLocations[0]).build();
StoreValue storeBookOp2 = new StoreValue.Builder(mobyDick2).withLocation(bookLocations[1]).build();
client.execute(storeBookOp);
client.execute(storeBookOp2);
return bookLocations;
}
private FetchValue[] verifyInsert(RiakClient client, Location[] bookLocations)
throws ExecutionException, InterruptedException
{
// And we'll verify that we can fetch the info about Moby Dick and
// that that info will match the object we created initially
FetchValue fetchMobyDickOp = new FetchValue.Builder(bookLocations[0]).build();
Book fetchedBook = client.execute(fetchMobyDickOp).getValue(Book.class);
assertNotNull(fetchedBook);
FetchValue fetchMobyDickOp2 = new FetchValue.Builder(bookLocations[1]).build();
Book fetchedBook2 = client.execute(fetchMobyDickOp2).getValue(Book.class);
assertNotNull(fetchedBook2);
return new FetchValue[] { fetchMobyDickOp, fetchMobyDickOp2 };
}
private void verifyDeletedData(RiakClient client, FetchValue[] fetchCmds)
throws ExecutionException, InterruptedException
{
Book deletedBook = client.execute(fetchCmds[0]).getValue(Book.class);
assertNull(deletedBook);
Book deletedBook2 = client.execute(fetchCmds[1]).getValue(Book.class);
assertNull(deletedBook2);
}
public static class Book
{
public String title;
public String author;
public String body;
public String isbn;
public Integer copiesOwned;
}
}
|
package com.github.dannil.httpdownloader.test.utility;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import org.joda.time.DateTime;
import com.github.dannil.httpdownloader.model.Download;
import com.github.dannil.httpdownloader.model.User;
public final class TestUtility {
// TODO Change this to a URL pointing to the project repo
private static final String DOWNLOAD_URL = "https://raw.githubusercontent.com/dannil/HttpDownloader/dev/resources/TEST_MAVEN_README.md";
private static long USER_ID = 1;
private static long DOWNLOAD_ID = 1;
private static final List<User> users;
private static final List<Download> downloads;
static {
users = new LinkedList<User>();
User user = new User("example@example.com", "test", "exampleFirst", "exampleLast");
user.setId(USER_ID);
users.add(user);
USER_ID++;
downloads = new LinkedList<Download>();
final Download download = new Download("README", DOWNLOAD_URL, new DateTime(), new DateTime(), null);
download.setId(DOWNLOAD_ID);
downloads.add(download);
DOWNLOAD_ID++;
}
public static final User getUser() {
Random random = new Random();
final User user = users.get(random.nextInt(users.size()));
user.setId(USER_ID);
user.setEmail("example" + USER_ID + "@example.com");
USER_ID++;
return user;
}
public static final Download getDownload() {
Random random = new Random();
Download download = downloads.get(random.nextInt(downloads.size()));
download.setId(DOWNLOAD_ID);
DOWNLOAD_ID++;
return download;
}
}
|
package duro.reflang.ast;
public interface ASTVisitor {
void visitMessageExchange(ASTMessageExchange ast);
void visitMessage(ASTMessage ast);
void visitThis(ASTThis ast);
void visitNull(ASTNull ast);
void visitTrue(ASTTrue ast);
void visitFalse(ASTFalse ast);
void visitFrame(ASTFrame ast);
void visitString(ASTString ast);
void visitInteger(ASTInteger ast);
void visitLocalAssignment(ASTLocalAssignment ast);
void visitLocalAccess(ASTLocalAccess ast);
void visitSlotAccess(ASTSlotAccess ast);
void visitSlotAssignment(ASTSlotAssignment ast);
void visitGrouping(ASTGrouping ast);
void visitClosure(ASTClosure ast);
void visitInterfaceId(ASTInterfaceId ast);
void visitDict(ASTDict ast);
void visitArray(ASTArray ast);
void visitBehavior(ASTBehavior ast);
void visitProgram(ASTProgram ast);
void visitImplicitReceiver(ASTImplicitReceiver ast);
void visitSpawn(ASTSpawn ast);
}
|
package com.rarchives.ripme.tst.ripper.rippers;
import com.rarchives.ripme.ripper.rippers.HqpornerRipper;
import com.rarchives.ripme.utils.Utils;
import java.io.IOException;
import java.net.URL;
public class HqpornerRipperTest extends RippersTest {
public void testRip() throws IOException {
if (Utils.getConfigBoolean("test.run_flaky_tests", false)) {
HqpornerRipper ripper = new HqpornerRipper(
new URL("https://hqporner.com/hdporn/84636-pool_lesson_with_a_cheating_husband.html"));
testRipper(ripper);
}
}
public void testGetGID() throws IOException {
URL poolURL = new URL("https://hqporner.com/hdporn/84636-pool_lesson_with_a_cheating_husband.html");
HqpornerRipper ripper = new HqpornerRipper(poolURL);
assertEquals("84636-pool_lesson_with_a_cheating_husband", ripper.getGID(poolURL));
}
public void testGetURLsFromPage() throws IOException {
URL actressUrl = new URL("https://hqporner.com/actress/kali-roses");
HqpornerRipper ripper = new HqpornerRipper(actressUrl);
assert (ripper.getURLsFromPage(ripper.getFirstPage()).size() >= 2);
}
public void testGetNextPage() throws IOException {
URL multiPageUrl = new URL("https://hqporner.com/category/tattooed");
HqpornerRipper multiPageRipper = new HqpornerRipper(multiPageUrl);
assert (multiPageRipper.getNextPage(multiPageRipper.getFirstPage()) != null);
URL singlePageUrl = new URL("https://hqporner.com/actress/amy-reid");
HqpornerRipper ripper = new HqpornerRipper(singlePageUrl);
try {
ripper.getNextPage(ripper.getFirstPage());
} catch (IOException e) {
assertEquals(e.getMessage(), "No next page found.");
}
}
public void testMyDaddyVideoHost() throws IOException {
if (Utils.getConfigBoolean("test.run_flaky_tests", false)) {
URL myDaddyUrl = new URL("https://hqporner.com/hdporn/84636-pool_lesson_with_a_cheating_husband.html");
HqpornerRipper myDaddyRipper = new HqpornerRipper(myDaddyUrl);
testRipper(myDaddyRipper);
}
}
public void testFlyFlvVideoHost() throws IOException {
if (Utils.getConfigBoolean("test.run_flaky_tests", false)) {
URL flyFlvUrl = new URL(
"https://hqporner.com/hdporn/69862-bangbros_-_amy_reid_taking_off_a_tight_sexy_swimsuit.html");
HqpornerRipper flyFlvRipper = new HqpornerRipper(flyFlvUrl);
testRipper(flyFlvRipper);
}
}
public void testUnknownVideoHost() throws IOException {
if (Utils.getConfigBoolean("test.run_flaky_tests", false)) {
URL unknownHostUrl = new URL("https://hqporner.com/hdporn/79528-Kayden_Kross_-_Serious_Masturbation.html"); // howq.cc
HqpornerRipper unknownHostRipper = new HqpornerRipper(unknownHostUrl);
testRipper(unknownHostRipper);
}
}
}
|
package duro.runtime;
import duro.runtime.CustomProcess.Frame;
public class ClosureProcess extends DictionaryProcess {
private static final long serialVersionUID = 1L;
private CustomProcess.Frame frame;
private CallFrameInfo callFrameInfo;
private CallFrameInfo callCallFrameInfo;
public ClosureProcess(Frame frame, CallFrameInfo callFrameInfo) {
this.frame = frame;
this.callFrameInfo = callFrameInfo;
Instruction[] callInstructions = new Instruction[] {
new Instruction(Instruction.OPCODE_LOAD_FRAME, frame),
new Instruction(Instruction.OPCODE_LOAD_FUNC, callFrameInfo),
new Instruction(Instruction.OPCODE_EXEC_ON_FRAME),
new Instruction(Instruction.OPCODE_RET, 1)
};
callCallFrameInfo = new CallFrameInfo(0, 0, callInstructions);
}
@Override
public Object getCallable(Object key) {
if(key.equals("call"))
return callCallFrameInfo;
return super.getCallable(key);
}
@Override
public DictionaryProcess newBase() {
return new ClosureProcess(frame, callFrameInfo);
}
}
|
package de.dhbw.humbuch.viewmodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.google.inject.Inject;
import com.google.inject.Provider;
import de.dhbw.humbuch.guice.GuiceJUnitRunner;
import de.dhbw.humbuch.guice.GuiceJUnitRunner.GuiceModules;
import de.dhbw.humbuch.guice.TestModule;
import de.dhbw.humbuch.model.DAO;
import de.dhbw.humbuch.model.entity.Grade;
import de.dhbw.humbuch.model.entity.Student;
import de.dhbw.humbuch.model.entity.TestPersistenceInitialiser;
@RunWith(GuiceJUnitRunner.class)
@GuiceModules({ TestModule.class })
public class StudentInformationViewModelTest extends BaseTest {
private StudentInformationViewModel vm;
private DAO<Student> daoStudent;
@Inject
public void setInjected(TestPersistenceInitialiser persistenceInitialiser,
Provider<EntityManager> emProvider,
StudentInformationViewModel studentInformationViewModel,
DAO<Student> daoStudent) {
this.daoStudent = daoStudent;
super.setInjected(persistenceInitialiser, emProvider);
this.vm = studentInformationViewModel;
}
private void importTwoStudents(boolean fullImport) {
Grade grade = new Grade.Builder(5, "").build();
List<Student> students = new ArrayList<Student>();
Student student1 = new Student.Builder(4, "Roberto", "Rastapopoulos", null, grade).build();
Student student2 = new Student.Builder(5, "Bianca", "Castafiore", null, grade).build();
students.add(student1);
students.add(student2);
vm.persistStudents(students, fullImport);
}
private void importThreeStudents(){
Grade grade = new Grade.Builder(7, "").build();
List<Student> students = new ArrayList<Student>();
Student student1 = new Student.Builder(1, "Tim", "Tintin", null, grade).build();
Student student2 = new Student.Builder(2, "Struppi", "Milou", null, grade).build();
Student student3 = new Student.Builder(3, "Archibald", "Haddock", null, grade).build();
students.add(student1);
students.add(student2);
students.add(student3);
vm.persistStudents(students, true);
}
private void overrideStudentWithId(int id){
Grade grade = new Grade.Builder(7, "").build();
List<Student> students = new ArrayList<Student>();
Student student1 = new Student.Builder(id, "Balduin", "Bienlein", null, grade).build();
students.add(student1);
vm.persistStudents(students, true);
}
@Before
public void refreshViewModel() {
vm.refresh();
}
@Test
public void testStateInitialisation() {
assertNotNull(vm.students.get());
}
@Test
public void testFullImport() {
importThreeStudents();
refreshViewModel();
importTwoStudents(true);
refreshViewModel();
assertEquals(2, daoStudent.findAll().size());
assertEquals("Bianca", daoStudent.find(5).getFirstname());
}
@Test
public void testDeltaImport() {
importThreeStudents();
refreshViewModel();
importTwoStudents(false);
refreshViewModel();
assertEquals(5, daoStudent.findAll().size());
assertEquals("Milou", daoStudent.find(2).getLastname());
}
@Test
public void updateStudentByImport(){
importThreeStudents();
refreshViewModel();
int id = 3;
assertEquals("Haddock", daoStudent.find(id).getLastname());
overrideStudentWithId(id);
refreshViewModel();
assertEquals("Bienlein", daoStudent.find(id).getLastname());
}
}
|
package de.dhbw.humbuch.viewmodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.google.inject.Inject;
import com.google.inject.Provider;
import de.dhbw.humbuch.guice.GuiceJUnitRunner;
import de.dhbw.humbuch.guice.GuiceJUnitRunner.GuiceModules;
import de.dhbw.humbuch.guice.TestModule;
import de.dhbw.humbuch.model.DAO;
import de.dhbw.humbuch.model.entity.Grade;
import de.dhbw.humbuch.model.entity.Student;
import de.dhbw.humbuch.model.entity.TestPersistenceInitialiser;
@RunWith(GuiceJUnitRunner.class)
@GuiceModules({ TestModule.class })
public class StudentInformationViewModelTest extends BaseTest {
private StudentInformationViewModel vm;
private DAO<Student> daoStudent;
@Inject
public void setInjected(TestPersistenceInitialiser persistenceInitialiser,
Provider<EntityManager> emProvider,
StudentInformationViewModel studentInformationViewModel,
DAO<Student> daoStudent) {
this.daoStudent = daoStudent;
super.setInjected(persistenceInitialiser, emProvider);
this.vm = studentInformationViewModel;
}
private void importTwoStudents(boolean fullImport) {
Grade grade = new Grade.Builder(5, "").build();
List<Student> students = new ArrayList<Student>();
Student student1 = new Student.Builder(4, "Peter", "Doe", null, grade).build();
Student student2 = new Student.Builder(5, "Claude", "Gable", null, grade).build();
students.add(student1);
students.add(student2);
vm.persistStudents(students, fullImport);
}
private void importThreeStudents(){
Grade grade = new Grade.Builder(7, "").build();
List<Student> students = new ArrayList<Student>();
Student student1 = new Student.Builder(1, "Tim", "Tintin", null, grade).build();
Student student2 = new Student.Builder(2, "Struppi", "Milou", null, grade).build();
Student student3 = new Student.Builder(3, "Archibald", "Haddock", null, grade).build();
students.add(student1);
students.add(student2);
students.add(student3);
vm.persistStudents(students, true);
}
@Before
public void refreshViewModel() {
vm.refresh();
}
@Test
public void testStateInitialisation() {
assertNotNull(vm.students.get());
}
@Test
public void testFullImport() {
importThreeStudents();
refreshViewModel();
importTwoStudents(true);
refreshViewModel();
assertEquals(2, daoStudent.findAll().size());
assertEquals("Claude", daoStudent.find(5).getFirstname());
}
@Test
public void testDeltaImport() {
importThreeStudents();
refreshViewModel();
importTwoStudents(false);
refreshViewModel();
assertEquals(5, daoStudent.findAll().size());
assertEquals("Milou", daoStudent.find(2).getLastname());
}
}
|
package org.opencloudb.config.loader.zookeeper;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.opencloudb.config.ZookeeperTestServer;
import org.opencloudb.config.loader.zookeeper.entitiy.Property;
import org.opencloudb.config.loader.zookeeper.entitiy.Server;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.IsCollectionContaining.hasItems;
@Ignore
public class ZookeeperSaverTest extends ZookeeperTestServer {
private JSONObject config;
@Before public void setUp() throws Exception {
ZookeeperLoader loader = new ZookeeperLoader();
loader.setZkURl(testingServer.getConnectString());
config = loader.loadConfig();
}
@Test public void testSaveServer() throws Exception {
ZookeeperSaver saver = new ZookeeperSaver();
Server server = saver.saveServer(config,"server_zk");
assertThat(server.getSystem().getProperty().size(), is(3));
assertThat(server.getSystem().getProperty().get(0),
is(new Property().setName("serverport").setValue("8066")));
assertThat(server.getSystem().getProperty().get(1),
is(new Property().setName("sequncehandlertype").setValue("1")));
assertThat(server.getSystem().getProperty().get(2),
is(new Property().setName("defaultsqlparser").setValue("druidparser")));
//users
assertThat(server.getUser().size(), is(2));
Server.User expectTest = new Server.User();
Property expectTestP1 = new Property().setName("readOnly").setValue("true");
Property expectTestP3 = new Property().setName("password").setValue("admin");
Property expectTestP4 = new Property().setName("schemas").setValue("testdb,test");
expectTest.addProperty(expectTestP1);
expectTest.addProperty(expectTestP3);
expectTest.addProperty(expectTestP4);
expectTest.setName("test");
assertThat(server.getUser().get(0).getName(),is(expectTest.getName()));
assertThat(server.getUser().get(0).getProperty(),
hasItems(expectTestP1, expectTestP3, expectTestP4));
Server.User expectMycat = new Server.User();
Property expectMycatP1 = new Property().setName("readOnly").setValue("false");
Property expectMycatP3 = new Property().setName("password").setValue("admin");
Property expectMycatP4 = new Property().setName("schemas").setValue("testdb");
expectMycat.addProperty(expectMycatP1);
expectMycat.addProperty(expectMycatP3);
expectMycat.addProperty(expectMycatP4);
expectMycat.setName("mycat");
assertThat(server.getUser().get(1).getName(),is(expectMycat.getName()));
assertThat(server.getUser().get(1).getProperty(),
hasItems(expectMycatP1, expectMycatP3, expectMycatP4));
}
}
|
package com.puppycrawl.tools.checkstyle.checks.imports;
import com.puppycrawl.tools.checkstyle.checks.imports.AccessResult;
import com.puppycrawl.tools.checkstyle.checks.imports.Guard;
import com.puppycrawl.tools.checkstyle.checks.imports.PkgControl;
import junit.framework.TestCase;
public class PkgControlTest extends TestCase
{
private final PkgControl pcRoot = new PkgControl("com.kazgroup.courtlink");
private final PkgControl pcCommon = new PkgControl(pcRoot, "common");
protected void setUp() throws Exception
{
super.setUp();
pcRoot.addGuard(new Guard(false, false, "org.springframework", false));
pcRoot.addGuard(new Guard(false, false, "org.hibernate", false));
pcRoot.addGuard(new Guard(true, false, "org.apache.commons", false));
pcCommon.addGuard(new Guard(true, false, "org.hibernate", false));
}
public void testFullPkg()
{
assertEquals("com.kazgroup.courtlink", pcRoot.getFullPackage());
assertEquals("com.kazgroup.courtlink.common", pcCommon.getFullPackage());
}
public void testLocateFinest()
{
assertEquals(pcRoot, pcRoot
.locateFinest("com.kazgroup.courtlink.domain"));
assertEquals(pcCommon, pcRoot
.locateFinest("com.kazgroup.courtlink.common.api"));
assertNull(pcRoot.locateFinest("com"));
}
public void testCheckAccess()
{
assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess(
"org.springframework.something",
"com.kazgroup.courtlink.common"));
assertEquals(AccessResult.ALLOWED, pcCommon
.checkAccess("org.apache.commons.something",
"com.kazgroup.courtlink.common"));
assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess(
"org.apache.commons", "com.kazgroup.courtlink.common"));
assertEquals(AccessResult.ALLOWED, pcCommon.checkAccess(
"org.hibernate.something", "com.kazgroup.courtlink.common"));
assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess(
"com.badpackage.something", "com.kazgroup.courtlink.common"));
assertEquals(AccessResult.DISALLOWED, pcRoot.checkAccess(
"org.hibernate.something", "com.kazgroup.courtlink"));
}
public void testUnknownPkg()
{
assertNull(pcRoot.locateFinest("net.another"));
}
}
|
package org.helioviewer.viewmodel.view.jp2view.image;
import java.awt.Rectangle;
import org.helioviewer.base.math.Interval;
/**
* A very simple region of interest class. Basically just an immutable (for
* thread safety) rectangle class with less functionality. At the moment the
* information contained in this class is just x,y,width, and height. This data
* is actually kept in two separate formats... int's and range/domain
* Interval's. The intervals are probably the better choice, but I have gone
* through and eliminated the direct calls to the member variables yet.
*
* @author caplins
*
*/
public class SubImage {
/** Holds the domain of the ROI */
public final Interval<Integer> domain;
/** Holds the range of the ROI */
public final Interval<Integer> range;
/** The same data as in the range and domain */
public int x;
public int y;
public int width;
public int height;
/**
* Constructor taking primitive ints.
*
* @param _x
* @param _y
* @param _width
* @param _height
*/
public SubImage(int _x, int _y, int _width, int _height) {
x = _x;
y = _y;
width = _width;
height = _height;
domain = new Interval<Integer>(x, x + width);
range = new Interval<Integer>(y, y + height);
}
/**
* Constructor taking Intervals.
*
* @param _domain
* @param _range
*/
public SubImage(Interval<Integer> _domain, Interval<Integer> _range) {
domain = _domain;
range = _range;
x = domain.getStart();
width = domain.getEnd() - domain.getStart();
y = range.getStart();
height = range.getEnd() - range.getStart();
}
/**
* Constructor taking a Rectangle
*
* @param _rect
*/
public SubImage(Rectangle _rect) {
this(_rect.x, _rect.y, _rect.width, _rect.height);
}
/** Overridden equals method. */
@Override
public boolean equals(Object _obj) {
if (_obj == null)
return false;
else if (!(_obj instanceof SubImage))
return false;
else {
SubImage roi = SubImage.class.cast(_obj);
return domain.equals(roi.domain) && range.equals(roi.range);
}
}
/** Returns the number of pixels in the ROI */
public int getNumPixels() {
return width * height;
}
/** Overridden toString method */
@Override
public String toString() {
String ret = "";
ret += "x=" + domain.getStart() + " ";
ret += "y=" + range.getStart() + " ";
ret += "width=" + (domain.getEnd() - domain.getStart()) + " ";
ret += "height=" + (range.getEnd() - range.getStart()) + " ";
return ret;
}
};
|
package com.ippon.kafka.streams.processor;
import com.ippon.kafka.streams.model.Effectif;
import com.ippon.kafka.streams.serdes.SerdeFactory;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KStreamBuilder;
import org.apache.kafka.streams.kstream.KTable;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@Component
public class StreamProcessor implements CommandLineRunner {
public static final String STREAM_APPLICATION_NAME = "StreamingTest";
private static final String inputTopic = "effectifs";
@Override
public void run(String... strings) throws Exception {
// Create an instance of StreamsConfig from the Properties instance
StreamsConfig config = new StreamsConfig(getProperties());
// Define Serialization / Deserialization
Map<String, Object> serdeProps = new HashMap<>();
Serde<Effectif> effectifSerde = SerdeFactory.createSerde(Effectif.class, serdeProps);
// Building Kafka Streams Model
KStreamBuilder kStreamBuilder = new KStreamBuilder();
// Init common topology
KStream<Integer, Effectif> effectifsStream = kStreamBuilder
.stream(Serdes.Integer(), effectifSerde, inputTopic)
.filter((year, effectif) -> !"TOTAL".equals(effectif.getGroup()))
.filter((year, effectif) -> "Commune".equals(effectif.getGeographicLevel()));
// Define streams topologies |
// 1. Global student count per year |
KTable<Integer, Double> studentsPerYear = effectifsStream
.map((year, effectif) -> new KeyValue<>(year, effectif.getStudentCount()))
.groupByKey(Serdes.Integer(), Serdes.Double())
.aggregate(
() -> 0D,
(aggKey, value, aggregate) -> aggregate + value,
Serdes.Double(),
"studentsPerYear");
// We can easily send to another topic
studentsPerYear.to(Serdes.Integer(), Serdes.Double(), "studentsPerYear");
// Or print the result
studentsPerYear.print();
// 2. Formation communes count |
effectifsStream
.groupBy((year, effectif) -> effectif.getGroup(), Serdes.String(), effectifSerde)
.count("countPerFormation")
.print();
// 3. Student count variation
// Students per commune 2014
KTable<String, Double> studentsPerCommune2014 = effectifsStream
.filter((year, effectif) -> year == 2014)
.groupBy((year, effectif) -> effectif.getGeographicUnit(), Serdes.String(), effectifSerde)
.aggregate(
() -> 0D,
((aggKey, value, aggregate) ->
aggregate + (value.getStudentCount() != null ? value.getStudentCount() : 0)),
Serdes.Double(),
"studentsPerCommune2014");
// Students per commune 2015
KTable<String, Double> studentsPerCommune2015 = effectifsStream
.filter((year, effectif) -> year == 2015)
.groupBy((year, effectif) -> effectif.getGeographicUnit(), Serdes.String(), effectifSerde)
.aggregate(
() -> 0D,
((aggKey, value, aggregate) ->
aggregate + (value.getStudentCount() != null ? value.getStudentCount() : 0)),
Serdes.Double(),
"studentsPerCommune2015");
// Student count variation between 2014 and 2015
studentsPerCommune2014
.leftJoin(studentsPerCommune2015, this::calculateEvolution)
.print("Evolution 2014 2015");
// Start processing
System.out.println("Starting Kafka Streams");
KafkaStreams kafkaStreams = new KafkaStreams(kStreamBuilder, config);
kafkaStreams.start();
System.out.println("Kafka Streams started");
}
private Double calculateEvolution(Double previousValue, Double newValue) {
if (previousValue == null && newValue == null) {
return 0D;
}
if (previousValue == null) {
return 100D;
}
if (newValue == null) {
return -100D;
}
return ((newValue - previousValue) / previousValue) * 100;
}
/**
* Init stream properties.
* @return the created stream settings.
*/
private static Properties getProperties() {
Properties settings = new Properties();
// Application ID, used for consumer groups
settings.put(StreamsConfig.APPLICATION_ID_CONFIG, STREAM_APPLICATION_NAME);
// Kafka bootstrap server (broker to talk to)
settings.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
// default serdes for serializing and deserializing key and value from and to streams
settings.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
settings.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
// We can also set Consumer properties
settings.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
return settings;
}
}
|
package net.sf.farrago.test;
import java.sql.*;
import java.util.*;
import javax.jmi.reflect.*;
import junit.framework.*;
import net.sf.farrago.cwm.relational.*;
import net.sf.farrago.fem.security.*;
import net.sf.farrago.jdbc.engine.*;
import net.sf.farrago.resource.*;
import net.sf.farrago.session.*;
import net.sf.farrago.type.*;
import org.eigenbase.rel.metadata.*;
import org.eigenbase.relopt.*;
import org.eigenbase.test.*;
/**
* FarragoQueryTest tests miscellaneous aspects of Farrago query processing
* which are impossible to test via SQL scripts.
*
* @author John V. Sichi
* @version $Id$
*/
public class FarragoQueryTest
extends FarragoTestCase
{
/**
* Creates a new FarragoQueryTest object.
*
* @param testName JUnit test name
*
* @throws Exception .
*/
public FarragoQueryTest(String testName)
throws Exception
{
super(testName);
}
// implement TestCase
public static Test suite()
{
return wrappedSuite(FarragoQueryTest.class);
}
/**
* Tests a query which involves operation on columns.
*/
public void testPrimitiveColumnOperation()
throws Exception
{
String sql =
"select deptno*1, deptno/1, deptno+0, deptno-0,"
+ " deptno*deptno, deptno/deptno,deptno"
+ " from sales.emps order by deptno";
preparedStmt = connection.prepareStatement(sql);
resultSet = preparedStmt.executeQuery();
List<String> refList = new ArrayList<String>();
refList.add("10");
refList.add("20");
refList.add("20");
refList.add("40");
compareResultList(refList);
}
/**
* Tests a query which involves comparison with VARBINARY values.
*/
public void testVarbinaryComparison()
throws Exception
{
String sql = "select name from sales.emps where public_key=?";
preparedStmt = connection.prepareStatement(sql);
final byte [] bytes = { 0x41, 0x62, 0x63 };
preparedStmt.setBytes(1, bytes);
resultSet = preparedStmt.executeQuery();
Set<String> refSet = new HashSet<String>();
refSet.add("Eric");
compareResultSet(refSet);
}
/**
* Tests a query which involves sorting VARBINARY values.
*/
public void testOrderByVarbinary()
throws Exception
{
String sql =
"select name,public_key from sales.emps" + " order by public_key";
resultSet = stmt.executeQuery(sql);
List<String> refList = new ArrayList<String>();
refList.add("Wilma");
refList.add("Eric");
refList.add("Fred");
refList.add("John");
compareResultList(refList);
}
/**
* Tests a query using a different catalog.
*/
public void testSetCatalog()
throws Exception
{
String sql = "set catalog 'sys_cwm'";
stmt.execute(sql);
sql = "select \"name\" from \"Relational\".\"Schema\"";
resultSet = stmt.executeQuery(sql);
Set<String> refSet = new HashSet<String>();
refSet.add("INFORMATION_SCHEMA");
refSet.add("JDBC_METADATA");
refSet.add("MGMT");
refSet.add("SALES");
refSet.add("SQLJ");
refSet.add("SYS_BOOT");
compareResultSet(refSet);
// restore default catalog
sql = "set catalog 'localdb'";
stmt.execute(sql);
}
/**
* Tests execution of an internal LURQL query defined in a resource file.
*/
public void testInternalLurqlQuery()
throws Exception
{
String lurql = FarragoInternalQuery.instance().TestQuery.str();
checkLurqlTableSchema(lurql, "DEPTS", "SALES");
checkLurqlTableSchema(lurql, "CATALOGS_VIEW", "JDBC_METADATA");
}
/**
* Verifies non-standard behavior preventing more than one statement active
* at a time in autocommit mode.
*/
public void testAutocommitCursorLimit()
throws Exception
{
// TODO jvs 20-Mar-2006: move this test to FarragoJdbcTest
// after that gets refactored.
String sql = "select name from sales.depts";
Statement stmt2 = null;
connection.setAutoCommit(true);
try {
// First, open a cursor.
resultSet = stmt.executeQuery(sql);
// Now, try to open another one on the same connection while the
// first one is still open: should fail.
stmt2 = connection.createStatement();
resultSet = stmt2.executeQuery(sql);
} catch (SQLException ex) {
// verify expected error message
Assert.assertTrue(
"Expected message about cursor still open but got '"
+ ex.getMessage() + "'",
ex.getMessage().indexOf("cursor is still open") > -1);
ex.getMessage();
} finally {
if (stmt2 != null) {
stmt2.close();
}
connection.setAutoCommit(false);
}
}
/**
* Verifies that multiple statements can be active when not in autocommit
* mode.
*/
public void testNoAutocommitCursorLimit()
throws Exception
{
String sql = "select name from sales.depts";
Statement stmt2 = null;
try {
// First, open a cursor.
resultSet = stmt.executeQuery(sql);
// Now, try to open another one on the same connection while the
// first one is still open.
stmt2 = connection.createStatement();
resultSet = stmt2.executeQuery(sql);
} finally {
if (stmt2 != null) {
stmt2.close();
}
}
}
private void checkLurqlTableSchema(
String lurql,
String tableName,
String schemaName)
throws Exception
{
Map<String, String> argMap = new HashMap<String, String>();
argMap.put("tableName", tableName);
FarragoJdbcEngineConnection farragoConnection =
(FarragoJdbcEngineConnection) connection;
FarragoSession session = farragoConnection.getSession();
Collection<RefObject> result =
session.executeLurqlQuery(
lurql,
argMap);
assertEquals(
1,
result.size());
RefObject obj = result.iterator().next();
assertTrue(obj instanceof CwmSchema);
assertEquals(
schemaName,
((CwmSchema) obj).getName());
}
/**
* Tests execution of a LURQL query to check role cycle. If role_2 has been
* granted to role_1, then role_1 can't be granted to role_2. This query
* expanded all the roles inherited by a specified input role, the test then
* scans through the inherited roles to ensure that a second specified role
* (to be granted to the first specified role) does not exist.
*/
public void testCheckSecurityRoleCyleLurqlQuery()
throws Exception
{
// CREATE ROLE ROLE_1, ROLE_2
// GRANT ROLE_2 TO ROLE_1
// Simulate GRANT ROLE ROLE_1 TO ROLE_2. This should fail.
stmt.execute("CREATE ROLE ROLE_1");
stmt.execute("CREATE ROLE ROLE_2");
stmt.execute("GRANT ROLE ROLE_2 TO ROLE_1");
// NOTE: now we want to simulate GRANT ROLE ROLE_1 TO ROLE_2.
// So the grantee is ROLE_2, and the granted role is ROLE_1.
// For the cycle check, we need to look for paths in the
// opposite direction, so we reverse the two roles in the
// call below.
String lurql =
FarragoInternalQuery.instance().TestSecurityRoleCycleCheck.str();
assertTrue(checkLurqlSecurityRoleCycle(lurql, "ROLE_1", "ROLE_2"));
}
private boolean checkLurqlSecurityRoleCycle(
String lurql,
String granteeName,
String grantedRoleName)
throws Exception
{
Map<String, String> argMap = new HashMap<String, String>();
argMap.put("granteeName", granteeName);
FarragoJdbcEngineConnection farragoConnection =
(FarragoJdbcEngineConnection) connection;
FarragoSession session = farragoConnection.getSession();
Collection<RefObject> result =
session.executeLurqlQuery(
lurql,
argMap);
for (RefObject o : result) {
FemRole role = (FemRole) o;
if (role.getName().equals(grantedRoleName)) {
return true;
}
}
return false;
}
public void testAbandonedResultSet()
throws Exception
{
// Start a query that returns N rows where N > 1. Get the first
// row and walk away. This is similar to a query timeout.
String sql = "select deptno, name from sales.depts";
preparedStmt = connection.prepareStatement(sql);
// won't trigger this, but it causes a different type of result set
preparedStmt.setQueryTimeout(60);
resultSet = preparedStmt.executeQuery();
try {
if (!resultSet.next()) {
fail("Query has no rows!");
}
} finally {
resultSet.close();
resultSet = null;
}
}
/**
* Tests relational expression metadata derivation via
* FarragoSession.analyzeSql.
*/
public void testRelMetadata()
throws Exception
{
// This test currently requires Volcano in order to succeed.
stmt.executeUpdate(
"alter session implementation add jar"
+ " sys_boot.sys_boot.volcano_plugin");
String sql =
"select deptno, max(name) from sales.depts"
+ " where name like '%E%G' group by deptno";
FarragoJdbcEngineConnection farragoConnection =
(FarragoJdbcEngineConnection) connection;
FarragoSession session = farragoConnection.getSession();
FarragoSessionAnalyzedSql analyzedSql =
session.analyzeSql(
sql,
new FarragoTypeFactoryImpl(session.getRepos()),
null,
true);
Set<RelColumnOrigin> rcoSet = analyzedSql.columnOrigins.get(0);
assertEquals(
1,
rcoSet.size());
RelMetadataTest.checkColumnOrigin(
rcoSet.iterator().next(),
"DEPTS",
"DEPTNO",
false);
rcoSet = analyzedSql.columnOrigins.get(1);
assertEquals(
1,
rcoSet.size());
RelMetadataTest.checkColumnOrigin(
rcoSet.iterator().next(),
"DEPTS",
"NAME",
true);
// By default, tables without stats are assumed to have
// 100 rows, and default selectivity assumption is 25% for a
// LIKE predicate. The single GROUP BY column gives a further 10%
// selectivity. 100 * 25% * 10% = 2.5.
assertEquals(2.5, analyzedSql.rowCount);
stmt.executeUpdate(
"alter session implementation set default");
}
public void testUdxRelMetadata()
throws Exception
{
String sql = "create schema udx";
stmt.executeUpdate(sql);
sql =
"create function udx.digest(c cursor) "
+ "returns table(c.*, row_digest int) "
+ "language java "
+ "parameter style system defined java "
+ "no sql "
+ "external name 'class net.sf.farrago.test.FarragoTestUDR.digest'";
stmt.executeUpdate(sql);
sql =
"select * from "
+ "table(udx.digest(cursor(select * from sales.depts)))";
FarragoJdbcEngineConnection farragoConnection =
(FarragoJdbcEngineConnection) connection;
FarragoSession session = farragoConnection.getSession();
FarragoSessionAnalyzedSql analyzedSql =
session.analyzeSql(
sql,
new FarragoTypeFactoryImpl(session.getRepos()),
null,
false);
Set<RelColumnOrigin> rcoSet = analyzedSql.columnOrigins.get(0);
assertEquals(
1,
rcoSet.size());
RelMetadataTest.checkColumnOrigin(
rcoSet.iterator().next(),
"DEPTS",
"DEPTNO",
true);
rcoSet = analyzedSql.columnOrigins.get(1);
assertEquals(
1,
rcoSet.size());
RelMetadataTest.checkColumnOrigin(
rcoSet.iterator().next(),
"DEPTS",
"NAME",
true);
rcoSet = analyzedSql.columnOrigins.get(2);
assertEquals(
0,
rcoSet.size());
sql = "drop schema udx cascade";
stmt.executeUpdate(sql);
}
/**
* Tests that the transaction manager correctly notifies listeners of table
* accesses.
*/
public void testTxnMgrListener()
throws Exception
{
// make sure we're starting a new txn
connection.commit();
FarragoJdbcEngineConnection farragoConnection =
(FarragoJdbcEngineConnection) connection;
FarragoSession session = farragoConnection.getSession();
FarragoSessionTxnMgr txnMgr = session.getTxnMgr();
TxnListener listener = new TxnListener();
txnMgr.addListener(listener);
try {
String sql = "select * from sales.depts";
resultSet = stmt.executeQuery(sql);
resultSet.close();
connection.commit();
} finally {
txnMgr.removeListener(listener);
}
List<String> expectedName =
Arrays.asList(
"LOCALDB",
"SALES",
"DEPTS");
assertEquals(
"begin",
listener.events.get(0));
assertEquals(
expectedName,
listener.events.get(1));
assertEquals(
TableAccessMap.Mode.READ_ACCESS,
listener.events.get(2));
assertEquals(
FarragoSessionTxnEnd.COMMIT,
listener.events.get(3));
}
/**
* Tests that ResultSet.getObject(int) implementation in farrago returns
* a distinct object for a ZonelessDateTime type column in each new row.
*
* @throws Exception
*/
public void testDateTimeOverLocalJdbc()
throws Exception
{
String createStmt =
"create table sales.datetable" +
"(keycol int not null primary key, datecol date)";
String dropStmt = " drop table sales.datetable";
String insertStmt1 =
"insert into sales.datetable values(0, DATE '2007-07-07')";
String insertStmt2 =
"insert into sales.datetable values(1, DATE '2007-07-08')";
String selectStmt1 =
"select * from (values cast('2007-06-22' as date), cast('2007-06-23' as date))";
String selectStmt2 =
"select t.datecol from sales.datetable as t";
String selectStmt3 =
"select t.datecol from sales.datetable as t where 1 = 1";
stmt.executeUpdate(createStmt);
stmt.executeUpdate(insertStmt1);
stmt.executeUpdate(insertStmt2);
Object obj1, obj2;
try {
// FarragoTupleIterResultSet with a CompoundTupleIter fetching
// from input iterators returning onw row each.
resultSet = stmt.executeQuery(selectStmt1);
resultSet.next();
obj1 = resultSet.getObject(1);
resultSet.next();
obj2 = resultSet.getObject(1);
assertFalse(obj1 == obj2);
resultSet.close();
// FennelOnlyResultSet
resultSet = stmt.executeQuery(selectStmt2);
resultSet.next();
obj1 = resultSet.getObject(1);
resultSet.next();
obj2 = resultSet.getObject(1);
assertFalse(obj1 == obj2);
resultSet.close();
// FarragoTupleIterResultSet
resultSet = stmt.executeQuery(selectStmt3);
resultSet.next();
obj1 = resultSet.getObject(1);
resultSet.next();
obj2 = resultSet.getObject(1);
assertFalse(obj1 == obj2);
resultSet.close();
} finally {
resultSet.close();
stmt.executeUpdate(dropStmt);
}
}
private static class TxnListener
implements FarragoSessionTxnListener
{
List<Object> events;
TxnListener()
{
events = new ArrayList<Object>();
}
public void transactionBegun(
FarragoSession session,
FarragoSessionTxnId txnId)
{
events.add("begin");
}
public void tableAccessed(
FarragoSessionTxnId txnId,
List<String> localTableName,
TableAccessMap.Mode accessType)
{
events.add(localTableName);
events.add(accessType);
}
public void transactionEnded(
FarragoSessionTxnId txnId,
FarragoSessionTxnEnd endType)
{
events.add(endType);
}
}
}
// End FarragoQueryTest.java
|
import ibis.ipl.*;
import java.util.Properties;
class Throughput extends Thread {
int count = 1000;
int transferSize = 0;
int rank;
int remoteRank;
int windowSize = Integer.MAX_VALUE;
String ibis_impl = "ibis.ipl.impl.tcp.TcpIbis";
ReceivePort rport;
SendPort sport;
byte[] data;
public static void main(String [] args) {
new Throughput(args).start();
}
void send() throws IbisIOException {
int w = windowSize;
for(int i = 0; i< count; i++) {
WriteMessage writeMessage = sport.newMessage();
writeMessage.writeArray(data);
writeMessage.send();
writeMessage.finish();
if (--w == 0) {
ReadMessage readMessage = rport.receive();
readMessage.readArray(data);
readMessage.finish();
w = windowSize;
}
}
}
void rcve() throws IbisIOException {
int w = windowSize;
for(int i = 0; i< count; i++) {
ReadMessage readMessage = rport.receive();
readMessage.readArray(data);
readMessage.finish();
if (--w == 0) {
WriteMessage writeMessage = sport.newMessage();
writeMessage.send();
writeMessage.writeArray(data);
writeMessage.finish();
w = windowSize;
}
}
}
Throughput(String[] args) {
/* parse the commandline */
int options = 0;
for (int i = 0; i < args.length; i++) {
if (false) {
} else if (args[i].equals("-panda")) {
ibis_impl = "ibis.ipl.impl.panda.PandaIbis";
} else if (args[i].equals("-window")) {
windowSize = Integer.parseInt(args[++i]);
} else if (options == 0) {
count = Integer.parseInt(args[i]);
options++;
} else if (options == 1) {
transferSize = Integer.parseInt(args[i]);
options++;
}
}
if (options != 2) {
System.err.println("Throughput <count> <size>");
System.exit(11);
}
data = new byte[transferSize];
}
public void run() {
try {
ReceivePortIdentifier ident;
Ibis ibis = Ibis.createIbis("throughput_ibis", ibis_impl, null);
Registry r = ibis.registry();
IbisIdentifier master = (IbisIdentifier)r.elect("throughput", ibis.identifier());
if (master.equals(ibis.identifier())) {
rank = 0;
remoteRank = 1;
System.err.println(">>>>>>>> Righto, I'm the master");
} else {
rank = 1;
remoteRank = 0;
System.err.println(">>>>>>>> Righto, I'm the slave");
}
StaticProperties s = new StaticProperties();
PortType t = ibis.createPortType("test type", s);
rport = t.createReceivePort("test port " + rank);
sport = t.createSendPort();
do {
ident = r.lookup("test port " + remoteRank);
if(ident == null) {
try {
Thread.sleep(1000);
} catch (Exception e) {}
}
} while (ident == null);
sport.connect(ident);
if(rank == 0) {
// warmup
send();
long time = System.currentTimeMillis();
send();
time = System.currentTimeMillis() - time;
double speed = (time * 1000.0) / (double)count;
double dataSent = ((double) transferSize * count) / (1024.0 * 1024.0);
System.out.print("Latency: " + count + " calls took " + (time/1000.0) + " seconds, time/call = " + speed + " micros, ");
System.out.println("Throughput: " + (dataSent / (time / 1000.0)) + " MByte/s");
} else {
rcve();
rcve();
}
/* free the send ports first */
sport.free();
rport.free();
ibis.end();
System.exit(0);
} catch (IbisException e) {
System.out.println("Got exception " + e);
System.out.println("StackTrace:");
e.printStackTrace();
} catch (IbisIOException e) {
System.out.println("Got exception " + e);
System.out.println("StackTrace:");
e.printStackTrace();
}
}
}
|
package com.scg.domain;
import java.util.List;
import java.util.Properties;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
/**
* Invoice encapsulates the attributes and behavior to create client
* invoices for a given time period from time cards. The invoicing business'
* name and address are obtained from a properties file. The name of the
* property file is specified by the PROP_FILE_NAME static member.
* @author Brian Stamm
*/
public final class Invoice {
//static variables here
private final String PROP_LOCATION = "/invoice.properties";
private final String BIZ_NAME = "business.name";
private final String BIZ_STREET = "business.street";
private final String BIZ_CITY = "business.city";
private final String BIZ_STATE = "business.state";
private final String BIZ_ZIP_CODE = "business.zip";
private final String NA = "n/a";
//private strings to be built from these -
private String businessName;
private String businessStreet;
private String businessCity;
private String businessState;
private String businessZipCode;
//static up here
static {
final Properties invoiceProperties = new Properties();
InputStream in = Invoice.class.getResourceAsStream(PROP_LOCATION)
try(invoiceProperties.load(in)){
businessName = invoiceProperties.getProperties(BIZ_NAME,NA);
businessStreet = invoiceProperties.getProperties(BIZ_STREET,NA);
businessCity = invoiceProperties.getProperties(BIZ_CITY,NA);
businessState = invoiceProperties.getProperties(BIZ_STATE,NA);
businessZipCode = invoiceProperties.getProperties(BIZ_ZIP_CODE,NA);
}
catch(IOException e){
System.err.println("Caught IOException: " + e.getMessage());
}
}
//private int invoiceYear;
private ClientAccount client;
//private java.time.Month invoiceMonth;
private LocalDate startDate;
List<InvoiceLineItem> lineItemList;
private int totalHours;
private int totalCharges;
/**
* Construct an Invoice for a client. The time period is set from the
* beginning to the end of the month specified.
* @param client - Client for this Invoice.
* @param invoiceMonth - Month for which this Invoice is being created.
* @param invoiceYear - Year for which this Invoice is being created.
*/
public Invoice(ClientAccount client, java.time.Month invoiceMonth, int invoiceYear) {
//this.invoiceYear = invoiceYear;
//invoice date = now
//start date is first of month of year
startDate = LocalDate.of(invoiceYear,invoiceMonth,1);
this.client = client;
//this.invoiceMonth = invoiceMonth;
this.lineItemList = new ArrayList<>();
totalHours = 0;
totalCharges = 0;
}
/**
* Get the start date for this Invoice, this is the earliest date/time a
* ConsultantTime instance may have and still be billed on this invoice.
* @return Start date.
*/
public java.time.LocalDate getStartDate(){
return startDate;
}
/**
* Get the invoice month. This is the 1-based month number.
* @return the invoice month number.
*/
public java.time.Month getInvoiceMonth(){
//return invoiceMonth;
return startDate.getMonth()
}
/**
* Get the client for this Invoice.
* @return the client.
*/
public ClientAccount getClientAccount() {
return client;
}
/**
* Get the total hours for this Invoice.
* @return Total hours.
*/
public int getTotalHours() {
return totalHours;
}
/**
* Get the total charges for this Invoice.
* @return Total charges.
*/
public int getTotalCharges() {
return totalCharges;
}
/**
* Add an invoice line item to this Invoice.
* @param lineItem - InvoiceLineItem to add.
*/
public void addLineItem(InvoiceLineItem lineItem) {
lineItemList.add(lineItem);
//then add hours and charges
totalCharges += lineItem.getCharge();
totalHours += lineItem.getHours();
}
/**
* Extract the billable hours for this Invoice's client from the input
* TimeCard and add them to the line items. Only those hours for the client
* and month unique to this invoice will be added.
* @param timeCard - the TimeCard potentially containing line items for this Invoices client.
*/
public void extractLineItems(TimeCard timeCard) {
List<ConsultantTime> billableList = timecard.getBillableHoursForClient(client.getName());
for(ConsultantTime currentConsultant : billableList){
LocalDate currentDate = currentConsultant.getDate();
if(currentDate == startDate){
InvoiceLineItem newLineItem = new InvoiceLineItem(currentDate, timeCard.getConsultant(),currentConsultant.getSkill(),currentConsultant.gethours());
addLineItem(newLineItem);
}
}
/**
* Create a string representation of this object, suitable for printing.
* @return string containing this invoices client name and billing start date
*/
@Override
public String toString() {
return "hello";
}
/**
* Create a formatted string containing the printable invoice. Includes a header
* and footer on each page.
* @return The formatted invoice as a string.
*/
public String toReportString() {
return "Another hello.";
}
}
|
package com.tuxnet.project_euler;
public class Main {
public static void main(String[] args) {
Problem10.solve();
}
}
|
package fi.mikuz.boarder.gui;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import fi.mikuz.boarder.R;
/**
*
* @author Jan Mikael Lindlf
*/
public class Introduction extends Activity {
public static final String TAG = "Guide";
LinearLayout mBody;
int mPage = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.introduction, (ViewGroup) findViewById(R.id.root));
mBody = (LinearLayout) layout.findViewById(R.id.introduction_body);
mBody.setOrientation(LinearLayout.VERTICAL);
mBody.setPadding(20, 20, 20, 20);
Button endButton = (Button) layout.findViewById(R.id.guide_end);
Button lastButton = (Button) layout.findViewById(R.id.guide_last);
Button nextButton = (Button) layout.findViewById(R.id.guide_next);
endButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
exit();
}
});
lastButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mPage > 0) {
mPage
changePage();
} else {
Toast.makeText(Introduction.this, "This is the first page", Toast.LENGTH_SHORT).show();
}
}
});
nextButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPage++;
changePage();
}
});
setContentView(layout);
changePage();
}
private void changePage() {
mBody.removeAllViews();
TextView text = new TextView(this);
switch(mPage) {
case 0:
setTitle("Welcome");
text.setText("Welcome to Boarder!\n\n" +
"This introduction helps you to get started with Boarder.\n\n" +
"You can return here any time through 'Help Center'.\n\n" +
"This is a short introduction. For more help please visit 'Help Center'.");
mBody.addView(text);
break;
case 1:
setTitle("Navigation");
text.setText("Downloading boards\n\n" +
"Default screen of Boarder is 'Soundboard Menu'. There you will be able to navigate to different places in Boarder.\n\n" +
"Opening menu will allow you to add new boards and stuff.\n\n" +
"You will will also find my email and forums so just ask me if you are lost.");
mBody.addView(text);
break;
case 2:
setTitle("Downloading boards");
text.setText("Downloading boards\n\n" +
"In 'Soundboard Menu' open menu and select 'Internet'.\n\n" +
"Select 'Download from Internets'. You can search and sort the list. Navigate the list by swiping left and right.\n\n" +
"Enter a board you want to download. It's recommended to start with highly rated board to avoid troubles.\n\n" +
"Click any button in 'Download' section. Download and execute a board '.zip' file. Select Boarder as app that executes the zip file.");
mBody.addView(text);
break;
case 3:
setTitle("Creating boards");
text.setText("Creating boards\n\n" +
"In 'Soundboard Menu' select 'Add' from menu.\n\n" +
"Add sounds from menu. Edit sound by short-clicking it.\n\n" +
"Swap to 'Listen board' mode in menu to use the board. Edit the board by swapping to 'Edit board' mode.");
mBody.addView(text);
break;
case 4:
setTitle("Thanks");
ImageView promo = new ImageView(this);
promo.setImageResource(R.drawable.promo);
promo.setAdjustViewBounds(true);
promo.setScaleType(ScaleType.CENTER_INSIDE);
mBody.addView(promo);
text.setText("\n\nThanks for reading Boarder introduction.\n\n" +
"I wish you pleasant boarding.");
text.setGravity(Gravity.CENTER_HORIZONTAL);
mBody.addView(text);
break;
default:
exit();
}
}
private void exit() {
try {
Introduction.this.finish();
} catch (Throwable e) {
Log.e(TAG, "Unable to finish", e);
}
}
}
|
//This code is developed as part of the Java CoG Kit project
//This message may not be removed or altered.
package org.globus.cog.karajan.scheduler;
import java.util.List;
import org.globus.cog.karajan.util.BoundContact;
// I'm terrible with naming classes
public interface ResourceConstraintChecker {
/**
* Checks if a resource meets the given task constraints
*
* @param resource
* the resource to be checked
* @param tc
* the constraints to check the resource against
*
* @return <code>true</code> if the resouce meets the constraints;
* <code>false</code> otherwise
*/
boolean checkConstraints(BoundContact resource, TaskConstraints tc);
/**
* Identifies the resouces in a list meeting the given task constraints
*
* @param resources
* a list of BoundContact objects
* @param tc
* the task constraints
* @return the subset of contacts meeting the given constraints
*
* @see BoundContact
*/
List checkConstraints(List resources, TaskConstraints tc);
}
|
package ca.corefacility.bioinformatics.irida.processing.impl;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.DirectFieldAccessor;
import uk.ac.babraham.FastQC.Graphs.LineGraph;
import uk.ac.babraham.FastQC.Graphs.QualityBoxPlot;
import uk.ac.babraham.FastQC.Modules.BasicStats;
import uk.ac.babraham.FastQC.Modules.PerBaseQualityScores;
import uk.ac.babraham.FastQC.Modules.PerSequenceQualityScores;
import uk.ac.babraham.FastQC.Modules.QCModule;
import uk.ac.babraham.FastQC.Sequence.Sequence;
import uk.ac.babraham.FastQC.Sequence.SequenceFactory;
import uk.ac.babraham.FastQC.Sequence.QualityEncoding.PhredEncoding;
import ca.corefacility.bioinformatics.irida.model.SequenceFile;
import ca.corefacility.bioinformatics.irida.processing.FileProcessor;
import ca.corefacility.bioinformatics.irida.processing.FileProcessorException;
import ca.corefacility.bioinformatics.irida.repositories.SequenceFileRepository;
import com.google.common.collect.ImmutableMap;
/**
* Executes FastQC on a {@link SequenceFile} and stores the report in the
* database. This is a terrible, ugly, hacky class because most of the internal
* statistics computed by FastQC are <code>private</code> fields, so we reflect
* on those fields and make them <code>public</code> to get the values.
*
* @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
*
*/
public class FastqcFileProcessor implements FileProcessor {
private static final Logger logger = LoggerFactory.getLogger(FastqcFileProcessor.class);
private SequenceFileRepository sequenceFileRepository;
public FastqcFileProcessor(SequenceFileRepository sequenceFileRepository) {
this.sequenceFileRepository = sequenceFileRepository;
}
public static void main(String[] args) {
FastqcFileProcessor ffp = new FastqcFileProcessor(null);
Path file = Paths.get("/home/fbristow/27459_S1_L001_R1_001.fastq.gz");
SequenceFile sequenceFile = new SequenceFile(file);
ffp.process(sequenceFile);
}
/**
* {@inheritDoc}
*/
@Override
public SequenceFile process(SequenceFile sequenceFile) throws FileProcessorException {
Path fileToProcess = sequenceFile.getFile();
try {
uk.ac.babraham.FastQC.Sequence.SequenceFile fastQCSequenceFile = SequenceFactory
.getSequenceFile(fileToProcess.toFile());
BasicStats basicStats = new BasicStats();
PerBaseQualityScores pbqs = new PerBaseQualityScores();
PerSequenceQualityScores psqs = new PerSequenceQualityScores();
QCModule[] moduleList = new QCModule[] { basicStats, pbqs, psqs };
logger.debug("Launching FastQC analysis modules on all sequences.");
while (fastQCSequenceFile.hasNext()) {
Sequence sequence = fastQCSequenceFile.next();
for (QCModule module : moduleList) {
module.processSequence(sequence);
}
}
logger.debug("Finished FastQC analysis modules.");
Map<String, Object> updatedProperties = new HashMap<>();
updatedProperties.putAll(handleBasicStats(basicStats));
updatedProperties.putAll(handlePerBaseQualityScores(pbqs));
updatedProperties.putAll(handlePerSequenceQualityScores(psqs));
sequenceFile = sequenceFileRepository.update(sequenceFile.getId(), updatedProperties);
} catch (Exception e) {
logger.error("FastQC failed to process the sequence file. Stack trace follows.", e);
throw new FileProcessorException("FastQC failed to parse the sequence file.");
}
return sequenceFile;
}
/**
* Handle writing the {@link BasicStats} to the database.
*
* @param stats
* the {@link BasicStats} computed by fastqc.
* @return properties suitable for updating a {@link SequenceFile}.
*/
private Map<String, Object> handleBasicStats(BasicStats stats) {
DirectFieldAccessor dfa = new DirectFieldAccessor(stats);
String fileType = (String) dfa.getPropertyValue("fileType");
Character lowestChar = (Character) dfa.getPropertyValue("lowestChar");
Integer minLength = (Integer) dfa.getPropertyValue("minLength");
Integer maxLength = (Integer) dfa.getPropertyValue("maxLength");
Integer totalSequences = (Integer) dfa.getPropertyValue("actualCount");
Integer filteredSequences = (Integer) dfa.getPropertyValue("filteredCount");
String encoding = PhredEncoding.getFastQEncodingOffset(lowestChar).name();
Long aCount = (Long) dfa.getPropertyValue("aCount");
Long cCount = (Long) dfa.getPropertyValue("cCount");
Long gCount = (Long) dfa.getPropertyValue("gCount");
Long tCount = (Long) dfa.getPropertyValue("tCount");
Short gcContent = (short) (((gCount + cCount) * 100) / (aCount + cCount + gCount + tCount));
Map<String, Object> updatedProperties = new HashMap<>();
updatedProperties.put("fileType", fileType);
updatedProperties.put("encoding", encoding);
updatedProperties.put("minLength", minLength);
updatedProperties.put("maxLength", maxLength);
updatedProperties.put("totalSequences", totalSequences);
updatedProperties.put("filteredSequences", filteredSequences);
updatedProperties.put("gcContent", gcContent);
return updatedProperties;
}
/**
* Handle writing the {@link PerBaseQualityScores} to the database.
*
* @param scores
* the {@link PerBaseQualityScores} computed by fastqc.
* @return a map with a single key containing a byte array, png-formatted
* chart.
*/
private Map<String, Object> handlePerBaseQualityScores(PerBaseQualityScores scores) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
QualityBoxPlot bp = (QualityBoxPlot) scores.getResultsPanel();
BufferedImage b = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
Graphics g = b.getGraphics();
bp.paint(g, b.getWidth(), b.getHeight());
ImageIO.write(b, "PNG", os);
byte[] image = os.toByteArray();
return ImmutableMap.of("perBaseQualityScoreChart", (Object) image);
}
/**
* Handle writing the {@link PerSequenceQualityScores} to the database.
*
* @param scores
* the {@link PerSequenceQualityScores} computed by fastqc.
* @return a map with a single key containing a byte array, png-formatted
* chart.
*/
private Map<String, Object> handlePerSequenceQualityScores(PerSequenceQualityScores scores) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
LineGraph lg = (LineGraph) scores.getResultsPanel();
BufferedImage b = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
Graphics g = b.getGraphics();
lg.paint(g, b.getWidth(), b.getHeight());
ImageIO.write(b, "PNG", os);
byte[] image = os.toByteArray();
return ImmutableMap.of("perSequenceQualityScoreChart", (Object) image);
}
/**
* {@inheritDoc}
*/
@Override
public Boolean modifiesFile() {
return false;
}
}
|
package com.bullhornsdk.data.model.entity.core.customobject;
import com.bullhornsdk.data.model.entity.core.type.AbstractEntity;
import com.bullhornsdk.data.model.entity.core.type.CreateEntity;
import com.bullhornsdk.data.model.entity.core.type.DateLastModifiedEntity;
import com.bullhornsdk.data.model.entity.core.type.HardDeleteEntity;
import com.bullhornsdk.data.model.entity.core.type.QueryEntity;
import com.bullhornsdk.data.model.entity.core.type.UpdateEntity;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.joda.time.DateTime;
import java.math.BigDecimal;
public abstract class CustomObjectInstance extends AbstractEntity implements QueryEntity, DateLastModifiedEntity, UpdateEntity, CreateEntity, HardDeleteEntity {
private Integer id;
private String text1;
private String text2;
private String text3;
private String text4;
private String text5;
private String text6;
private String text7;
private String text8;
private String text9;
private String text10;
private String text11;
private String text12;
private String text13;
private String text14;
private String text15;
private String text16;
private String text17;
private String text18;
private String text19;
private String text20;
private Integer int1;
private Integer int2;
private Integer int3;
private Integer int4;
private Integer int5;
private Integer int6;
private Integer int7;
private Integer int8;
private Integer int9;
private Integer int10;
private BigDecimal float1;
private BigDecimal float2;
private BigDecimal float3;
private BigDecimal float4;
private BigDecimal float5;
private BigDecimal float6;
private BigDecimal float7;
private BigDecimal float8;
private BigDecimal float9;
private BigDecimal float10;
private String textBlock1;
private String textBlock2;
private String textBlock3;
private String textBlock4;
private String textBlock5;
private DateTime date1;
private DateTime date2;
private DateTime date3;
private DateTime date4;
private DateTime date5;
private DateTime date6;
private DateTime date7;
private DateTime date8;
private DateTime date9;
private DateTime date10;
private DateTime dateAdded;
private DateTime dateLastModified;
public CustomObjectInstance() {
super();
}
@JsonProperty("id")
public Integer getId() {
return id;
}
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
@JsonProperty("text1")
public String getText1() {
return text1;
}
@JsonProperty("text1")
public void setText1(String text1) {
this.text1 = text1;
}
@JsonProperty("text2")
public String getText2() {
return text2;
}
@JsonProperty("text2")
public void setText2(String text2) {
this.text2 = text2;
}
@JsonProperty("text3")
public String getText3() {
return text3;
}
@JsonProperty("text3")
public void setText3(String text3) {
this.text3 = text3;
}
@JsonProperty("text4")
public String getText4() {
return text4;
}
@JsonProperty("text4")
public void setText4(String text4) {
this.text4 = text4;
}
@JsonProperty("text5")
public String getText5() {
return text5;
}
@JsonProperty("text5")
public void setText5(String text5) {
this.text5 = text5;
}
@JsonProperty("text6")
public String getText6() {
return text6;
}
@JsonProperty("text6")
public void setText6(String text6) {
this.text6 = text6;
}
@JsonProperty("text7")
public String getText7() {
return text7;
}
@JsonProperty("text7")
public void setText7(String text7) {
this.text7 = text7;
}
@JsonProperty("text8")
public String getText8() {
return text8;
}
@JsonProperty("text8")
public void setText8(String text8) {
this.text8 = text8;
}
@JsonProperty("text9")
public String getText9() {
return text9;
}
@JsonProperty("text9")
public void setText9(String text9) {
this.text9 = text9;
}
@JsonProperty("text10")
public String getText10() {
return text10;
}
@JsonProperty("text10")
public void setText10(String text10) {
this.text10 = text10;
}
@JsonProperty("text11")
public String getText11() {
return text11;
}
@JsonProperty("text11")
public void setText11(String text11) {
this.text11 = text11;
}
@JsonProperty("text12")
public String getText12() {
return text12;
}
@JsonProperty("text12")
public void setText12(String text12) {
this.text12 = text12;
}
@JsonProperty("text13")
public String getText13() {
return text13;
}
@JsonProperty("text13")
public void setText13(String text13) {
this.text13 = text13;
}
@JsonProperty("text14")
public String getText14() {
return text14;
}
@JsonProperty("text14")
public void setText14(String text14) {
this.text14 = text14;
}
@JsonProperty("text15")
public String getText15() {
return text15;
}
@JsonProperty("text15")
public void setText15(String text15) {
this.text15 = text15;
}
@JsonProperty("text16")
public String getText16() {
return text16;
}
@JsonProperty("text16")
public void setText16(String text16) {
this.text16 = text16;
}
@JsonProperty("text17")
public String getText17() {
return text17;
}
@JsonProperty("text17")
public void setText17(String text17) {
this.text17 = text17;
}
@JsonProperty("text18")
public String getText18() {
return text18;
}
@JsonProperty("text18")
public void setText18(String text18) {
this.text18 = text18;
}
@JsonProperty("text19")
public String getText19() {
return text19;
}
@JsonProperty("text19")
public void setText19(String text19) {
this.text19 = text19;
}
@JsonProperty("text20")
public String getText20() {
return text20;
}
@JsonProperty("text20")
public void setText20(String text20) {
this.text20 = text20;
}
@JsonProperty("int1")
public Integer getInt1() {
return int1;
}
@JsonProperty("int1")
public void setInt1(Integer int1) {
this.int1 = int1;
}
@JsonProperty("int2")
public Integer getInt2() {
return int2;
}
@JsonProperty("int2")
public void setInt2(Integer int2) {
this.int2 = int2;
}
@JsonProperty("int3")
public Integer getInt3() {
return int3;
}
@JsonProperty("int3")
public void setInt3(Integer int3) {
this.int3 = int3;
}
@JsonProperty("int4")
public Integer getInt4() {
return int4;
}
@JsonProperty("int4")
public void setInt4(Integer int4) {
this.int4 = int4;
}
@JsonProperty("int5")
public Integer getInt5() {
return int5;
}
@JsonProperty("int5")
public void setInt5(Integer int5) {
this.int5 = int5;
}
@JsonProperty("int6")
public Integer getInt6() {
return int6;
}
@JsonProperty("int6")
public void setInt6(Integer int6) {
this.int6 = int6;
}
@JsonProperty("int7")
public Integer getInt7() {
return int7;
}
@JsonProperty("int7")
public void setInt7(Integer int7) {
this.int7 = int7;
}
@JsonProperty("int8")
public Integer getInt8() {
return int8;
}
@JsonProperty("int8")
public void setInt8(Integer int8) {
this.int8 = int8;
}
@JsonProperty("int9")
public Integer getInt9() {
return int9;
}
@JsonProperty("int9")
public void setInt9(Integer int9) {
this.int9 = int9;
}
@JsonProperty("int10")
public Integer getInt10() {
return int10;
}
@JsonProperty("int10")
public void setInt10(Integer int10) {
this.int10 = int10;
}
@JsonProperty("float1")
public BigDecimal getFloat1() {
return float1;
}
@JsonProperty("float1")
public void setFloat1(BigDecimal float1) {
this.float1 = float1;
}
@JsonProperty("float2")
public BigDecimal getFloat2() {
return float2;
}
@JsonProperty("float2")
public void setFloat2(BigDecimal float2) {
this.float2 = float2;
}
@JsonProperty("float3")
public BigDecimal getFloat3() {
return float3;
}
@JsonProperty("float3")
public void setFloat3(BigDecimal float3) {
this.float3 = float3;
}
@JsonProperty("float4")
public BigDecimal getFloat4() {
return float4;
}
@JsonProperty("float4")
public void setFloat4(BigDecimal float4) {
this.float4 = float4;
}
@JsonProperty("float5")
public BigDecimal getFloat5() {
return float5;
}
@JsonProperty("float5")
public void setFloat5(BigDecimal float5) {
this.float5 = float5;
}
@JsonProperty("float6")
public BigDecimal getFloat6() {
return float6;
}
@JsonProperty("float6")
public void setFloat6(BigDecimal float6) {
this.float6 = float6;
}
@JsonProperty("float7")
public BigDecimal getFloat7() {
return float7;
}
@JsonProperty("float7")
public void setFloat7(BigDecimal float7) {
this.float7 = float7;
}
@JsonProperty("float8")
public BigDecimal getFloat8() {
return float8;
}
@JsonProperty("float8")
public void setFloat8(BigDecimal float8) {
this.float8 = float8;
}
@JsonProperty("float9")
public BigDecimal getFloat9() {
return float9;
}
@JsonProperty("float9")
public void setFloat9(BigDecimal float9) {
this.float9 = float9;
}
@JsonProperty("float10")
public BigDecimal getFloat10() {
return float10;
}
@JsonProperty("float10")
public void setFloat10(BigDecimal float10) {
this.float10 = float10;
}
@JsonProperty("textBlock1")
public String getTextBlock1() {
return textBlock1;
}
@JsonProperty("textBlock1")
public void setTextBlock1(String textBlock1) {
this.textBlock1 = textBlock1;
}
@JsonProperty("textBlock2")
public String getTextBlock2() {
return textBlock2;
}
@JsonProperty("textBlock2")
public void setTextBlock2(String textBlock2) {
this.textBlock2 = textBlock2;
}
@JsonProperty("textBlock3")
public String getTextBlock3() {
return textBlock3;
}
@JsonProperty("textBlock3")
public void setTextBlock3(String textBlock3) {
this.textBlock3 = textBlock3;
}
@JsonProperty("textBlock4")
public String getTextBlock4() {
return textBlock4;
}
@JsonProperty("textBlock4")
public void setTextBlock4(String textBlock4) {
this.textBlock4 = textBlock4;
}
@JsonProperty("textBlock5")
public String getTextBlock5() {
return textBlock5;
}
@JsonProperty("textBlock5")
public void setTextBlock5(String textBlock5) {
this.textBlock5 = textBlock5;
}
@JsonProperty("date1")
public DateTime getDate1() {
return date1;
}
@JsonProperty("date1")
public void setDate1(DateTime date1) {
this.date1 = date1;
}
@JsonProperty("date2")
public DateTime getDate2() {
return date2;
}
@JsonProperty("date2")
public void setDate2(DateTime date2) {
this.date2 = date2;
}
@JsonProperty("date3")
public DateTime getDate3() {
return date3;
}
@JsonProperty("date3")
public void setDate3(DateTime date3) {
this.date3 = date3;
}
@JsonProperty("date4")
public DateTime getDate4() {
return date4;
}
@JsonProperty("date4")
public void setDate4(DateTime date4) {
this.date4 = date4;
}
@JsonProperty("date5")
public DateTime getDate5() {
return date5;
}
@JsonProperty("date5")
public void setDate5(DateTime date5) {
this.date5 = date5;
}
@JsonProperty("date6")
public DateTime getDate6() {
return date6;
}
@JsonProperty("date6")
public void setDate6(DateTime date6) {
this.date6 = date6;
}
@JsonProperty("date7")
public DateTime getDate7() {
return date7;
}
@JsonProperty("date7")
public void setDate7(DateTime date7) {
this.date7 = date7;
}
@JsonProperty("date8")
public DateTime getDate8() {
return date8;
}
@JsonProperty("date8")
public void setDate8(DateTime date8) {
this.date8 = date8;
}
@JsonProperty("date9")
public DateTime getDate9() {
return date9;
}
@JsonProperty("date9")
public void setDate9(DateTime date9) {
this.date9 = date9;
}
@JsonProperty("date10")
public DateTime getDate10() {
return date10;
}
@JsonProperty("date10")
public void setDate10(DateTime date10) {
this.date10 = date10;
}
@JsonProperty("dateAdded")
public DateTime getDateAdded() {
return dateAdded;
}
@JsonProperty("dateAdded")
public void setDateAdded(DateTime dateAdded) {
this.dateAdded = dateAdded;
}
@JsonProperty("dateLastModified")
public DateTime getDateLastModified() {
return dateLastModified;
}
@JsonProperty("dateLastModified")
public void setDateLastModified(DateTime dateLastModified) {
this.dateLastModified = dateLastModified;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomObjectInstance that = (CustomObjectInstance) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (text1 != null ? !text1.equals(that.text1) : that.text1 != null) return false;
if (text2 != null ? !text2.equals(that.text2) : that.text2 != null) return false;
if (text3 != null ? !text3.equals(that.text3) : that.text3 != null) return false;
if (text4 != null ? !text4.equals(that.text4) : that.text4 != null) return false;
if (text5 != null ? !text5.equals(that.text5) : that.text5 != null) return false;
if (text6 != null ? !text6.equals(that.text6) : that.text6 != null) return false;
if (text7 != null ? !text7.equals(that.text7) : that.text7 != null) return false;
if (text8 != null ? !text8.equals(that.text8) : that.text8 != null) return false;
if (text9 != null ? !text9.equals(that.text9) : that.text9 != null) return false;
if (text10 != null ? !text10.equals(that.text10) : that.text10 != null) return false;
if (text11 != null ? !text11.equals(that.text11) : that.text11 != null) return false;
if (text12 != null ? !text12.equals(that.text12) : that.text12 != null) return false;
if (text13 != null ? !text13.equals(that.text13) : that.text13 != null) return false;
if (text14 != null ? !text14.equals(that.text14) : that.text14 != null) return false;
if (text15 != null ? !text15.equals(that.text15) : that.text15 != null) return false;
if (text16 != null ? !text16.equals(that.text16) : that.text16 != null) return false;
if (text17 != null ? !text17.equals(that.text17) : that.text17 != null) return false;
if (text18 != null ? !text18.equals(that.text18) : that.text18 != null) return false;
if (text19 != null ? !text19.equals(that.text19) : that.text19 != null) return false;
if (text20 != null ? !text20.equals(that.text20) : that.text20 != null) return false;
if (int1 != null ? !int1.equals(that.int1) : that.int1 != null) return false;
if (int2 != null ? !int2.equals(that.int2) : that.int2 != null) return false;
if (int3 != null ? !int3.equals(that.int3) : that.int3 != null) return false;
if (int4 != null ? !int4.equals(that.int4) : that.int4 != null) return false;
if (int5 != null ? !int5.equals(that.int5) : that.int5 != null) return false;
if (int6 != null ? !int6.equals(that.int6) : that.int6 != null) return false;
if (int7 != null ? !int7.equals(that.int7) : that.int7 != null) return false;
if (int8 != null ? !int8.equals(that.int8) : that.int8 != null) return false;
if (int9 != null ? !int9.equals(that.int9) : that.int9 != null) return false;
if (int10 != null ? !int10.equals(that.int10) : that.int10 != null) return false;
if (float1 != null ? !float1.equals(that.float1) : that.float1 != null) return false;
if (float2 != null ? !float2.equals(that.float2) : that.float2 != null) return false;
if (float3 != null ? !float3.equals(that.float3) : that.float3 != null) return false;
if (float4 != null ? !float4.equals(that.float4) : that.float4 != null) return false;
if (float5 != null ? !float5.equals(that.float5) : that.float5 != null) return false;
if (float6 != null ? !float6.equals(that.float6) : that.float6 != null) return false;
if (float7 != null ? !float7.equals(that.float7) : that.float7 != null) return false;
if (float8 != null ? !float8.equals(that.float8) : that.float8 != null) return false;
if (float9 != null ? !float9.equals(that.float9) : that.float9 != null) return false;
if (float10 != null ? !float10.equals(that.float10) : that.float10 != null) return false;
if (textBlock1 != null ? !textBlock1.equals(that.textBlock1) : that.textBlock1 != null) return false;
if (textBlock2 != null ? !textBlock2.equals(that.textBlock2) : that.textBlock2 != null) return false;
if (textBlock3 != null ? !textBlock3.equals(that.textBlock3) : that.textBlock3 != null) return false;
if (textBlock4 != null ? !textBlock4.equals(that.textBlock4) : that.textBlock4 != null) return false;
if (textBlock5 != null ? !textBlock5.equals(that.textBlock5) : that.textBlock5 != null) return false;
if (date1 != null ? !date1.equals(that.date1) : that.date1 != null) return false;
if (date2 != null ? !date2.equals(that.date2) : that.date2 != null) return false;
if (date3 != null ? !date3.equals(that.date3) : that.date3 != null) return false;
if (date4 != null ? !date4.equals(that.date4) : that.date4 != null) return false;
if (date5 != null ? !date5.equals(that.date5) : that.date5 != null) return false;
if (date6 != null ? !date6.equals(that.date6) : that.date6 != null) return false;
if (date7 != null ? !date7.equals(that.date7) : that.date7 != null) return false;
if (date8 != null ? !date8.equals(that.date8) : that.date8 != null) return false;
if (date9 != null ? !date9.equals(that.date9) : that.date9 != null) return false;
if (date10 != null ? !date10.equals(that.date10) : that.date10 != null) return false;
if (dateAdded != null ? !dateAdded.equals(that.dateAdded) : that.dateAdded != null) return false;
return !(dateLastModified != null ? !dateLastModified.equals(that.dateLastModified) : that.dateLastModified != null);
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (text1 != null ? text1.hashCode() : 0);
result = 31 * result + (text2 != null ? text2.hashCode() : 0);
result = 31 * result + (text3 != null ? text3.hashCode() : 0);
result = 31 * result + (text4 != null ? text4.hashCode() : 0);
result = 31 * result + (text5 != null ? text5.hashCode() : 0);
result = 31 * result + (text6 != null ? text6.hashCode() : 0);
result = 31 * result + (text7 != null ? text7.hashCode() : 0);
result = 31 * result + (text8 != null ? text8.hashCode() : 0);
result = 31 * result + (text9 != null ? text9.hashCode() : 0);
result = 31 * result + (text10 != null ? text10.hashCode() : 0);
result = 31 * result + (text11 != null ? text11.hashCode() : 0);
result = 31 * result + (text12 != null ? text12.hashCode() : 0);
result = 31 * result + (text13 != null ? text13.hashCode() : 0);
result = 31 * result + (text14 != null ? text14.hashCode() : 0);
result = 31 * result + (text15 != null ? text15.hashCode() : 0);
result = 31 * result + (text16 != null ? text16.hashCode() : 0);
result = 31 * result + (text17 != null ? text17.hashCode() : 0);
result = 31 * result + (text18 != null ? text18.hashCode() : 0);
result = 31 * result + (text19 != null ? text19.hashCode() : 0);
result = 31 * result + (text20 != null ? text20.hashCode() : 0);
result = 31 * result + (int1 != null ? int1.hashCode() : 0);
result = 31 * result + (int2 != null ? int2.hashCode() : 0);
result = 31 * result + (int3 != null ? int3.hashCode() : 0);
result = 31 * result + (int4 != null ? int4.hashCode() : 0);
result = 31 * result + (int5 != null ? int5.hashCode() : 0);
result = 31 * result + (int6 != null ? int6.hashCode() : 0);
result = 31 * result + (int7 != null ? int7.hashCode() : 0);
result = 31 * result + (int8 != null ? int8.hashCode() : 0);
result = 31 * result + (int9 != null ? int9.hashCode() : 0);
result = 31 * result + (int10 != null ? int10.hashCode() : 0);
result = 31 * result + (float1 != null ? float1.hashCode() : 0);
result = 31 * result + (float2 != null ? float2.hashCode() : 0);
result = 31 * result + (float3 != null ? float3.hashCode() : 0);
result = 31 * result + (float4 != null ? float4.hashCode() : 0);
result = 31 * result + (float5 != null ? float5.hashCode() : 0);
result = 31 * result + (float6 != null ? float6.hashCode() : 0);
result = 31 * result + (float7 != null ? float7.hashCode() : 0);
result = 31 * result + (float8 != null ? float8.hashCode() : 0);
result = 31 * result + (float9 != null ? float9.hashCode() : 0);
result = 31 * result + (float10 != null ? float10.hashCode() : 0);
result = 31 * result + (textBlock1 != null ? textBlock1.hashCode() : 0);
result = 31 * result + (textBlock2 != null ? textBlock2.hashCode() : 0);
result = 31 * result + (textBlock3 != null ? textBlock3.hashCode() : 0);
result = 31 * result + (textBlock4 != null ? textBlock4.hashCode() : 0);
result = 31 * result + (textBlock5 != null ? textBlock5.hashCode() : 0);
result = 31 * result + (date1 != null ? date1.hashCode() : 0);
result = 31 * result + (date2 != null ? date2.hashCode() : 0);
result = 31 * result + (date3 != null ? date3.hashCode() : 0);
result = 31 * result + (date4 != null ? date4.hashCode() : 0);
result = 31 * result + (date5 != null ? date5.hashCode() : 0);
result = 31 * result + (date6 != null ? date6.hashCode() : 0);
result = 31 * result + (date7 != null ? date7.hashCode() : 0);
result = 31 * result + (date8 != null ? date8.hashCode() : 0);
result = 31 * result + (date9 != null ? date9.hashCode() : 0);
result = 31 * result + (date10 != null ? date10.hashCode() : 0);
result = 31 * result + (dateAdded != null ? dateAdded.hashCode() : 0);
result = 31 * result + (dateLastModified != null ? dateLastModified.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "CustomObjectInstance{" +
"id=" + id +
", text1='" + text1 + '\'' +
", text2='" + text2 + '\'' +
", text3='" + text3 + '\'' +
", text4='" + text4 + '\'' +
", text5='" + text5 + '\'' +
", text6='" + text6 + '\'' +
", text7='" + text7 + '\'' +
", text8='" + text8 + '\'' +
", text9='" + text9 + '\'' +
", text10='" + text10 + '\'' +
", text11='" + text11 + '\'' +
", text12='" + text12 + '\'' +
", text13='" + text13 + '\'' +
", text14='" + text14 + '\'' +
", text15='" + text15 + '\'' +
", text16='" + text16 + '\'' +
", text17='" + text17 + '\'' +
", text18='" + text18 + '\'' +
", text19='" + text19 + '\'' +
", text20='" + text20 + '\'' +
", int1=" + int1 +
", int2=" + int2 +
", int3=" + int3 +
", int4=" + int4 +
", int5=" + int5 +
", int6=" + int6 +
", int7=" + int7 +
", int8=" + int8 +
", int9=" + int9 +
", int10=" + int10 +
", float1=" + float1 +
", float2=" + float2 +
", float3=" + float3 +
", float4=" + float4 +
", float5=" + float5 +
", float6=" + float6 +
", float7=" + float7 +
", float8=" + float8 +
", float9=" + float9 +
", float10=" + float10 +
", textBlock1='" + textBlock1 + '\'' +
", textBlock2='" + textBlock2 + '\'' +
", textBlock3='" + textBlock3 + '\'' +
", textBlock4='" + textBlock4 + '\'' +
", textBlock5='" + textBlock5 + '\'' +
", date1=" + date1 +
", date2=" + date2 +
", date3=" + date3 +
", date4=" + date4 +
", date5=" + date5 +
", date6=" + date6 +
", date7=" + date7 +
", date8=" + date8 +
", date9=" + date9 +
", date10=" + date10 +
", dateAdded=" + dateAdded +
", dateLastModified=" + dateLastModified +
'}';
}
}
|
package com.github.mikhailerofeev.mars.calendar.model.values.time;
import org.joda.time.*;
import org.springframework.web.bind.MethodArgumentNotValidException;
public class PlanetDateTime {
private DateTime timePoint = null;
private DateTime epoch = null;
private PlanetCalendar calendar = null;
private Duration solDuration;
private Integer year = null;
private Integer monthNum = null; // from 1 ...
private Integer sol = null; // from 1 ...
private Integer hour = null; // from 1 ...
private Integer minute = null; // from 1 ...
private Integer second = null; // from 1 ...
private Integer week = null; // from 1 ...
@SuppressWarnings("UnusedDeclaration")
public PlanetDateTime() {
this.timePoint = DateTime.now();
this.epoch = new DateTime(0);
}
@SuppressWarnings("UnusedDeclaration")
public PlanetDateTime(DateTime timePoint) {
this.timePoint = timePoint;
this.epoch = new DateTime(0);
}
@SuppressWarnings("UnusedDeclaration")
public PlanetDateTime(DateTime timePoint, DateTime epoch) {
this.timePoint = timePoint;
this.epoch = epoch;
}
public PlanetDateTime(long unixTimeStamp) {
this.timePoint = new DateTime(unixTimeStamp);
this.epoch = new DateTime(0);
}
public PlanetDateTime(long unixTimeStamp, long epoch) {
this.timePoint = new DateTime(unixTimeStamp);
this.epoch = new DateTime(epoch);
}
public PlanetDateTime(DateTime timePoint, DateTime epoch, PlanetCalendar calendar, Duration solDuration) {
this.timePoint = timePoint;
this.epoch = epoch;
this.calendar = calendar;
this.solDuration = solDuration;
}
public PlanetDateTime(DateTime epoch, int year, int monthNum, int sol, int hour, int minute, int second) {
this.epoch = epoch;
this.year = year;
this.monthNum = monthNum;
this.sol = sol;
this.hour = hour;
this.minute = minute;
this.second = second;
MutableDateTime mutableTimePoint = new MutableDateTime(calendar.solsInLeapPeriod() * solDuration.getMillis());
int yearsUntilCurrentCalc = year - (year % calendar.getLeapPeriod().size());
while (yearsUntilCurrentCalc <= year) {
mutableTimePoint.add(calendar.solsInYear(yearsUntilCurrentCalc) * solDuration.getMillis());
++yearsUntilCurrentCalc;
}
--yearsUntilCurrentCalc;
for (int currentMonth = 0; currentMonth < monthNum - 1; ++currentMonth) {
mutableTimePoint.add(calendar.solsInMonth(yearsUntilCurrentCalc, monthNum) * solDuration.getMillis());
}
for (int currentSol = 0; currentSol < sol - 1; ++currentSol) {
mutableTimePoint.add(solDuration.getMillis());
}
for (int currentHour = 0; currentHour < hour; ++currentHour) {
mutableTimePoint.add(3600000);
}
for (int currentMinute = 0; currentMinute < minute; ++currentMinute) {
mutableTimePoint.add(60000);
}
for (int currentSecond = 0; currentSecond < second; ++currentSecond) {
mutableTimePoint.add(1000);
}
}
public Duration timeSinceEpoch() {
return new Duration(epoch, timePoint);
}
private double solsSinceEpoch() {
return timeSinceEpoch().getMillis() / solDuration.getMillis();
}
public long wholeSolsSinceEpoch() {
return (long)solsSinceEpoch();
}
public Duration durationSinceSolStart() {
return new Duration(timeSinceEpoch().getMillis() % solDuration.getMillis());
}
public DateTime toTerrestrial() {
return timePoint;
}
public DateTime getTimePoint() {
return timePoint;
}
public DateTime getEpoch() {
return epoch;
}
public PlanetCalendar getCalendar() {
return calendar;
}
public Duration getSolDuration() {
return solDuration;
}
/**
*
* @param year
* @return terrestrial duration of the specific year
*/
public Duration yearDuration(int year) {
return new Duration(solDuration.getMillis() * calendar.solsInYear(year));
}
public Duration monthDuration(int year, int month) {
return new Duration(solDuration.getMillis() * calendar.solsInMonth(year, month));
}
private void calcTime() {
long wholeSolsSinceEpoch = wholeSolsSinceEpoch();
long solsInLeapPeriod = calendar.solsInLeapPeriod();
int periodsSinceEpoch = (int)(wholeSolsSinceEpoch / solsInLeapPeriod);
year = periodsSinceEpoch * calendar.getLeapPeriod().size();
long solsElapsedUntilCurrentCalc = periodsSinceEpoch * calendar.solsInLeapPeriod();
// may need to be changed to 1 (instead of 0)
while (solsElapsedUntilCurrentCalc <= wholeSolsSinceEpoch) {
solsElapsedUntilCurrentCalc += calendar.solsInYear(year);
++year;
}
solsElapsedUntilCurrentCalc -= calendar.solsInYear(year - 1);
//--year; // because we return the nearest PREVIOUS year, not the NEXT one (!!!)
// -- by now, the year is supposed to be calculated -- //
monthNum = 0;
while (solsElapsedUntilCurrentCalc <= wholeSolsSinceEpoch) {
// we use the month starting from zero here as it accesses the list
solsElapsedUntilCurrentCalc += calendar.solsInMonth(year, monthNum);
++monthNum;
}
solsElapsedUntilCurrentCalc -= calendar.solsInMonth(year, monthNum);
// no need to decrement sol because it should start from 0 (!!!)
// -- by now, we have month -- //
sol = 0;
while (solsElapsedUntilCurrentCalc < wholeSolsSinceEpoch) {
++sol;
++solsElapsedUntilCurrentCalc;
}
++sol; // because it should start from 1
// sol calculated
long hoursElapsedUntilCurrentCalc = solsElapsedUntilCurrentCalc * solDuration.getMillis() / 3600000;
long totalHoursElapsed = timeSinceEpoch().getStandardHours();
hour = 0;
while (hoursElapsedUntilCurrentCalc < totalHoursElapsed) {
++hoursElapsedUntilCurrentCalc;
++hour;
}
// hour calculated
long minutesElapsedUntilCurrentCalc = hoursElapsedUntilCurrentCalc * 60;
long totalMinutesElapsed = timeSinceEpoch().getStandardMinutes();
minute = 0;
while (minutesElapsedUntilCurrentCalc < totalMinutesElapsed) {
++minutesElapsedUntilCurrentCalc;
++minute;
}
// minute calculated
long secondsElapsedUntilCurrentCalc = minutesElapsedUntilCurrentCalc * 60;
long totalSecondsElapsed = timeSinceEpoch().getStandardSeconds();
second = 0;
while (secondsElapsedUntilCurrentCalc < totalSecondsElapsed) {
++secondsElapsedUntilCurrentCalc;
++second;
}
// second calculated
// kludges:
if (hour == solDuration.getStandardHours()) hour = 0;
if (minute == 60) minute = 0;
if (second == 60) second = 0;
}
/**
* returns the year in the natural form
* @return
*/
public int getYear() {
if (year == null) calcTime();
return year;
}
/**
*
* @return month number starting from 1
*/
public int getMonthNum() {
if (monthNum == null) calcTime();
return monthNum;
}
/**
*
* @return month object (if you need month number use getMonthNum instead)
*/
public PlanetMonth getMonth() {
return calendar.getMonths().get(getMonthNum() - 1);
}
/**
*
* @return sol number starting with 1
*/
public int getSol() {
if (sol == null) calcTime();
return sol;
}
@SuppressWarnings("UnusedDeclaration")
public long getHour() {
if (hour == null) calcTime();
return hour;
}
public long getMinute() {
if (minute == null) calcTime();
return minute;
}
public long getSecond() {
if (second == null) calcTime();
return second;
}
/**
*
* @return week number starting with 1
*/
public int getWeek(){
if (week == null) {
if (calendar.weekRestarts()) {
// we use sol minus one because getSol returns the number of the sol for normal humans
// (i.e. starting from 1)
week = (getSol() - 1) / calendar.getWeekSols().size() + 1;
} else {
week = (int)(wholeSolsSinceEpoch() / calendar.getWeekSols().size() + 1);
}
}
return week;
}
}
|
package org.chocosolver.solver.propagation.hardcoded;
import org.chocosolver.solver.ICause;
import org.chocosolver.solver.Model;
import org.chocosolver.solver.Settings;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.constraints.Propagator;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.exception.SolverException;
import org.chocosolver.solver.propagation.IPropagationEngine;
import org.chocosolver.solver.propagation.PropagationTrigger;
import org.chocosolver.solver.variables.Variable;
import org.chocosolver.solver.variables.events.IEventType;
import org.chocosolver.solver.variables.events.PropagatorEventType;
import org.chocosolver.util.iterators.EvtScheduler;
import org.chocosolver.util.objects.IntCircularQueue;
import org.chocosolver.util.objects.IntMap;
import org.chocosolver.util.objects.queues.CircularQueue;
import java.util.ArrayList;
import java.util.List;
/**
* This engine is priority-driven constraint-oriented seven queues engine.
* <br/>On a call to {@code onVariableUpdate}, it stores the event generated and schedules the propagator in
* one of the 7 queues wrt to its priority for future revision.
* <p>
* <br/>
*
* @author Charles Prud'homme
* @since 05/07/12
*/
public class SevenQueuesPropagatorEngine implements IPropagationEngine {
/**
* Mask to deal with emptiness (see {@link #notEmpty})
*/
private static final int WORD_MASK = 0xffffffff;
/**
* For debugging purpose: set to <tt>true</tt> to output debugging information
*/
private final boolean DEBUG;
/**
* For debugging purpose: set to <tt>true</tt> to use color on console when debugging
*/
private final boolean COLOR;
/**
* The strategy to use for idempotency (for debugging purpose)
*/
private final Settings.Idem idemStrat;
/**
* Internal unique contradiction exception, used on propagation failures
*/
private final ContradictionException exception;
/**
* The model declaring this engine
*/
private final Model model;
/**
* The array of propagators to execute
*/
private Propagator[] propagators;
/**
* The main structure of this engine: seven circular queues,
* each of them is dedicated to store propagator to execute wrt their priority.
*/
private final CircularQueue<Propagator>[] pro_queue;
/**
* The last propagator executed
*/
private Propagator lastProp;
/**
* Mapping between propagator ID and its absolute index
*/
private IntMap p2i;
/**
* One bit per queue: true if the queue is not empty.
*/
private int notEmpty;
/**
* Per propagator: indicates whether it is scheduled (and in which queue) or not.
*/
private short[] scheduled;
/**
* Per propagator: set of (variable) events to propagate
*/
private IntCircularQueue[] eventsets;
/**
* Set to <tt>true</tt> once {@link #initialize()} has been called.
*/
private boolean init;
/**
* Per propagator (i) and per variable of the propagator (j): modification event mask of variable j from propagator i
* since the last propagation of propagator j.
*/
private int[][] eventmasks;
/**
* Per propagator: counter of events to be propagated
*/
private int[] pendingEvt;
/**
* A specific object to deal with first propagation
*/
private final PropagationTrigger trigger; // an object that starts the propagation
/**
* A seven-queue propagation engine.
* Each of the seven queues deals with on priority.
* When a propagator needs to be executed, it is scheduled in the queue corresponding to its priority.
* The lowest priority queue is emptied before one element of the second lowest queue is popped, etc.
* @param model the declaring model
*/
public SevenQueuesPropagatorEngine(Model model) {
this.exception = new ContradictionException();
this.trigger = new PropagationTrigger(this, model);
this.idemStrat = model.getSettings().getIdempotencyStrategy();
this.model = model;
//noinspection unchecked
this.pro_queue = new CircularQueue[8];
this.DEBUG = model.getSettings().debugPropagation();
this.COLOR = model.getSettings().outputWithANSIColors();
}
@Override
public void fails(ICause cause, Variable variable, String message) throws ContradictionException {
throw exception.set(cause, variable, message);
}
@Override
public ContradictionException getContradictionException() {
return exception;
}
@Override
public void initialize() throws SolverException{
if (!init) {
List<Propagator> _propagators = new ArrayList<>();
Constraint[] constraints = model.getCstrs();
int nbProp = 0;
for (int c = 0; c < constraints.length; c++) {
Propagator[] cprops = constraints[c].getPropagators();
for (int j = 0; j < cprops.length; j++, nbProp++) {
_propagators.add(cprops[j]);
}
}
propagators = _propagators.toArray(new Propagator[_propagators.size()]);
p2i = new IntMap(propagators.length);
for (int j = 0; j < propagators.length; j++) {
if(p2i.containsKey(propagators[j].getId())){
throw new SolverException("The following propagator " +
"is declared more than once into the propagation engine " +
"(this happens when a constraint is posted twice " +
"or when a posted constraint is also reified.)\n" +
propagators[j]+" of "+propagators[j].getConstraint());
}
p2i.put(propagators[j].getId(), j);
}
for (int i = 0; i < 8; i++) {
pro_queue[i] = new CircularQueue<>(16);
}
scheduled = new short[nbProp];
pendingEvt = new int[nbProp];
eventsets = new IntCircularQueue[nbProp];
eventmasks = new int[nbProp][];
for (int i = 0; i < nbProp; i++) {
int nbv = propagators[i].getNbVars();
if (propagators[i].reactToFineEvent()) {
eventsets[i] = new IntCircularQueue(nbv);
eventmasks[i] = new int[nbv];
}
}
notEmpty = 0;
init = true;
}
trigger.addAll(propagators);
}
@Override
public boolean isInitialized() {
return init;
}
@SuppressWarnings({"NullableProblems"})
@Override
public void propagate() throws ContradictionException {
int mask, aid;
IntCircularQueue evtset;
if (trigger.needToRun()) {
trigger.propagate();
}
for (int i = nextNotEmpty(0); i > -1; i = nextNotEmpty(0)) {
while (!pro_queue[i].isEmpty()) {
lastProp = pro_queue[i].pollFirst();
// revision of the variable
aid = p2i.get(lastProp.getId());
scheduled[aid] = 0;
if (lastProp.reactToFineEvent()) {
evtset = eventsets[aid];
while (evtset.size() > 0) {
int v = evtset.pollFirst();
assert lastProp.isActive() : "propagator is not active:" + lastProp;
if (DEBUG) {
IPropagationEngine.Trace.printPropagation(lastProp.getVar(v), lastProp, COLOR);
}
// clear event
mask = eventmasks[aid][v];
eventmasks[aid][v] = 0;
assert (pendingEvt[aid] > 0) : "number of enqueued records is <= 0 " + this;
pendingEvt[aid]
// run propagation on the specific event
lastProp.propagate(v, mask);
}
// now we can check whether a delayed propagation has been scheduled
if(scheduled[aid]>0){
if (DEBUG) {
IPropagationEngine.Trace.printPropagation(null, lastProp, COLOR);
}
mask = scheduled[aid];
scheduled[aid] = 0;
lastProp.propagate(mask);
}
} else if (lastProp.isActive()) { // need to be checked due to views
//assert lastProp.isActive() : "propagator is not active:" + lastProp;
if (DEBUG) {
IPropagationEngine.Trace.printPropagation(null, lastProp, COLOR);
}
lastProp.propagate(PropagatorEventType.FULL_PROPAGATION.getMask());
}
// This part is for debugging only!!
if (Settings.Idem.disabled != idemStrat) {
FakeEngine.checkIdempotency(lastProp);
}
}
notEmpty = notEmpty & ~(1 << i);
}
}
private int nextNotEmpty(int fromIndex) {
int word = notEmpty & (WORD_MASK << fromIndex);
if (word != 0) {
return Integer.numberOfTrailingZeros(word);
} else {
return -1;
}
}
@Override
public void flush() {
if (lastProp != null) {
flush(p2i.get(lastProp.getId()));
}
for (int i = nextNotEmpty(0); i > -1; i = nextNotEmpty(i + 1)) {
while (!pro_queue[i].isEmpty()) {
lastProp = pro_queue[i].pollFirst();
// revision of the variable
flush(p2i.get(lastProp.getId()));
}
notEmpty = notEmpty & ~(1 << i);
}
}
private void flush(int aid) {
IntCircularQueue evtset;
if (lastProp.reactToFineEvent()) {
evtset = eventsets[aid];
while (evtset.size() > 0) {
int v = evtset.pollFirst();
eventmasks[aid][v] = 0;
}
evtset.clear();
pendingEvt[aid] = 0;
}
scheduled[aid] = 0;
}
@Override
public void onVariableUpdate(Variable variable, IEventType type, ICause cause) {
if (DEBUG) {
IPropagationEngine.Trace.printModification(variable, type, cause, COLOR);
}
Propagator[] vpropagators = variable.getPropagators();
int[] vindices = variable.getPIndices();
Propagator prop;
int pindice;
EvtScheduler si = variable._schedIter();
//noinspection unchecked
si.init(type);
while (si.hasNext()) {
int p = variable.getDindex(si.next());
int t = variable.getDindex(si.next());
for (; p < t; p++) {
prop = vpropagators[p];
pindice = vindices[p];
if (prop.isActive() && cause != prop) {
int aid = p2i.get(prop.getId());
if (prop.reactToFineEvent()) {
boolean needSched = (eventmasks[aid][pindice] == 0);
eventmasks[aid][pindice] |= type.getMask();
if (needSched) {
if (DEBUG) {
IPropagationEngine.Trace.printFineSchedule(prop, COLOR);
}
assert (pendingEvt[aid] >= 0) : "number of enqueued records is < 0 " + this;
pendingEvt[aid]++;
eventsets[aid].addLast(pindice);
}
}
if (scheduled[aid] == 0) {
int prio = /*dynamic ? prop.dynPriority() :*/ prop.getPriority().priority;
pro_queue[prio].addLast(prop);
scheduled[aid] = (short) (prio + 1);
// notEmpty.set(prio);
notEmpty = notEmpty | (1 << prio);
if (DEBUG) {
IPropagationEngine.Trace.printCoarseSchedule(prop, COLOR);
}
}
}
}
}
}
@Override
public void delayedPropagation(Propagator propagator, PropagatorEventType type) throws ContradictionException {
assert scheduled[p2i.get(propagator.getId())] == 0 || scheduled[p2i.get(propagator.getId())] == type.getMask();
scheduled[p2i.get(propagator.getId())] = (short) type.getMask();
}
@Override
public void onPropagatorExecution(Propagator propagator) {
desactivatePropagator(propagator);
}
@Override
public void desactivatePropagator(Propagator propagator) {
if (propagator.reactToFineEvent()) {
int pid = propagator.getId();
int aid = p2i.get(pid);
if (aid > -1) {
assert aid > -1 : "try to desactivate an unknown constraint";
// we don't remove the element from its master to avoid costly operations
IntCircularQueue evtset = eventsets[aid];
while (evtset.size() > 0) {
int v = evtset.pollFirst();
eventmasks[aid][v] = 0;
}
evtset.clear();
pendingEvt[aid] = 0;
}
}
}
@Override
public void clear() {
propagators = null;
trigger.clear();
p2i = null;
for (int i = 0; i < 8; i++) {
pro_queue[i] = null;
}
scheduled = null;
eventsets = null;
eventmasks = null;
notEmpty = 0;
init = false;
}
@Override
public void dynamicAddition(boolean permanent, Propagator... ps) throws SolverException{
int osize = propagators.length;
int nbp = ps.length;
int nsize = osize + nbp;
Propagator[] _propagators = propagators;
propagators = new Propagator[nsize];
System.arraycopy(_propagators, 0, propagators, 0, osize);
System.arraycopy(ps, 0, propagators, osize, nbp);
for (int j = osize; j < nsize; j++) {
if(p2i.containsKey(propagators[j].getId())){
throw new SolverException("The following propagator " +
"is declared more than once into the propagation engine " +
"(this happens when a constraint is posted twice " +
"or when a posted constraint is also reified.)\n" +
propagators[j]+" of "+propagators[j].getConstraint());
}
p2i.put(propagators[j].getId(), j);
trigger.dynAdd(propagators[j], permanent);
}
short[] _scheduled = scheduled;
scheduled = new short[nsize];
System.arraycopy(_scheduled, 0, scheduled, 0, osize);
int[] _pendingEvt = pendingEvt;
pendingEvt = new int[nsize];
System.arraycopy(_pendingEvt, 0, pendingEvt, 0, osize);
IntCircularQueue[] _eventsets = eventsets;
eventsets = new IntCircularQueue[nsize];
System.arraycopy(_eventsets, 0, eventsets, 0, osize);
int[][] _eventmasks = eventmasks;
eventmasks = new int[nsize][];
System.arraycopy(_eventmasks, 0, eventmasks, 0, osize);
for (int i = osize; i < nsize; i++) {
if (propagators[i].reactToFineEvent()) {
int nbv = propagators[i].getNbVars();
eventsets[i] = new IntCircularQueue(nbv);
eventmasks[i] = new int[nbv];
}
}
}
@Override
public void updateInvolvedVariables(Propagator p) {
if (p.reactToFineEvent()) {
int i = p2i.get(p.getId());
assert scheduled[i] == 0 : "Try to update variable scope during propagation";
int nbv = p.getNbVars();
eventsets[i] = new IntCircularQueue(nbv);
eventmasks[i] = new int[nbv];
}
propagateOnBacktrack(p); // TODO: when p is not permanent AND a new var is added ... well, one looks for trouble!
}
@Override
public void propagateOnBacktrack(Propagator p) {
trigger.dynAdd(p, true);
}
@Override
public void dynamicDeletion(Propagator... ps) {
for (Propagator toDelete : ps) {
int nsize = propagators.length - 1;
Propagator toMove = propagators[nsize];
int idtd = p2i.get(toDelete.getId());
int idtm = p2i.get(toMove.getId());
p2i.clear(toDelete.getId());
assert idtd <= idtm : "wrong id for prop to delete";
// 1. remove from propagators[] and p2i
Propagator[] _propagators = propagators;
propagators = new Propagator[nsize];
System.arraycopy(_propagators, 0, propagators, 0, nsize);
// 2. resize scheduled
short stm = scheduled[idtm];
assert scheduled[idtd] == 0 : "try to delete a propagator which is scheduled (fine)";
short[] _scheduled = scheduled;
scheduled = new short[nsize];
System.arraycopy(_scheduled, 0, scheduled, 0, nsize);
// 3. resize scheduled
int ptm = pendingEvt[idtm];
assert pendingEvt[idtd] == 0 : "try to delete a propagator which is scheduled (fine)";
int[] _pendingEvt = pendingEvt;
pendingEvt = new int[nsize];
System.arraycopy(_pendingEvt, 0, pendingEvt, 0, nsize);
// 4. remove eventsets
IntCircularQueue estm = eventsets[idtm];
assert !toDelete.reactToFineEvent() || eventsets[idtd].isEmpty() : "try to delete a propagator which has events to propagate (fine)";
IntCircularQueue[] _eventsets = eventsets;
eventsets = new IntCircularQueue[nsize];
System.arraycopy(_eventsets, 0, eventsets, 0, nsize);
// 5. remove eventmasks
int[] emtm = eventmasks[idtm];
// assert eventmasks[idtd]. : "try to delete a propagator which has events to propagate (fine)";
int[][] _eventmasks = eventmasks;
eventmasks = new int[nsize][];
System.arraycopy(_eventmasks, 0, eventmasks, 0, nsize);
// 6. copy data
if (idtd < nsize) {
propagators[idtd] = toMove;
p2i.put(toMove.getId(), idtd);
scheduled[idtd] = stm;
pendingEvt[idtd] = ptm;
eventsets[idtd] = estm;
eventmasks[idtd] = emtm;
}
trigger.remove(toDelete);
}
}
}
|
package uk.ac.ebi.pride.archive.web.service.controller.protein;
import com.mangofactory.swagger.annotations.ApiIgnore;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import uk.ac.ebi.pride.archive.security.protein.ProteinIdentificationSecureSearchService;
import uk.ac.ebi.pride.archive.web.service.model.protein.ProteinDetail;
import uk.ac.ebi.pride.archive.web.service.model.protein.ProteinDetailList;
import uk.ac.ebi.pride.archive.web.service.util.ObjectMapper;
import uk.ac.ebi.pride.proteinidentificationindex.search.model.ProteinIdentification;
import java.util.List;
import java.util.Set;
/**
* @author Florian Reisinger
* @since 1.0.8
*/
@Api(value = "protein", description = "retrieve protein identifications", position = 3)
@Controller
@RequestMapping(value = "/protein")
public class ProteinController {
private static final Logger logger = LoggerFactory.getLogger(ProteinController.class);
protected static final int DEFAULT_SHOW = 10;
protected static final int DEFAULT_PAGE = 0;
@Autowired
ProteinIdentificationSecureSearchService pissService; // ToDo: find a better name ;)
// ToDo: count methods once available in the service
// ToDo: performance tests (page sizes, security impact), and perhaps max number of retrievable (page size) results
// not available as not secured yet
// @ApiOperation(value = "retrieve protein identifications by protein identifier", position = 1)
// @RequestMapping(value = "/{proteinId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
// @ResponseStatus(HttpStatus.OK) // 200
// public
// @ResponseBody
// ProteinDetailList getProteinSummary(
// @ApiParam(value = "a protein identifier")
// @PathVariable("proteinId") String id,
// @ApiParam(value = "whether to include alternative protein ids")
// @RequestParam(value = "includeSynonyms", required = false, defaultValue = "false") boolean includeSynonyms
// logger.info("Protein " + id + " summary requested");
// List<ProteinIdentified> foundProteins;
// if (includeSynonyms) {
// foundProteins = proteinIdentificationSearchService.findBySynonyms(id);
// } else {
// foundProteins = proteinIdentificationSearchService.findByAccession(id);
// // convert the searches List of ProteinIdentified objects into the WS ProteinDetail objects
// List<ProteinDetail> resultProteins = ObjectMapper.mapProteinIdentifiedListToWSProteinDetailList(foundProteins);
// return new ProteinDetailList(resultProteins);
@ApiOperation(value = "retrieve protein identifications by project accession", position = 2)
@RequestMapping(value = "/list/project/{projectAccession}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK) // 200
public
@ResponseBody
ProteinDetailList getProteinsByProject(
@ApiParam(value = "a project accession")
@PathVariable("projectAccession") String projectAccession,
@ApiParam(value = "how many results to show per page")
@RequestParam(value = "show", required = false, defaultValue = DEFAULT_SHOW+"") int showResults,
@ApiParam(value = "which page of the result to return")
@RequestParam(value = "page", required = false, defaultValue = DEFAULT_PAGE+"") int page
) {
logger.info("Proteins for project " + projectAccession + " requested");
List<ProteinIdentification> foundProteins = pissService.findByProjectAccession(projectAccession, new PageRequest(page, showResults)).getContent();
// convert the searches List of ProteinIdentified objects into the WS ProteinDetail objects
List<ProteinDetail>resultProteins = ObjectMapper.mapProteinIdentifiedListToWSProteinDetailList(foundProteins);
return new ProteinDetailList(resultProteins);
}
@ApiOperation(value = "count protein identifications by project accession", position = 3)
@RequestMapping(value = "/count/project/{projectAccession}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK) // 200
public
@ResponseBody
Long countProteinsByProject(
@ApiParam(value = "a project accession")
@PathVariable("projectAccession") String projectAccession
) {
logger.info("Protein count for project " + projectAccession + " requested");
return pissService.countByProjectAccession(projectAccession);
}
@ApiOperation(value = "retrieve protein identifications by assay accession", position = 4)
@RequestMapping(value = "/list/assay/{assayAccession}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK) // 200
public
@ResponseBody
ProteinDetailList getProteinsByAssay(
@ApiParam(value = "an assay accession")
@PathVariable("assayAccession") String assayAccession,
@ApiParam(value = "how many results to show per page")
@RequestParam(value = "show", required = false, defaultValue = DEFAULT_SHOW+"") int showResults,
@ApiParam(value = "which page of the result to return")
@RequestParam(value = "page", required = false, defaultValue = DEFAULT_PAGE+"") int page
) {
logger.info("Proteins for assay " + assayAccession + " requested");
List<ProteinIdentification> foundProteins = pissService.findByAssayAccession(assayAccession, new PageRequest(page, showResults)).getContent();
// convert the searches List of ProteinIdentified objects into the WS ProteinDetail objects
List<ProteinDetail> resultProteins = ObjectMapper.mapProteinIdentifiedListToWSProteinDetailList(foundProteins);
return new ProteinDetailList(resultProteins);
}
@ApiOperation(value = "count protein identifications by assay accession", position = 4)
@RequestMapping(value = "/count/assay/{assayAccession}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK) // 200
public
@ResponseBody
Long countProteinsByAssay(
@ApiParam(value = "an assay accession")
@PathVariable("assayAccession") String assayAccession
) {
logger.info("Proteins for assay " + assayAccession + " requested");
return pissService.countByAssayAccession(assayAccession);
}
@ApiIgnore
@RequestMapping(value = "/list/assay/{assayAccession}.acc", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
@ResponseStatus(HttpStatus.OK) // 200
public
@ResponseBody
String getProteinListForAssay(
@ApiParam(value = "an assay accession")
@PathVariable("assayAccession") String assayAccession,
@ApiParam(value = "filter accessions (to remove decoy, reverse, etc accessions)")
@RequestParam(value = "filter", required = false, defaultValue = "true") boolean filter
) {
logger.info("Protein accessions for assay " + assayAccession + " requested");
StringBuilder sb = new StringBuilder();
sb.append("#PRIDE assay:").append(assayAccession).append("\n");
Set<String> accessions = pissService.getUniqueProteinAccessionsByAssayAccession(assayAccession);
for (String accession : accessions) {
if (filter && !isValidAccession(accession)) {
// if filtering is enabled, we apply accession filtering to remove decoy, etc accessions
continue;
}
sb.append(accession).append("\n");
}
return sb.toString();
}
@ApiIgnore
@RequestMapping(value = "/list/project/{projectAccession}.acc", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
@ResponseStatus(HttpStatus.OK) // 200
public
@ResponseBody
String getProteinListForProject(
@ApiParam(value = "an project accession")
@PathVariable("projectAccession") String projectAccession,
@ApiParam(value = "filter accessions (to remove decoy, reverse, etc accessions)")
@RequestParam(value = "filter", required = false, defaultValue = "true") boolean filter
) {
logger.info("Protein accessions for project " + projectAccession + " requested");
StringBuilder sb = new StringBuilder();
sb.append("#PRIDE project:").append(projectAccession).append("\n");
Set<String> accessions = pissService.getUniqueProteinAccessionsByProjectAccession(projectAccession);
for (String accession : accessions) {
if (filter && !isValidAccession(accession)) {
// if filtering is enabled, we apply accession filtering to remove decoy, etc accessions
continue;
}
sb.append(accession).append("\n");
}
return sb.toString();
}
private static boolean isValidAccession(String accession) {
// ToDo: this should probably be a general utility for use in different projects
// ToDo: extend with more cases!
return !accession.toUpperCase().contains("DECOY") && !accession.toUpperCase().contains("REVERSE");
}
}
|
package raptor.connector.ics;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import raptor.chat.Bugger;
import raptor.chat.ChatEvent;
import raptor.chat.ChatType;
import raptor.chat.Partnership;
import raptor.chat.Seek;
import raptor.chess.BughouseGame;
import raptor.chess.Game;
import raptor.chess.GameConstants;
import raptor.chess.Result;
import raptor.chess.Variant;
import raptor.chess.pgn.PgnHeader;
import raptor.connector.ics.bughouse.BugWhoGParser;
import raptor.connector.ics.bughouse.BugWhoPParser;
import raptor.connector.ics.bughouse.BugWhoUParser;
import raptor.connector.ics.chat.CShoutEventParser;
import raptor.connector.ics.chat.ChallengeEventParser;
import raptor.connector.ics.chat.ChannelTellEventParser;
import raptor.connector.ics.chat.ChatEventParser;
import raptor.connector.ics.chat.FollowingEventParser;
import raptor.connector.ics.chat.KibitzEventParser;
import raptor.connector.ics.chat.PartnerTellEventParser;
import raptor.connector.ics.chat.PartnershipCreatedEventParser;
import raptor.connector.ics.chat.PartnershipEndedEventParser;
import raptor.connector.ics.chat.ShoutEventParser;
import raptor.connector.ics.chat.TellEventParser;
import raptor.connector.ics.chat.ToldEventParser;
import raptor.connector.ics.chat.WhisperEventParser;
import raptor.connector.ics.game.message.B1Message;
import raptor.connector.ics.game.message.G1Message;
import raptor.connector.ics.game.message.GameEndMessage;
import raptor.connector.ics.game.message.IllegalMoveMessage;
import raptor.connector.ics.game.message.MovesMessage;
import raptor.connector.ics.game.message.NoLongerExaminingGameMessage;
import raptor.connector.ics.game.message.RemovingObsGameMessage;
import raptor.connector.ics.game.message.Style12Message;
import raptor.service.GameService;
import raptor.util.RaptorStringTokenizer;
/**
* An implementation of IcsParser that is both BICS and FICS friendly.
*/
public class IcsParser implements GameConstants {
private static final Log LOG = LogFactory.getLog(IcsParser.class);
public static final int MAX_GAME_MESSAGE = 1000;
protected B1Parser b1Parser;
protected IcsConnector connector;
protected G1Parser g1Parser;
protected GameEndParser gameEndParser;
protected IllegalMoveParser illegalMoveParser;
protected MovesParser movesParser;
protected NoLongerExaminingGameParser noLongerExaminingParser;
protected List<ChatEventParser> nonGameEventParsers = new ArrayList<ChatEventParser>(
30);
protected RemovingObsGameParser removingObsGameParser;
protected FollowingEventParser followingParser;
protected Style12Parser style12Parser;
protected SoughtParser soughtParser;
protected BugWhoGParser bugWhoGParser;
protected BugWhoPParser bugWhoPParser;
protected BugWhoUParser bugWhoUParser;
protected TakebackParser takebackParser;
protected boolean isBicsParser = false;
/**
* A map keyed by game id. Used to temporarily store G1 messages until the
* first style 12 message comes along. A new game requires a 12 message as
* well as a G1.
*/
protected Map<String, G1Message> unprocessedG1Messages = new HashMap<String, G1Message>();
/**
* BICS does'nt support the partner board in G1 messages so you have to
* resort to this to link the bug games together.
*/
protected List<String> bugGamesWithoutBoard2 = new ArrayList<String>(10);
public IcsParser(boolean isBicsParser) {
this.isBicsParser = isBicsParser;
gameEndParser = new GameEndParser();
b1Parser = new B1Parser();
g1Parser = new G1Parser();
illegalMoveParser = new IllegalMoveParser();
removingObsGameParser = new RemovingObsGameParser();
takebackParser = new TakebackParser();
noLongerExaminingParser = new NoLongerExaminingGameParser();
movesParser = new MovesParser();
followingParser = new FollowingEventParser();
style12Parser = new Style12Parser();
if (!isBicsParser) {
soughtParser = new SoughtParser();
bugWhoGParser = new BugWhoGParser();
bugWhoPParser = new BugWhoPParser();
bugWhoUParser = new BugWhoUParser();
}
nonGameEventParsers.add(new PartnerTellEventParser());
nonGameEventParsers.add(new ToldEventParser());
nonGameEventParsers.add(new ChannelTellEventParser());
nonGameEventParsers.add(new CShoutEventParser());
nonGameEventParsers.add(new ShoutEventParser());
nonGameEventParsers.add(new KibitzEventParser());
nonGameEventParsers.add(new TellEventParser());
nonGameEventParsers.add(new WhisperEventParser());
// Non tell types of events.
nonGameEventParsers.add(new ChallengeEventParser());
nonGameEventParsers.add(new PartnershipCreatedEventParser());
nonGameEventParsers.add(new PartnershipEndedEventParser());
nonGameEventParsers.add(new FollowingEventParser());
}
public ChatEvent[] parse(String inboundMessage) {
if (LOG.isDebugEnabled()) {
LOG.debug("Raw message in: " + inboundMessage);
}
List<ChatEvent> events = new ArrayList<ChatEvent>(5);
// First handle the Moves message.
String afterMovesMessage = parseMovesMessage(inboundMessage, events);
if (LOG.isDebugEnabled()) {
LOG.debug("After handling moves message: " + afterMovesMessage);
}
// Next handle game events.
if (StringUtils.isNotBlank(afterMovesMessage)) {
String afterGameEvents = parseGameEvents(afterMovesMessage);
if (LOG.isDebugEnabled()) {
LOG.debug("After handling game events: " + afterGameEvents);
}
// Now process what is left over as chat events.
// Don't send it if its only a prompt.
if (StringUtils.isNotBlank(afterGameEvents)
&& !afterGameEvents.trim().equals(
connector.getContext().getPrompt())) {
// Now process bug who events.
ChatEvent bugWhoEvent = processBugWho(afterGameEvents);
if (bugWhoEvent == null) {
// Now process sought events.
ChatEvent soughtEvent = processSought(afterGameEvents);
if (soughtEvent == null) {
// Its not a game,bugwho,or sought event so now try the
// other parsers.
for (ChatEventParser parser : nonGameEventParsers) {
ChatEvent event = parser.parse(afterGameEvents);
if (event != null) {
events.add(event);
break;
}
}
// Its an unhandled event
if (events.isEmpty()) {
events.add(new ChatEvent(null, ChatType.UNKNOWN,
afterGameEvents));
}
} else {
events.add(soughtEvent);
}
} else {
events.add(bugWhoEvent);
}
}
}
return events.toArray(new ChatEvent[0]);
}
public void setConnector(IcsConnector connector) {
this.connector = connector;
}
/**
* Parses and removes all of the game events from inboundEvent. Adjusts the
* games in service. Returns a String with the game events removed.
*/
protected String parseGameEvents(String inboundMessage) {
if (inboundMessage.length() > MAX_GAME_MESSAGE) {
return inboundMessage;
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Raw message in: " + inboundMessage);
}
StringBuilder result = new StringBuilder(inboundMessage.length());
RaptorStringTokenizer tok = new RaptorStringTokenizer(
inboundMessage, "\n");
while (tok.hasMoreTokens()) {
String line = tok.nextToken();
if (LOG.isDebugEnabled()) {
LOG.debug("Processing raw line: " + line);
}
G1Message g1Message = g1Parser.parse(line);
if (g1Message != null) {
process(g1Message, connector.getGameService());
continue;
}
Style12Message style12Message = style12Parser.parse(line);
if (style12Message != null) {
process(style12Message, connector.getGameService(),
inboundMessage);
continue;
}
B1Message b1Message = b1Parser.parse(line);
if (b1Message != null) {
process(b1Message, connector.getGameService());
continue;
}
GameEndMessage gameEndMessage = gameEndParser.parse(line);
if (gameEndMessage != null) {
process(gameEndMessage, connector.getGameService());
result.append(line + (tok.hasMoreTokens() ? "\n" : ""));
continue;
}
IllegalMoveMessage illegalMoveMessage = illegalMoveParser
.parse(line);
if (illegalMoveMessage != null) {
process(illegalMoveMessage, connector.getGameService());
result.append(line + (tok.hasMoreTokens() ? "\n" : ""));
continue;
}
RemovingObsGameMessage removingObsGameMessage = removingObsGameParser
.parse(line);
if (removingObsGameMessage != null) {
process(removingObsGameMessage, connector.getGameService());
result.append(line + (tok.hasMoreTokens() ? "\n" : ""));
continue;
}
NoLongerExaminingGameMessage noLonerExaminingGameMessage = noLongerExaminingParser
.parse(line);
if (noLonerExaminingGameMessage != null) {
process(noLonerExaminingGameMessage, connector
.getGameService());
result.append(line + (tok.hasMoreTokens() ? "\n" : ""));
continue;
}
takebackParser.parse(line);
ChatEvent followingEvent = followingParser.parse(line);
if (followingEvent != null
&& followingEvent.getType() == ChatType.FOLLOWING) {
connector.setUserFollowing(followingEvent.getSource());
// Don't eat this line. Let it be appended so the event gets
// published.
// It is just being used here to set the user we are
// following so white on top
// can be set properly.
}
result.append(line + (tok.hasMoreTokens() ? "\n" : ""));
}
return result.toString();
}
}
/**
* Parses out the Moves message from inboundEvent. It is assumed moves
* messages will never contain other messages.
*
* @param inboundEvent
* The inbound message.
* @param events
* The chatEvents
*/
protected String parseMovesMessage(String inboundMessage,
List<ChatEvent> events) {
MovesMessage movesMessage = movesParser.parse(inboundMessage);
if (movesMessage != null) {
process(movesMessage, connector.getGameService());
events.add(new ChatEvent(null, ChatType.MOVES, inboundMessage));
return null;
} else {
return inboundMessage;
}
}
protected void process(B1Message message, GameService service) {
if (LOG.isDebugEnabled()) {
LOG.debug("Processing b1: " + message);
}
Game game = service.getGame(message.gameId);
if (game == null) {
connector.onError("Received B1 for a game not in the GameService. "
+ message, new Exception());
} else {
for (int i = 1; i < message.whiteHoldings.length; i++) {
game.setDropCount(WHITE, i, message.whiteHoldings[i]);
}
for (int i = 1; i < message.blackHoldings.length; i++) {
game.setDropCount(BLACK, i, message.blackHoldings[i]);
}
service.fireDroppablePiecesChanged(message.gameId);
}
}
protected void process(G1Message message, GameService service) {
unprocessedG1Messages.put(message.gameId, message);
}
protected void process(GameEndMessage message, GameService service) {
Game game = service.getGame(message.gameId);
if (game == null) {
connector.onError(
"Received game end for a game not in the GameService. "
+ message, new Exception());
} else {
switch (message.type) {
case GameEndMessage.ABORTED:
case GameEndMessage.ADJOURNED:
case GameEndMessage.UNDETERMINED:
game.setHeader(PgnHeader.ResultDescription, Result.UNDETERMINED
.getDescription());
break;
case GameEndMessage.BLACK_WON:
game.setHeader(PgnHeader.ResultDescription, Result.BLACK_WON
.getDescription());
break;
case GameEndMessage.WHITE_WON:
game.setHeader(PgnHeader.ResultDescription, Result.WHITE_WON
.getDescription());
break;
case GameEndMessage.DRAW:
game.setHeader(PgnHeader.ResultDescription, Result.DRAW
.getDescription());
break;
default:
LOG.error("Undetermined game end type. " + message);
break;
}
game.setHeader(PgnHeader.ResultDescription, message.description);
game.clearState(Game.ACTIVE_STATE | Game.IS_CLOCK_TICKING_STATE);
game.addState(Game.INACTIVE_STATE);
service.fireGameInactive(game.getId());
service.removeGame(game);
takebackParser.clearTakebackMessages(game.getId());
}
if (LOG.isDebugEnabled()) {
LOG.debug("Processed game end: " + message);
}
}
protected void process(IllegalMoveMessage message, GameService service) {
// Except for simuls you can only place one game at a time.
// For now ignore simuls and just send this to the first active game
// found in the game service.
Game[] allActive = service.getAllActiveGames();
for (Game game : allActive) {
service.fireIllegalMove(game.getId(), message.move);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Processed illegal move: " + message);
}
}
protected void process(MovesMessage message, GameService service) {
if (LOG.isDebugEnabled()) {
LOG.debug("Processing movesMessage: " + message);
}
Game game = service.getGame(message.gameId);
if (game == null) {
if (LOG.isWarnEnabled()) {
LOG
.warn("Received a MovesMessage for a game not being managed. This can occur if the user manually types in the moves command. "
+ message.gameId);
}
} else {
IcsUtils.updateGamesMoves(game, message);
service.fireGameMovesAdded(game.getId());
}
}
protected void process(NoLongerExaminingGameMessage message,
GameService service) {
Game game = service.getGame(message.gameId);
if (game == null) {
connector.onError(
"Received no longer examining game message for a game not in the GameService. "
+ message, new Exception());
} else {
game.setHeader(PgnHeader.ResultDescription,
"Interrupted by uexamine.");
game.setHeader(PgnHeader.Result, Result.UNDETERMINED
.getDescription());
game.clearState(Game.ACTIVE_STATE | Game.IS_CLOCK_TICKING_STATE);
game.addState(Game.INACTIVE_STATE);
service.fireGameInactive(game.getId());
service.removeGame(game);
takebackParser.clearTakebackMessages(game.getId());
}
if (LOG.isDebugEnabled()) {
LOG.debug("Processed no longer examining game message: " + message);
}
}
protected void process(RemovingObsGameMessage message, GameService service) {
Game game = service.getGame(message.gameId);
if (game == null) {
if (LOG.isInfoEnabled()) {
LOG
.info("Received removing obs game message for a game not in the GameService. This can usually be ignored if a game end message was received first."
+ message);
}
} else {
game.setHeader(PgnHeader.ResultDescription,
"Interrupted by unobserve");
game.setHeader(PgnHeader.Result, Result.UNDETERMINED
.getDescription());
game.clearState(Game.ACTIVE_STATE | Game.IS_CLOCK_TICKING_STATE);
game.addState(Game.INACTIVE_STATE);
service.fireGameInactive(game.getId());
service.removeGame(game);
takebackParser.clearTakebackMessages(game.getId());
}
if (LOG.isDebugEnabled()) {
LOG.debug("Processed removing obs game: " + message);
}
}
protected void process(Style12Message message, GameService service,
String entireMessage) {
if (LOG.isDebugEnabled()) {
LOG.debug("Processing style 12: " + message);
}
long startTime = System.currentTimeMillis();
Game game = service.getGame(message.gameId);
if (game != null) {
if (game.isInState(Game.EXAMINING_STATE)
|| game.isInState(Game.SETUP_STATE)) {
// Examined/BSetup moves flow through here.
if (LOG.isDebugEnabled()) {
LOG.debug("Processing bsetup or examine position move.");
}
if (entireMessage
.contains("Game is validated - entering examine mode.\n")) {
// Games changing from Setup to Examine mode flow through
// here.
game.clearState(Game.SETUP_STATE);
game.clearState(Game.DROPPABLE_STATE);
IcsUtils.resetGame(game, message);
service.fireSetupGameBecameExamined(message.gameId);
} else {
// Clear out the game and start over.
// There is no telling what happened
// in a setup or examine game.
IcsUtils.resetGame(game, message);
service.fireGameStateChanged(message.gameId, true);
}
} else {
// Playing/Obsing moves flow through here.
if (LOG.isDebugEnabled()) {
LOG.debug("Processing obs/playing position move.");
}
// Takebacks may have effected the state of the game so first
// adjsut to those.
if (!IcsUtils.adjustToTakebacks(game, message, takebackParser)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Making move in obs/playing position.");
}
// Now add the move to the game.
// Game Ends and Refreshes dont involve adding a move.
if (IcsUtils.addCurrentMove(game, message)) {
if (LOG.isDebugEnabled()) {
LOG
.debug("Position was a move firing state changed.");
}
service.fireGameStateChanged(message.gameId, true);
} else {
if (LOG.isDebugEnabled()) {
LOG
.debug("Position was not a move firing state changed.");
}
service.fireGameStateChanged(message.gameId, false);
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Adjusted for takebacks.");
}
service.fireGameStateChanged(message.gameId, true);
}
}
} else {
G1Message g1Message = unprocessedG1Messages.get(message.gameId);
if (g1Message == null) {
// Examined/Bsetup game starts flow through here
if (LOG.isDebugEnabled()) {
LOG.debug("Processing new ex or bsetup game.");
}
game = IcsUtils.createGame(message, entireMessage);
service.addGame(game);
if (LOG.isDebugEnabled()) {
LOG.debug("Firing game created.");
}
// Respect the flip variable if its set.
game.setHeader(PgnHeader.WhiteOnTop, message.isWhiteOnTop ? "1"
: "0");
service.fireGameCreated(game.getId());
} else {
// Observed/Playing games starts flow through here
if (LOG.isDebugEnabled()) {
LOG.debug("Processing new obs/playing game.");
}
unprocessedG1Messages.remove(message.gameId);
game = IcsUtils.createGame(g1Message);
IcsUtils.updateNonPositionFields(game, message);
IcsUtils.updatePosition(game, message);
IcsUtils.verifyLegal(game);
service.addGame(game);
if (message.isWhiteOnTop) {
// Respect the flip variable.
game.setHeader(PgnHeader.WhiteOnTop, "1");
} else if (StringUtils.equalsIgnoreCase(message.whiteName,
connector.userName)) {
game.setHeader(PgnHeader.WhiteOnTop, "0");
} else if (StringUtils.equalsIgnoreCase(message.whiteName,
connector.userFollowing)) {
game.setHeader(PgnHeader.WhiteOnTop, "0");
} else if (StringUtils.equalsIgnoreCase(message.blackName,
connector.userName)) {
game.setHeader(PgnHeader.WhiteOnTop, "1");
} else if (StringUtils.equalsIgnoreCase(message.blackName,
connector.userFollowing)) {
game.setHeader(PgnHeader.WhiteOnTop, "1");
} else {
game.setHeader(PgnHeader.WhiteOnTop, "0");
}
if (game.getVariant() == Variant.bughouse) {
if (g1Message.parterGameId.equals("0")) {
// BICS mode its ugly buggy and i hate it. Please ask
// them
// to add
// a damn partnerGameId its a pain without it.
if (bugGamesWithoutBoard2.isEmpty()) {
bugGamesWithoutBoard2.add(message.gameId);
connector.sendMessage("pobserve "
+ (message.isWhiteOnTop ? message.blackName
: message.whiteName), true);
} else {
Game otherBoard = service
.getGame(bugGamesWithoutBoard2.get(0));
if (otherBoard == null) {
connector
.onError(
"Could not find game with id "
+ bugGamesWithoutBoard2
.get(0)
+ " in the GameService. Please get BICS to add a partner game id to its G1 message.\n"
+ " You can complain to both johnthegreat and aramen.",
new Exception());
} else {
((BughouseGame) game)
.setOtherBoard((BughouseGame) otherBoard);
((BughouseGame) otherBoard)
.setOtherBoard((BughouseGame) game);
if (StringUtils
.defaultIfEmpty(
otherBoard
.getHeader(PgnHeader.WhiteOnTop),
"0").equals("0")) {
game.setHeader(PgnHeader.WhiteOnTop, "1");
} else {
game.setHeader(PgnHeader.WhiteOnTop, "0");
}
}
bugGamesWithoutBoard2.clear();
}
} else { // Fics mode, nice and clean.
if (!connector.getGameService().isManaging(
g1Message.parterGameId)) {
connector.sendMessage("observe "
+ g1Message.parterGameId, true);
} else {
Game otherBoard = service
.getGame(g1Message.parterGameId);
((BughouseGame) game)
.setOtherBoard((BughouseGame) otherBoard);
((BughouseGame) otherBoard)
.setOtherBoard((BughouseGame) game);
if (StringUtils.defaultIfEmpty(
otherBoard.getHeader(PgnHeader.WhiteOnTop),
"0").equals("0")) {
game.setHeader(PgnHeader.WhiteOnTop, "1");
} else {
game.setHeader(PgnHeader.WhiteOnTop, "0");
}
}
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Firing game created.");
}
service.fireGameCreated(game.getId());
/**
* Send a request for the moves.
*/
if (message.fullMoveNumber > 1 || message.fullMoveNumber == 1
&& !message.isWhitesMoveAfterMoveIsMade) {
connector.sendMessage("moves " + message.gameId, true,
ChatType.MOVES);
}
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Processed style 12: " + message + " in "
+ (System.currentTimeMillis() - startTime));
}
}
protected ChatEvent processBugWho(String message) {
ChatEvent result = null;
// Bics bugwho is different. Someone needs to write bics bugwho to get
// it working.
if (bugWhoUParser != null) {
Bugger[] buggers = bugWhoUParser.parse(message);
if (buggers == null) {
Partnership[] partnerships = bugWhoPParser.parse(message);
if (partnerships == null) {
raptor.chat.BugGame[] bugGames = bugWhoGParser
.parse(message);
if (bugGames != null) {
connector.getBughouseService().setGamesInProgress(
bugGames);
result = new ChatEvent(null, ChatType.BUGWHO_GAMES,
message);
}
} else {
connector.getBughouseService().setAvailablePartnerships(
partnerships);
result = new ChatEvent(null,
ChatType.BUGWHO_AVAILABLE_TEAMS, message);
}
} else {
connector.getBughouseService().setUnpartneredBuggers(buggers);
result = new ChatEvent(null,
ChatType.BUGWHO_UNPARTNERED_BUGGERS, message);
}
}
return result;
}
protected ChatEvent processSought(String message) {
ChatEvent result = null;
if (soughtParser != null) {
Seek[] seeks = soughtParser.parse(message);
if (seeks != null) {
connector.getSeekService().setSeeks(seeks);
result = new ChatEvent(null, ChatType.SEEKS, message);
}
}
return result;
}
}
|
package org.spongepowered.common.mixin.api.mcp.util.registry;
import com.mojang.serialization.Lifecycle;
import net.minecraft.util.RegistryKey;
import net.minecraft.util.ResourceLocation;
import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.registry.Registry;
import org.spongepowered.api.registry.RegistryEntry;
import org.spongepowered.api.registry.RegistryType;
import org.spongepowered.api.registry.ValueNotFoundException;
import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.Interface;
import org.spongepowered.asm.mixin.Intrinsic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.common.accessor.util.RegistryKeyAccessor;
import org.spongepowered.common.bridge.util.registry.RegistryBridge;
import org.spongepowered.common.registry.SpongeRegistryType;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import javax.annotation.Nullable;
@Mixin(net.minecraft.util.registry.Registry.class)
@Implements(@Interface(iface = Registry.class, prefix = "registry$"))
public abstract class RegistryMixin_API<T> implements Registry<T> {
// @formatter:off
@Shadow public abstract RegistryKey<? extends net.minecraft.util.registry.Registry<T>> shadow$key();
@Shadow @Nullable public abstract ResourceLocation shadow$getKey(T p_177774_1_);
@Shadow @Nullable public abstract T get(@org.checkerframework.checker.nullness.qual.Nullable ResourceLocation p_82594_1_);
// @formatter:on
private RegistryType<T> api$type;
@Inject(method = "<init>", at = @At("TAIL"))
private void api$setType(RegistryKey<? extends net.minecraft.util.registry.Registry<T>> key, Lifecycle p_i232510_2_, CallbackInfo ci) {
this.api$type = new SpongeRegistryType<T>((ResourceKey) (Object) ((RegistryKeyAccessor) key).accessor$registryName(),
(ResourceKey) (Object) key.location());
}
@Override
public RegistryType<T> type() {
return this.api$type;
}
@Override
public Optional<ResourceKey> findValueKey(final T value) {
Objects.requireNonNull(value, "value");
return Optional.ofNullable(this.shadow$getKey(value)).map(l -> (ResourceKey) (Object) l);
}
@Override
public <V extends T> Optional<RegistryEntry<V>> findEntry(final ResourceKey key) {
Objects.requireNonNull(key, "key");
return Optional.ofNullable(((RegistryBridge<V>) this).bridge$getEntries().get(key));
}
@Override
public <V extends T> Optional<V> findValue(final ResourceKey key) {
Objects.requireNonNull(key, "key");
return Optional.ofNullable((V) this.get((ResourceLocation) (Object) key));
}
@Override
public <V extends T> V value(final ResourceKey key) {
Objects.requireNonNull(key, "key");
final V value = (V) this.get((ResourceLocation) (Object) key);
if (value == null) {
throw new ValueNotFoundException(String.format("No value was found for key '%s'!", key));
}
return value;
}
@Intrinsic
public Stream<RegistryEntry<T>> registry$stream() {
return ((RegistryBridge<T>) this).bridge$getEntries().values().stream();
}
@Override
public Stream<T> streamValues() {
return ((RegistryBridge<T>) this).bridge$getEntries().values().stream().map(RegistryEntry::value);
}
@Override
public boolean isDynamic() {
return false;
}
@Override
public <V extends T> Optional<RegistryEntry<V>> register(final ResourceKey key, final V value) {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(value, "value");
return Optional.empty();
}
}
|
package org.pentaho.di.repository.kdr.delegates;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.Counters;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.logging.LoggingObjectInterface;
import org.pentaho.di.core.logging.LoggingObjectType;
import org.pentaho.di.core.logging.SimpleLoggingObject;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.LongObjectId;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryDirectoryInterface;
import org.pentaho.di.repository.RepositoryElementMetaInterface;
import org.pentaho.di.repository.RepositoryObject;
import org.pentaho.di.repository.RepositoryObjectType;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
public class KettleDatabaseRepositoryConnectionDelegate extends KettleDatabaseRepositoryBaseDelegate {
private static Class<?> PKG = Repository.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
public static final LoggingObjectInterface loggingObject = new SimpleLoggingObject("Database repository", LoggingObjectType.REPOSITORY, null);
public static final int REQUIRED_MAJOR_VERSION = 4;
public static final int REQUIRED_MINOR_VERSION = 0;
protected final static int[] KEY_POSITIONS = new int[] {0, 1, 2};
protected Database database;
protected DatabaseMeta databaseMeta;
protected int majorVersion;
protected int minorVersion;
protected PreparedStatement psStepAttributesLookup;
protected PreparedStatement psStepAttributesInsert;
protected PreparedStatement psTransAttributesLookup;
protected PreparedStatement psTransAttributesInsert;
protected PreparedStatement psJobAttributesLookup;
protected PreparedStatement psJobAttributesInsert;
protected List<Object[]> stepAttributesBuffer;
protected RowMetaInterface stepAttributesRowMeta;
protected PreparedStatement pstmt_entry_attributes;
protected boolean useBatchProcessing;
protected Map<String, PreparedStatement> sqlMap;
private class StepAttributeComparator implements Comparator<Object[]> {
public int compare(Object[] r1, Object[] r2)
{
try {
return stepAttributesRowMeta.compare(r1, r2, KEY_POSITIONS);
} catch (KettleValueException e) {
return 0; // conversion errors
}
}
}
public KettleDatabaseRepositoryConnectionDelegate(KettleDatabaseRepository repository, DatabaseMeta databaseMeta) {
super(repository);
this.databaseMeta = databaseMeta;
this.database = new Database(loggingObject, databaseMeta);
sqlMap = new HashMap<String, PreparedStatement>();
useBatchProcessing = true; // defaults to true;
psStepAttributesLookup = null;
psStepAttributesInsert = null;
psTransAttributesLookup = null;
pstmt_entry_attributes = null;
this.majorVersion = REQUIRED_MAJOR_VERSION;
this.minorVersion = REQUIRED_MINOR_VERSION;
}
/**
* Connect to the repository
*/
public synchronized void connect() throws KettleException
{
connect(false, false);
}
public synchronized void connect(boolean no_lookup) throws KettleException
{
connect(no_lookup, false);
}
public synchronized void connect(boolean no_lookup, boolean ignoreVersion) throws KettleException
{
if (repository.isConnected())
{
throw new KettleException("Repository is already by class " + repository.isConnected());
}
try
{
database.initializeVariablesFrom(null);
database.connect();
if (!ignoreVersion) {
verifyVersion();
}
setAutoCommit(false);
repository.setConnected(true);
if (!no_lookup)
{
try
{
repository.connectionDelegate.setLookupStepAttribute();
repository.connectionDelegate.setLookupTransAttribute();
repository.connectionDelegate.setLookupJobEntryAttribute();
repository.connectionDelegate.setLookupJobAttribute();
}
catch (KettleException dbe)
{
throw new KettleException("Error setting lookup prep.statements", dbe);
}
}
}
catch (KettleException e)
{
throw new KettleException("Error connecting to the repository!", e);
}
}
/**
* Get the required repository version for this version of Kettle.
* @return the required repository version for this version of Kettle.
*/
public static final String getRequiredVersion()
{
return REQUIRED_MAJOR_VERSION + "." + REQUIRED_MINOR_VERSION;
}
protected void verifyVersion() throws KettleException
{
RowMetaAndData lastUpgrade = null;
String versionTable = databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_VERSION);
try
{
lastUpgrade = database.getOneRow("SELECT "+quote(KettleDatabaseRepository.FIELD_VERSION_MAJOR_VERSION)+", "+quote(KettleDatabaseRepository.FIELD_VERSION_MINOR_VERSION)+", "+quote(KettleDatabaseRepository.FIELD_VERSION_UPGRADE_DATE)+" FROM "+versionTable+" ORDER BY "+quote(KettleDatabaseRepository.FIELD_VERSION_UPGRADE_DATE)+" DESC");
}
catch(Exception e)
{
try
{
// See if the repository exists at all. For this we verify table R_USER.
String userTable = databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_USER);
database.getOneRow("SELECT * FROM "+userTable);
// Still here? That means we have a repository...
// this means the R_VERSION table doesn't exist.
// This table was introduced in version 2.3.0
if(log.isBasic())
{
log.logBasic(BaseMessages.getString(PKG, "Repository.Error.GettingInfoVersionTable",versionTable));
log.logBasic(BaseMessages.getString(PKG, "Repository.Error.NewTable"));
log.logBasic("Stack trace: "+Const.getStackTracker(e));
}
majorVersion = 2;
minorVersion = 2;
lastUpgrade = null;
}
catch(Exception ex)
{
throw new KettleException(BaseMessages.getString(PKG, "Repository.NoRepositoryExists.Messages"));
}
}
if (lastUpgrade != null)
{
majorVersion = (int)lastUpgrade.getInteger(KettleDatabaseRepository.FIELD_VERSION_MAJOR_VERSION, -1);
minorVersion = (int)lastUpgrade.getInteger(KettleDatabaseRepository.FIELD_VERSION_MINOR_VERSION, -1);
}
if (majorVersion < REQUIRED_MAJOR_VERSION || ( majorVersion==REQUIRED_MAJOR_VERSION && minorVersion<REQUIRED_MINOR_VERSION))
{
throw new KettleException(BaseMessages.getString(PKG, "Repository.UpgradeRequired.Message", getVersion(), getRequiredVersion()));
}
if (majorVersion==3 && minorVersion==0) {
// The exception: someone upgraded the repository to version 3.0.0
// In that version, one column got named incorrectly.
// Another upgrade to 3.0.1 or later will fix that.
// However, since we don't have point versions in here, we'll have to look at the column in question...
String tableName = databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_TRANS_PARTITION_SCHEMA);
String errorColumn = "TRANSFORMATION";
RowMetaInterface tableFields = database.getTableFields(tableName);
if (tableFields.indexOfValue(errorColumn)>=0)
{
throw new KettleException(BaseMessages.getString(PKG, "Repository.FixFor300Required.Message"));
}
}
}
public synchronized void disconnect()
{
try
{
repository.connectionDelegate.closeStepAttributeLookupPreparedStatement();
repository.connectionDelegate.closeTransAttributeLookupPreparedStatement();
repository.connectionDelegate.closeLookupJobEntryAttribute();
for (String sql : sqlMap.keySet()) {
PreparedStatement ps = sqlMap.get(sql);
try {
ps.close();
} catch (SQLException e) {
log.logError("Error closing prepared statement: " + sql, e);
}
}
if (!database.isAutoCommit()) commit();
repository.setConnected(false);
}
catch (KettleException dbe)
{
log.logError("Error disconnecting from database : " + dbe.getMessage());
}
finally
{
database.disconnect();
sqlMap.clear();
}
}
public synchronized void setAutoCommit(boolean autocommit)
{
if (!autocommit)
database.setCommit(99999999);
else
database.setCommit(0);
}
public synchronized void commit() throws KettleException
{
try
{
closeJobAttributeInsertPreparedStatement();
closeStepAttributeInsertPreparedStatement();
closeTransAttributeInsertPreparedStatement();
if (!database.isAutoCommit()) {
database.commit();
}
// Also, clear the counters, reducing the risk of collisions!
Counters.getInstance().clear();
}
catch (KettleException dbe)
{
throw new KettleException("Unable to commit repository connection", dbe);
}
}
public synchronized void rollback()
{
try
{
database.rollback();
// Also, clear the counters, reducing the risk of collisions!
Counters.getInstance().clear();
}
catch (KettleException dbe)
{
log.logError("Error rolling back repository.");
}
}
/**
* @return the database
*/
public Database getDatabase() {
return database;
}
/**
* @param database the database to set
*/
public void setDatabase(Database database) {
this.database = database;
}
/**
* @return the databaseMeta
*/
public DatabaseMeta getDatabaseMeta() {
return databaseMeta;
}
/**
* @param databaseMeta the databaseMeta to set
*/
public void setDatabaseMeta(DatabaseMeta databaseMeta) {
this.databaseMeta = databaseMeta;
}
/**
* @return the majorVersion
*/
public int getMajorVersion() {
return majorVersion;
}
/**
* @param majorVersion the majorVersion to set
*/
public void setMajorVersion(int majorVersion) {
this.majorVersion = majorVersion;
}
/**
* @return the minorVersion
*/
public int getMinorVersion() {
return minorVersion;
}
/**
* @param minorVersion the minorVersion to set
*/
public void setMinorVersion(int minorVersion) {
this.minorVersion = minorVersion;
}
/**
* Get the repository version.
* @return The repository version as major version + "." + minor version
*/
public String getVersion()
{
return majorVersion + "." + minorVersion;
}
public synchronized void fillStepAttributesBuffer(ObjectId id_transformation) throws KettleException
{
String sql = "SELECT "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_ID_STEP)+", "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_CODE)+", "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_NR)+", "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_VALUE_NUM)+", "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_VALUE_STR)+" "+
"FROM "+databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_STEP_ATTRIBUTE) +" "+
"WHERE "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_ID_TRANSFORMATION)+" = ? "+
"ORDER BY "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_ID_STEP)+", "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_CODE)+", "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_NR)
;
PreparedStatement ps = sqlMap.get(sql);
if (ps == null) {
ps = database.prepareSQL(sql);
sqlMap.put(sql, ps);
}
RowMetaAndData parameter = getParameterMetaData(id_transformation);
ResultSet resultSet = database.openQuery(ps, parameter.getRowMeta(), parameter.getData());
stepAttributesBuffer = database.getRows(resultSet, -1, null);
stepAttributesRowMeta = database.getReturnRowMeta();
// must use java-based sort to ensure compatibility with binary search
// database ordering may or may not be case-insensitive
Collections.sort(stepAttributesBuffer, new StepAttributeComparator()); // in case db sort does not match our sort
}
/**
* @return Returns the stepAttributesBuffer.
*/
public List<Object[]> getStepAttributesBuffer()
{
return stepAttributesBuffer;
}
/**
* @param stepAttributesBuffer The stepAttributesBuffer to set.
*/
public void setStepAttributesBuffer(List<Object[]> stepAttributesBuffer)
{
this.stepAttributesBuffer = stepAttributesBuffer;
}
private synchronized RowMetaAndData searchStepAttributeInBuffer(ObjectId id_step, String code, long nr) throws KettleValueException
{
int index = searchStepAttributeIndexInBuffer(id_step, code, nr);
if (index<0) return null;
// Get the row
Object[] r = stepAttributesBuffer.get(index);
// and remove it from the list...
// stepAttributesBuffer.remove(index);
return new RowMetaAndData(stepAttributesRowMeta, r);
}
private synchronized int searchStepAttributeIndexInBuffer(ObjectId id_step, String code, long nr) throws KettleValueException
{
Object[] key = new Object[] {
new LongObjectId(id_step).longValue(), // ID_STEP
code, // CODE
new Long(nr),
};
int index = Collections.binarySearch(stepAttributesBuffer, key, new StepAttributeComparator());
if (index>=stepAttributesBuffer.size() || index<0) return -1;
// Check this... If it is not in there, we didn't find it!
// stepAttributesRowMeta.compare returns 0 when there are conversion issues
// so the binarySearch could have 'found' a match when there really isn't one
Object[] look = stepAttributesBuffer.get(index);
if (stepAttributesRowMeta.compare(look, key, KEY_POSITIONS)==0)
{
return index;
}
return -1;
}
private synchronized int searchNrStepAttributes(ObjectId id_step, String code) throws KettleValueException
{
// Search the index of the first step attribute with the specified code...
int idx = searchStepAttributeIndexInBuffer(id_step, code, 0L);
if (idx<0) return 0;
int nr = 1;
int offset = 1;
if (idx+offset>=stepAttributesBuffer.size())
{
// Only 1, the last of the attributes buffer.
return 1;
}
Object[] look = (Object[])stepAttributesBuffer.get(idx+offset);
RowMetaInterface rowMeta = stepAttributesRowMeta;
long lookID = rowMeta.getInteger(look, 0);
String lookCode = rowMeta.getString(look, 1);
while (lookID==new LongObjectId(id_step).longValue() && code.equalsIgnoreCase( lookCode ) )
{
// Find the maximum
nr = rowMeta.getInteger(look, 2).intValue() + 1;
offset++;
if (idx+offset<stepAttributesBuffer.size())
{
look = (Object[])stepAttributesBuffer.get(idx+offset);
lookID = rowMeta.getInteger(look, 0);
lookCode = rowMeta.getString(look, 1);
}
else
{
return nr;
}
}
return nr;
}
public synchronized void setLookupStepAttribute() throws KettleException
{
String sql = "SELECT "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_VALUE_STR)+", "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_VALUE_NUM)+
" FROM "+databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_STEP_ATTRIBUTE)+
" WHERE "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_ID_STEP)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_CODE)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_NR)+" = ? ";
psStepAttributesLookup = database.prepareSQL(sql);
}
public synchronized void setLookupTransAttribute() throws KettleException
{
String sql = "SELECT "+quote(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_VALUE_STR)+", "+quote(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_VALUE_NUM)+
" FROM "+databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_TRANS_ATTRIBUTE)+" WHERE "+quote(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_ID_TRANSFORMATION)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_CODE)+" = ? AND "+KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_NR+" = ? ";
psTransAttributesLookup = database.prepareSQL(sql);
}
public synchronized void closeTransAttributeLookupPreparedStatement() throws KettleException
{
database.closePreparedStatement(psTransAttributesLookup);
psTransAttributesLookup = null;
}
public synchronized void setLookupJobAttribute() throws KettleException
{
String sql = "SELECT "+quote(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_VALUE_STR)+", "+quote(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_VALUE_NUM)+
" FROM "+databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_JOB_ATTRIBUTE)+" WHERE "+quote(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_ID_JOB)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_CODE)+" = ? AND "+KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_NR+" = ? ";
psJobAttributesLookup = database.prepareSQL(sql);
}
public synchronized void closeJobAttributeLookupPreparedStatement() throws KettleException
{
database.closePreparedStatement(psTransAttributesLookup);
psJobAttributesLookup = null;
}
public synchronized void closeStepAttributeLookupPreparedStatement() throws KettleException
{
database.closePreparedStatement(psStepAttributesLookup);
psStepAttributesLookup = null;
}
public synchronized void closeStepAttributeInsertPreparedStatement() throws KettleException
{
if (psStepAttributesInsert!=null)
{
database.emptyAndCommit(psStepAttributesInsert, useBatchProcessing, 1); // batch mode!
psStepAttributesInsert = null;
}
}
public synchronized void closeTransAttributeInsertPreparedStatement() throws KettleException
{
if (psTransAttributesInsert!=null)
{
database.emptyAndCommit(psTransAttributesInsert, useBatchProcessing, 1); // batch mode!
psTransAttributesInsert = null;
}
}
public synchronized void closeJobAttributeInsertPreparedStatement() throws KettleException
{
if (psJobAttributesInsert!=null)
{
database.emptyAndCommit(psJobAttributesInsert, useBatchProcessing, 1); // batch mode!
psJobAttributesInsert = null;
}
}
private RowMetaAndData getStepAttributeRow(ObjectId id_step, int nr, String code) throws KettleException
{
RowMetaAndData par = new RowMetaAndData();
par.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_ID_STEP, ValueMetaInterface.TYPE_INTEGER), id_step);
par.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
par.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_NR, ValueMetaInterface.TYPE_INTEGER), new Long(nr));
database.setValues(par.getRowMeta(), par.getData(), psStepAttributesLookup);
Object[] rowData = database.getLookup(psStepAttributesLookup);
return new RowMetaAndData(database.getReturnRowMeta(), rowData);
}
public RowMetaAndData getTransAttributeRow(ObjectId id_transformation, int nr, String code) throws KettleException
{
RowMetaAndData par = new RowMetaAndData();
par.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_ID_TRANSFORMATION, ValueMetaInterface.TYPE_INTEGER), id_transformation);
par.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
par.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_NR, ValueMetaInterface.TYPE_INTEGER), new Long(nr));
database.setValues(par, psTransAttributesLookup);
Object[] r = database.getLookup(psTransAttributesLookup);
if (r==null) return null;
return new RowMetaAndData(database.getReturnRowMeta(), r);
}
public RowMetaAndData getJobAttributeRow(ObjectId id_job, int nr, String code) throws KettleException
{
RowMetaAndData par = new RowMetaAndData();
par.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_ID_JOB, ValueMetaInterface.TYPE_INTEGER), id_job);
par.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
par.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_NR, ValueMetaInterface.TYPE_INTEGER), new Long(nr));
database.setValues(par, psJobAttributesLookup);
Object[] r = database.getLookup(psJobAttributesLookup);
if (r==null) return null;
return new RowMetaAndData(database.getReturnRowMeta(), r);
}
public synchronized long getStepAttributeInteger(ObjectId id_step, int nr, String code) throws KettleException
{
RowMetaAndData r = null;
if (stepAttributesBuffer!=null) r = searchStepAttributeInBuffer(id_step, code, (long)nr);
else r = getStepAttributeRow(id_step, nr, code);
if (r == null)
return -1L;
long id = r.getInteger(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_VALUE_NUM, -1L);
return id;
}
public synchronized ObjectId findStepAttributeID(ObjectId id_step, int nr, String code) throws KettleException
{
RowMetaAndData r = null;
if (stepAttributesBuffer!=null) r = searchStepAttributeInBuffer(id_step, code, (long)nr);
else r = getStepAttributeRow(id_step, nr, code);
if (r == null) return null;
long id = r.getInteger(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_ID_STEP, -1L);
if (id<0) return null;
return new LongObjectId(id);
}
public synchronized String getStepAttributeString(ObjectId id_step, int nr, String code) throws KettleException
{
RowMetaAndData r = null;
if (stepAttributesBuffer!=null) r = searchStepAttributeInBuffer(id_step, code, (long)nr);
else r = getStepAttributeRow(id_step, nr, code);
if (r == null)
return null;
return r.getString(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_VALUE_STR, null);
}
public boolean getStepAttributeBoolean(ObjectId id_step, int nr, String code, boolean def) throws KettleException
{
RowMetaAndData r = null;
if (stepAttributesBuffer!=null) r = searchStepAttributeInBuffer(id_step, code, (long)nr);
else r = getStepAttributeRow(id_step, nr, code);
if (r == null) return def;
String v = r.getString(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_VALUE_STR, null);
if (v==null || Const.isEmpty(v)) return def;
return ValueMeta.convertStringToBoolean(v).booleanValue();
}
public boolean getStepAttributeBoolean(ObjectId id_step, int nr, String code) throws KettleException
{
RowMetaAndData r = null;
if (stepAttributesBuffer!=null) r = searchStepAttributeInBuffer(id_step, code, (long)nr);
else r = getStepAttributeRow(id_step, nr, code);
if (r == null)
return false;
return ValueMeta.convertStringToBoolean(r.getString(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_VALUE_STR, null)).booleanValue();
}
public synchronized long getStepAttributeInteger(ObjectId id_step, String code) throws KettleException
{
return getStepAttributeInteger(id_step, 0, code);
}
public synchronized String getStepAttributeString(ObjectId id_step, String code) throws KettleException
{
return getStepAttributeString(id_step, 0, code);
}
public boolean getStepAttributeBoolean(ObjectId id_step, String code) throws KettleException
{
return getStepAttributeBoolean(id_step, 0, code);
}
public synchronized ObjectId saveStepAttribute(ObjectId id_transformation, ObjectId id_step, String code, String value) throws KettleException {
return saveStepAttribute(code, 0, id_transformation, id_step, 0.0, value);
}
public synchronized ObjectId saveStepAttribute(ObjectId id_transformation, ObjectId id_step, String code, double value) throws KettleException {
return saveStepAttribute(code, 0, id_transformation, id_step, value, null);
}
public synchronized ObjectId saveStepAttribute(ObjectId id_transformation, ObjectId id_step, String code, boolean value) throws KettleException {
return saveStepAttribute(code, 0, id_transformation, id_step, 0.0, value ? "Y" : "N");
}
public synchronized ObjectId saveStepAttribute(ObjectId id_transformation, ObjectId id_step, long nr, String code, String value) throws KettleException {
return saveStepAttribute(code, nr, id_transformation, id_step, 0.0, value);
}
public synchronized ObjectId saveStepAttribute(ObjectId id_transformation, ObjectId id_step, long nr, String code, double value) throws KettleException {
return saveStepAttribute(code, nr, id_transformation, id_step, value, null);
}
public synchronized ObjectId saveStepAttribute(ObjectId id_transformation, ObjectId id_step, long nr, String code, boolean value) throws KettleException {
return saveStepAttribute(code, nr, id_transformation, id_step, 0.0, value ? "Y" : "N");
}
private ObjectId saveStepAttribute(String code, long nr, ObjectId id_transformation, ObjectId id_step, double value_num, String value_str) throws KettleException {
return insertStepAttribute(id_transformation, id_step, nr, code, value_num, value_str);
}
public synchronized int countNrStepAttributes(ObjectId id_step, String code) throws KettleException
{
if (stepAttributesBuffer!=null) // see if we can do this in memory...
{
int nr = searchNrStepAttributes(id_step, code);
return nr;
}
else
{
String sql = "SELECT COUNT(*) FROM "+databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_STEP_ATTRIBUTE)+" WHERE "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_ID_STEP)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_CODE)+" = ?";
RowMetaAndData table = new RowMetaAndData();
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_ID_STEP, ValueMetaInterface.TYPE_INTEGER), id_step);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
RowMetaAndData r = database.getOneRow(sql, table.getRowMeta(), table.getData());
if (r == null || r.getData()==null) return 0;
return (int) r.getInteger(0, 0L);
}
}
// TRANS ATTRIBUTES: get
public synchronized String getTransAttributeString(ObjectId id_transformation, int nr, String code) throws KettleException
{
RowMetaAndData r = null;
r = getTransAttributeRow(id_transformation, nr, code);
if (r == null)
return null;
return r.getString(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_VALUE_STR, null);
}
public synchronized boolean getTransAttributeBoolean(ObjectId id_transformation, int nr, String code) throws KettleException
{
RowMetaAndData r = null;
r = getTransAttributeRow(id_transformation, nr, code);
if (r == null)
return false;
return r.getBoolean(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_VALUE_STR, false);
}
public synchronized double getTransAttributeNumber(ObjectId id_transformation, int nr, String code) throws KettleException
{
RowMetaAndData r = null;
r = getTransAttributeRow(id_transformation, nr, code);
if (r == null)
return 0.0;
return r.getNumber(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_VALUE_NUM, 0.0);
}
public synchronized long getTransAttributeInteger(ObjectId id_transformation, int nr, String code) throws KettleException
{
RowMetaAndData r = null;
r = getTransAttributeRow(id_transformation, nr, code);
if (r == null)
return 0L;
return r.getInteger(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_VALUE_NUM, 0L);
}
public synchronized int countNrTransAttributes(ObjectId id_transformation, String code) throws KettleException
{
String sql = "SELECT COUNT(*) FROM "+databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_TRANS_ATTRIBUTE)+" WHERE "+quote(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_ID_TRANSFORMATION)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_CODE)+" = ?";
RowMetaAndData table = new RowMetaAndData();
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_ID_TRANSFORMATION, ValueMetaInterface.TYPE_INTEGER), id_transformation);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
RowMetaAndData r = database.getOneRow(sql, table.getRowMeta(), table.getData());
if (r == null|| r.getData()==null)
return 0;
return (int) r.getInteger(0, 0L);
}
public synchronized List<Object[]> getTransAttributes(ObjectId id_transformation, String code, long nr) throws KettleException
{
String sql = "SELECT *"+
" FROM "+databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_TRANS_ATTRIBUTE)+
" WHERE "+quote(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_ID_TRANSFORMATION)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_CODE)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_NR)+" = ?"+
" ORDER BY "+quote(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_VALUE_NUM);
RowMetaAndData table = new RowMetaAndData();
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_ID_TRANSFORMATION, ValueMetaInterface.TYPE_INTEGER), new LongObjectId(id_transformation));
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_NR, ValueMetaInterface.TYPE_INTEGER), new Long(nr));
return database.getRows(sql, 0);
}
// JOB ATTRIBUTES: get
public synchronized String getJobAttributeString(ObjectId id_job, int nr, String code) throws KettleException
{
RowMetaAndData r = null;
r = getJobAttributeRow(id_job, nr, code);
if (r == null)
return null;
return r.getString(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_VALUE_STR, null);
}
public synchronized boolean getJobAttributeBoolean(ObjectId id_job, int nr, String code) throws KettleException
{
RowMetaAndData r = null;
r = getJobAttributeRow(id_job, nr, code);
if (r == null)
return false;
return r.getBoolean(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_VALUE_STR, false);
}
public synchronized double getJobAttributeNumber(ObjectId id_job, int nr, String code) throws KettleException
{
RowMetaAndData r = null;
r = getJobAttributeRow(id_job, nr, code);
if (r == null)
return 0.0;
return r.getNumber(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_VALUE_NUM, 0.0);
}
public synchronized long getJobAttributeInteger(ObjectId id_job, int nr, String code) throws KettleException
{
RowMetaAndData r = null;
r = getJobAttributeRow(id_job, nr, code);
if (r == null)
return 0L;
return r.getInteger(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_VALUE_NUM, 0L);
}
public synchronized int countNrJobAttributes(ObjectId id_job, String code) throws KettleException
{
String sql = "SELECT COUNT(*) FROM "+databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_JOB_ATTRIBUTE)+" WHERE "+quote(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_ID_JOB)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_CODE)+" = ?";
RowMetaAndData table = new RowMetaAndData();
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_ID_JOB, ValueMetaInterface.TYPE_INTEGER), id_job);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
RowMetaAndData r = database.getOneRow(sql, table.getRowMeta(), table.getData());
if (r == null|| r.getData()==null)
return 0;
return (int) r.getInteger(0, 0L);
}
public synchronized List<Object[]> getJobAttributes(ObjectId id_job, String code, long nr) throws KettleException
{
String sql = "SELECT *"+
" FROM "+databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_JOB_ATTRIBUTE)+
" WHERE "+quote(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_ID_JOB)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_CODE)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_NR)+" = ?"+
" ORDER BY "+quote(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_VALUE_NUM);
RowMetaAndData table = new RowMetaAndData();
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_ID_JOB, ValueMetaInterface.TYPE_INTEGER), id_job);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_NR, ValueMetaInterface.TYPE_INTEGER), new Long(nr));
return database.getRows(sql, 0);
}
// JOBENTRY ATTRIBUTES: SAVE
// WANTED: throw extra exceptions to locate storage problems (strings too long etc)
public synchronized ObjectId saveJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, String code, String value)
throws KettleException
{
return saveJobEntryAttribute(code, 0, id_job, id_jobentry, 0.0, value);
}
public synchronized ObjectId saveJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, String code, double value)
throws KettleException
{
return saveJobEntryAttribute(code, 0, id_job, id_jobentry, value, null);
}
public synchronized ObjectId saveJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, String code, boolean value)
throws KettleException
{
return saveJobEntryAttribute(code, 0, id_job, id_jobentry, 0.0, value ? "Y" : "N");
}
public synchronized ObjectId saveJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, long nr, String code, String value)
throws KettleException
{
return saveJobEntryAttribute(code, nr, id_job, id_jobentry, 0.0, value);
}
public synchronized ObjectId saveJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, long nr, String code, double value)
throws KettleException
{
return saveJobEntryAttribute(code, nr, id_job, id_jobentry, value, null);
}
public synchronized ObjectId saveJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, long nr, String code, boolean value)
throws KettleException
{
return saveJobEntryAttribute(code, nr, id_job, id_jobentry, 0.0, value ? "Y" : "N");
}
private ObjectId saveJobEntryAttribute(String code, long nr, ObjectId id_job, ObjectId id_jobentry, double value_num,
String value_str) throws KettleException
{
return insertJobEntryAttribute(id_job, id_jobentry, nr, code, value_num, value_str);
}
public synchronized ObjectId insertJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, long nr, String code, double value_num,
String value_str) throws KettleException
{
ObjectId id = getNextJobEntryAttributeID();
RowMetaAndData table = new RowMetaAndData();
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_ID_JOBENTRY_ATTRIBUTE, ValueMetaInterface.TYPE_INTEGER), id);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_ID_JOB, ValueMetaInterface.TYPE_INTEGER), id_job);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_ID_JOBENTRY, ValueMetaInterface.TYPE_INTEGER), id_jobentry);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_NR, ValueMetaInterface.TYPE_INTEGER), new Long(nr));
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_VALUE_NUM, ValueMetaInterface.TYPE_NUMBER), new Double(value_num));
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_VALUE_STR, ValueMetaInterface.TYPE_STRING), value_str);
database.prepareInsert(table.getRowMeta(), KettleDatabaseRepository.TABLE_R_JOBENTRY_ATTRIBUTE);
database.setValuesInsert(table);
database.insertRow();
database.closeInsert();
return id;
}
public synchronized LongObjectId getNextJobEntryAttributeID() throws KettleException
{
return getNextID(databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_JOBENTRY_ATTRIBUTE), quote(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_ID_JOBENTRY_ATTRIBUTE));
}
public synchronized LongObjectId getNextID(String tableName, String fieldName) throws KettleException
{
String counterName = tableName+"."+fieldName;
Counter counter = Counters.getInstance().getCounter(counterName);
if (counter==null)
{
LongObjectId id = getNextTableID(tableName, fieldName);
counter = new Counter(id.longValue());
Counters.getInstance().setCounter(counterName, counter);
return new LongObjectId(counter.next());
}
else
{
return new LongObjectId(counter.next());
}
}
private synchronized LongObjectId getNextTableID(String tablename, String idfield) throws KettleException
{
LongObjectId retval = null;
RowMetaAndData r = database.getOneRow("SELECT MAX(" + idfield + ") FROM " + tablename);
if (r != null)
{
Long id = r.getInteger(0);
if (id == null)
{
if (log.isDebug()) log.logDebug("no max(" + idfield + ") found in table " + tablename);
retval = new LongObjectId(1);
}
else
{
if (log.isDebug()) log.logDebug("max(" + idfield + ") found in table " + tablename + " --> " + idfield + " number: " + id);
retval = new LongObjectId(id.longValue() + 1L);
}
}
return retval;
}
// JOBENTRY ATTRIBUTES: GET
public synchronized void setLookupJobEntryAttribute() throws KettleException
{
String sql = "SELECT "+quote(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_VALUE_STR)+", "+quote(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_VALUE_NUM)+
" FROM "+databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_JOBENTRY_ATTRIBUTE)+
" WHERE "+quote(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_ID_JOBENTRY)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_CODE)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_NR)+" = ? ";
pstmt_entry_attributes = database.prepareSQL(sql);
}
public synchronized void closeLookupJobEntryAttribute() throws KettleException
{
database.closePreparedStatement(pstmt_entry_attributes);
pstmt_entry_attributes = null;
}
private RowMetaAndData getJobEntryAttributeRow(ObjectId id_jobentry, int nr, String code) throws KettleException
{
RowMetaAndData par = new RowMetaAndData();
par.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_ID_JOBENTRY, ValueMetaInterface.TYPE_INTEGER), id_jobentry);
par.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
par.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_NR, ValueMetaInterface.TYPE_INTEGER), new Long(nr));
database.setValues(par.getRowMeta(), par.getData(), pstmt_entry_attributes);
Object[] rowData = database.getLookup(pstmt_entry_attributes);
return new RowMetaAndData(database.getReturnRowMeta(), rowData);
}
public synchronized long getJobEntryAttributeInteger(ObjectId id_jobentry, int nr, String code) throws KettleException
{
RowMetaAndData r = getJobEntryAttributeRow(id_jobentry, nr, code);
if (r == null)
return 0;
return r.getInteger(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_VALUE_NUM, 0L);
}
public double getJobEntryAttributeNumber(ObjectId id_jobentry, int nr, String code) throws KettleException
{
RowMetaAndData r = getJobEntryAttributeRow(id_jobentry, nr, code);
if (r == null)
return 0.0;
return r.getNumber(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_VALUE_NUM, 0.0);
}
public synchronized String getJobEntryAttributeString(ObjectId id_jobentry, int nr, String code) throws KettleException
{
RowMetaAndData r = getJobEntryAttributeRow(id_jobentry, nr, code);
if (r == null)
return null;
return r.getString(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_VALUE_STR, null);
}
public boolean getJobEntryAttributeBoolean(ObjectId id_jobentry, int nr, String code) throws KettleException
{
return getJobEntryAttributeBoolean(id_jobentry, nr, code, false);
}
public boolean getJobEntryAttributeBoolean(ObjectId id_jobentry, int nr, String code, boolean def) throws KettleException
{
RowMetaAndData r = getJobEntryAttributeRow(id_jobentry, nr, code);
if (r == null) return def;
String v = r.getString(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_VALUE_STR, null);
if (v==null || Const.isEmpty(v)) return def;
return ValueMeta.convertStringToBoolean(v).booleanValue();
}
public double getJobEntryAttributeNumber(ObjectId id_jobentry, String code) throws KettleException
{
return getJobEntryAttributeNumber(id_jobentry, 0, code);
}
public synchronized long getJobEntryAttributeInteger(ObjectId id_jobentry, String code) throws KettleException
{
return getJobEntryAttributeInteger(id_jobentry, 0, code);
}
public synchronized String getJobEntryAttributeString(ObjectId id_jobentry, String code) throws KettleException
{
return getJobEntryAttributeString(id_jobentry, 0, code);
}
public boolean getJobEntryAttributeBoolean(ObjectId id_jobentry, String code) throws KettleException
{
return getJobEntryAttributeBoolean(id_jobentry, 0, code, false);
}
public boolean getJobEntryAttributeBoolean(ObjectId id_jobentry, String code, boolean def) throws KettleException
{
return getJobEntryAttributeBoolean(id_jobentry, 0, code, def);
}
public synchronized int countNrJobEntryAttributes(ObjectId id_jobentry, String code) throws KettleException
{
String sql = "SELECT COUNT(*) FROM "+databaseMeta.getQuotedSchemaTableCombination(null, KettleDatabaseRepository.TABLE_R_JOBENTRY_ATTRIBUTE)+" WHERE "+quote(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_ID_JOBENTRY)+" = ? AND "+quote(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_CODE)+" = ?";
RowMetaAndData table = new RowMetaAndData();
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_ID_JOBENTRY, ValueMetaInterface.TYPE_INTEGER), id_jobentry);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOBENTRY_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
RowMetaAndData r = database.getOneRow(sql, table.getRowMeta(), table.getData());
if (r == null || r.getData()==null) return 0;
return (int) r.getInteger(0, 0L);
}
// GET NEW IDS
public synchronized ObjectId getNextTransformationID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_TRANSFORMATION), quote(KettleDatabaseRepository.FIELD_TRANSFORMATION_ID_TRANSFORMATION));
}
public synchronized ObjectId getNextJobID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_JOB), quote(KettleDatabaseRepository.FIELD_JOB_ID_JOB));
}
public synchronized ObjectId getNextNoteID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_NOTE), quote(KettleDatabaseRepository.FIELD_NOTE_ID_NOTE));
}
public synchronized ObjectId getNextLogID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_REPOSITORY_LOG), quote(KettleDatabaseRepository.FIELD_REPOSITORY_LOG_ID_REPOSITORY_LOG));
}
public synchronized ObjectId getNextDatabaseID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_DATABASE), quote(KettleDatabaseRepository.FIELD_DATABASE_ID_DATABASE));
}
public synchronized ObjectId getNextDatabaseTypeID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_DATABASE_TYPE), quote(KettleDatabaseRepository.FIELD_DATABASE_TYPE_ID_DATABASE_TYPE));
}
public synchronized ObjectId getNextDatabaseConnectionTypeID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_DATABASE_CONTYPE), quote(KettleDatabaseRepository.FIELD_DATABASE_CONTYPE_ID_DATABASE_CONTYPE));
}
public synchronized ObjectId getNextLoglevelID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_LOGLEVEL), quote(KettleDatabaseRepository.FIELD_LOGLEVEL_ID_LOGLEVEL));
}
public synchronized ObjectId getNextStepTypeID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_STEP_TYPE), quote(KettleDatabaseRepository.FIELD_STEP_TYPE_ID_STEP_TYPE));
}
public synchronized ObjectId getNextStepID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_STEP), quote(KettleDatabaseRepository.FIELD_STEP_ID_STEP));
}
public synchronized ObjectId getNextJobEntryID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_JOBENTRY), quote(KettleDatabaseRepository.FIELD_JOBENTRY_ID_JOBENTRY));
}
public synchronized ObjectId getNextJobEntryTypeID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_JOBENTRY_TYPE), quote(KettleDatabaseRepository.FIELD_JOBENTRY_TYPE_ID_JOBENTRY_TYPE));
}
public synchronized LongObjectId getNextJobEntryCopyID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_JOBENTRY_COPY), quote(KettleDatabaseRepository.FIELD_JOBENTRY_COPY_ID_JOBENTRY_COPY));
}
public synchronized LongObjectId getNextStepAttributeID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_STEP_ATTRIBUTE), quote(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_ID_STEP_ATTRIBUTE));
}
public synchronized LongObjectId getNextTransAttributeID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_TRANS_ATTRIBUTE), quote(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_ID_TRANS_ATTRIBUTE));
}
public synchronized LongObjectId getNextJobAttributeID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_JOB_ATTRIBUTE), quote(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_ID_JOB_ATTRIBUTE));
}
public synchronized LongObjectId getNextDatabaseAttributeID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_DATABASE_ATTRIBUTE), quote(KettleDatabaseRepository.FIELD_DATABASE_ATTRIBUTE_ID_DATABASE_ATTRIBUTE));
}
public synchronized ObjectId getNextTransHopID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_TRANS_HOP), quote(KettleDatabaseRepository.FIELD_TRANS_HOP_ID_TRANS_HOP));
}
public synchronized ObjectId getNextJobHopID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_JOB_HOP), quote(KettleDatabaseRepository.FIELD_JOB_HOP_ID_JOB_HOP));
}
public synchronized ObjectId getNextDepencencyID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_DEPENDENCY), quote(KettleDatabaseRepository.FIELD_DEPENDENCY_ID_DEPENDENCY));
}
public synchronized ObjectId getNextPartitionSchemaID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_PARTITION_SCHEMA), quote(KettleDatabaseRepository.FIELD_PARTITION_SCHEMA_ID_PARTITION_SCHEMA));
}
public synchronized ObjectId getNextPartitionID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_PARTITION), quote(KettleDatabaseRepository.FIELD_PARTITION_ID_PARTITION));
}
public synchronized ObjectId getNextTransformationPartitionSchemaID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_TRANS_PARTITION_SCHEMA), quote(KettleDatabaseRepository.FIELD_TRANS_PARTITION_SCHEMA_ID_TRANS_PARTITION_SCHEMA));
}
public synchronized ObjectId getNextClusterID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_CLUSTER), quote(KettleDatabaseRepository.FIELD_CLUSTER_ID_CLUSTER));
}
public synchronized ObjectId getNextSlaveServerID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_SLAVE), quote(KettleDatabaseRepository.FIELD_SLAVE_ID_SLAVE));
}
public synchronized ObjectId getNextClusterSlaveID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_CLUSTER_SLAVE), quote(KettleDatabaseRepository.FIELD_CLUSTER_SLAVE_ID_CLUSTER_SLAVE));
}
public synchronized ObjectId getNextTransformationSlaveID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_TRANS_SLAVE), quote(KettleDatabaseRepository.FIELD_TRANS_SLAVE_ID_TRANS_SLAVE));
}
public synchronized ObjectId getNextTransformationClusterID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_TRANS_CLUSTER), quote(KettleDatabaseRepository.FIELD_TRANS_CLUSTER_ID_TRANS_CLUSTER));
}
public synchronized ObjectId getNextConditionID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_CONDITION), quote(KettleDatabaseRepository.FIELD_CONDITION_ID_CONDITION));
}
public synchronized ObjectId getNextValueID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_VALUE), quote(KettleDatabaseRepository.FIELD_VALUE_ID_VALUE));
}
public synchronized ObjectId getNextUserID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_USER), quote(KettleDatabaseRepository.FIELD_USER_ID_USER));
}
public synchronized void clearNextIDCounters()
{
Counters.getInstance().clear();
}
public synchronized ObjectId getNextDirectoryID() throws KettleException
{
return getNextID(quoteTable(KettleDatabaseRepository.TABLE_R_DIRECTORY), quote(KettleDatabaseRepository.FIELD_DIRECTORY_ID_DIRECTORY));
}
public synchronized ObjectId insertStepAttribute(ObjectId id_transformation, ObjectId id_step, long nr, String code, double value_num,
String value_str) throws KettleException
{
ObjectId id = getNextStepAttributeID();
RowMetaAndData table = new RowMetaAndData();
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_ID_STEP_ATTRIBUTE, ValueMetaInterface.TYPE_INTEGER), id);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_ID_TRANSFORMATION, ValueMetaInterface.TYPE_INTEGER), id_transformation);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_ID_STEP, ValueMetaInterface.TYPE_INTEGER), id_step);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_NR, ValueMetaInterface.TYPE_INTEGER), new Long(nr));
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_VALUE_NUM, ValueMetaInterface.TYPE_NUMBER), new Double(value_num));
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_STEP_ATTRIBUTE_VALUE_STR, ValueMetaInterface.TYPE_STRING), value_str);
/* If we have prepared the insert, we don't do it again.
* We assume that all the step insert statements come one after the other.
*/
if (psStepAttributesInsert == null)
{
String sql = database.getInsertStatement(KettleDatabaseRepository.TABLE_R_STEP_ATTRIBUTE, table.getRowMeta());
psStepAttributesInsert = database.prepareSQL(sql);
}
database.setValues(table, psStepAttributesInsert);
database.insertRow(psStepAttributesInsert, useBatchProcessing);
if (log.isDebug()) log.logDebug("saved attribute ["+code+"]");
return id;
}
public synchronized ObjectId insertTransAttribute(ObjectId id_transformation, long nr, String code, long value_num, String value_str) throws KettleException
{
ObjectId id = getNextTransAttributeID();
RowMetaAndData table = new RowMetaAndData();
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_ID_TRANS_ATTRIBUTE, ValueMetaInterface.TYPE_INTEGER), id);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_ID_TRANSFORMATION, ValueMetaInterface.TYPE_INTEGER), id_transformation);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_NR, ValueMetaInterface.TYPE_INTEGER), new Long(nr));
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_VALUE_NUM, ValueMetaInterface.TYPE_INTEGER), new Long(value_num));
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_TRANS_ATTRIBUTE_VALUE_STR, ValueMetaInterface.TYPE_STRING), value_str);
/* If we have prepared the insert, we don't do it again.
* We asume that all the step insert statements come one after the other.
*/
if (psTransAttributesInsert == null)
{
String sql = database.getInsertStatement(KettleDatabaseRepository.TABLE_R_TRANS_ATTRIBUTE, table.getRowMeta());
psTransAttributesInsert = database.prepareSQL(sql);
}
database.setValues(table, psTransAttributesInsert);
database.insertRow(psTransAttributesInsert, useBatchProcessing);
if (log.isDebug()) log.logDebug("saved transformation attribute ["+code+"]");
return id;
}
public synchronized ObjectId insertJobAttribute(ObjectId id_job, long nr, String code, long value_num, String value_str) throws KettleException
{
ObjectId id = getNextJobAttributeID();
//System.out.println("Insert job attribute : id_job="+id_job+", code="+code+", value_str="+value_str);
RowMetaAndData table = new RowMetaAndData();
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_ID_JOB_ATTRIBUTE, ValueMetaInterface.TYPE_INTEGER), id);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_ID_JOB, ValueMetaInterface.TYPE_INTEGER), id_job);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_NR, ValueMetaInterface.TYPE_INTEGER), new Long(nr));
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_CODE, ValueMetaInterface.TYPE_STRING), code);
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_VALUE_NUM, ValueMetaInterface.TYPE_INTEGER), new Long(value_num));
table.addValue(new ValueMeta(KettleDatabaseRepository.FIELD_JOB_ATTRIBUTE_VALUE_STR, ValueMetaInterface.TYPE_STRING), value_str);
/* If we have prepared the insert, we don't do it again.
* We asume that all the step insert statements come one after the other.
*/
if (psJobAttributesInsert == null)
{
String sql = database.getInsertStatement(KettleDatabaseRepository.TABLE_R_JOB_ATTRIBUTE, table.getRowMeta());
psJobAttributesInsert = database.prepareSQL(sql);
}
database.setValues(table, psJobAttributesInsert);
database.insertRow(psJobAttributesInsert, useBatchProcessing);
if (log.isDebug()) log.logDebug("saved job attribute ["+code+"]");
return id;
}
public synchronized void updateTableRow(String tablename, String idfield, RowMetaAndData values, ObjectId id) throws KettleException
{
String sets[] = new String[values.size()];
for (int i = 0; i < values.size(); i++)
sets[i] = values.getValueMeta(i).getName();
String codes[] = new String[] { idfield };
String condition[] = new String[] { "=" };
database.prepareUpdate(tablename, codes, condition, sets);
values.addValue(new ValueMeta(idfield, ValueMetaInterface.TYPE_INTEGER), id);
database.setValuesUpdate(values.getRowMeta(), values.getData());
database.updateRow();
database.closeUpdate();
}
public synchronized void updateTableRow(String tablename, String idfield, RowMetaAndData values) throws KettleException
{
long id = values.getInteger(idfield, 0L);
values.removeValue(idfield);
String sets[] = new String[values.size()];
for (int i = 0; i < values.size(); i++)
sets[i] = values.getValueMeta(i).getName();
String codes[] = new String[] { idfield };
String condition[] = new String[] { "=" };
database.prepareUpdate(tablename, codes, condition, sets);
values.addValue(new ValueMeta(idfield, ValueMetaInterface.TYPE_INTEGER), new Long(id));
database.setValuesUpdate(values.getRowMeta(), values.getData());
database.updateRow();
}
/**
* @param id_directory
* @return A list of RepositoryObjects
*
* @throws KettleException
*/
public synchronized List<RepositoryElementMetaInterface> getRepositoryObjects(String tableName, RepositoryObjectType objectType, ObjectId id_directory) throws KettleException
{
try
{
String idField;
if (RepositoryObjectType.TRANSFORMATION.equals(objectType)) {
idField = KettleDatabaseRepository.FIELD_TRANSFORMATION_ID_TRANSFORMATION;
} else {
idField = KettleDatabaseRepository.FIELD_JOB_ID_JOB;
}
if (id_directory==null) {
id_directory = new LongObjectId(0L); // root!
}
RepositoryDirectoryInterface repositoryDirectory = repository.directoryDelegate.loadPathToRoot(id_directory);
// RepositoryDirectoryInterface repositoryDirectory = repository.loadRepositoryDirectoryTree().findDirectory(id_directory);
String sql = "SELECT "+quote(KettleDatabaseRepository.FIELD_TRANSFORMATION_NAME)+", "+
quote(KettleDatabaseRepository.FIELD_TRANSFORMATION_MODIFIED_USER)+", "+
quote(KettleDatabaseRepository.FIELD_TRANSFORMATION_MODIFIED_DATE)+", "+
quote(KettleDatabaseRepository.FIELD_TRANSFORMATION_DESCRIPTION)+", " +
quote(idField) + " " +
"FROM "+tableName+" " +
"WHERE "+quote(KettleDatabaseRepository.FIELD_TRANSFORMATION_ID_DIRECTORY)+" = ? "
;
RowMetaAndData directoryIdRow = getParameterMetaData(id_directory);
List<RepositoryElementMetaInterface> repositoryObjects = new ArrayList<RepositoryElementMetaInterface>();
ResultSet rs = database.openQuery(sql, directoryIdRow.getRowMeta(), directoryIdRow.getData());
if (rs != null)
{
List<Object[]> rows = database.getRows(rs, -1, null);
if ( rs != null )
{
database.closeQuery(rs);
}
RowMetaInterface rowMeta = database.getReturnRowMeta();
for (Object[] r : rows)
{
ObjectId id = new LongObjectId( rowMeta.getInteger(r, 4) );
repositoryObjects.add(new RepositoryObject(id, rowMeta.getString(r, 0), repositoryDirectory, rowMeta.getString(r, 1), rowMeta.getDate(r, 2), objectType, rowMeta.getString(r, 3), false));
}
}
return repositoryObjects;
}
catch(Exception e) {
throw new KettleException("Unable to get list of repository objects", e);
}
}
public ObjectId[] getIDs(String sql, ObjectId...objectId) throws KettleException
{
// Get the prepared statement
PreparedStatement ps = sqlMap.get(sql);
if (ps == null) {
ps = database.prepareSQL(sql);
sqlMap.put(sql, ps);
}
// Assemble the parameters (if any)
RowMetaInterface parameterMeta = new RowMeta();
Object[] parameterData = new Object[objectId.length];
for (int i = 0; i < objectId.length; i++) {
parameterMeta.addValueMeta(new ValueMeta("id" + (i + 1), ValueMetaInterface.TYPE_INTEGER));
parameterData[i] = ((LongObjectId)objectId[i]).longValue();
}
ResultSet resultSet = database.openQuery(ps, parameterMeta, parameterData);
List<Object[]> rows = database.getRows(resultSet, 0, null);
if (Const.isEmpty(rows)) {
return new ObjectId[0];
}
RowMetaInterface rowMeta = database.getReturnRowMeta();
ObjectId[] ids = new ObjectId[rows.size()];
for (int i=0;i<ids.length;i++) {
Object[] row = rows.get(i);
ids[i] = new LongObjectId(rowMeta.getInteger(row, 0));
}
return ids;
}
public String[] getStrings(String sql, ObjectId...objectId) throws KettleException
{
// Get the prepared statement
PreparedStatement ps = sqlMap.get(sql);
if (ps == null) {
ps = database.prepareSQL(sql);
sqlMap.put(sql, ps);
}
// Assemble the parameters (if any)
// Assemble the parameters (if any)
RowMetaInterface parameterMeta = new RowMeta();
Object[] parameterData = new Object[objectId.length];
for (int i = 0; i < objectId.length; i++) {
parameterMeta.addValueMeta(new ValueMeta("id" + (i + 1), ValueMetaInterface.TYPE_INTEGER));
parameterData[i] = ((LongObjectId)objectId[i]).longValue();
}
// Get the result set back...
ResultSet resultSet = database.openQuery(ps, parameterMeta, parameterData);
List<Object[]> rows = database.getRows(resultSet, 0, null);
if (Const.isEmpty(rows)) {
return new String[0];
}
// assemble the result
RowMetaInterface rowMeta = database.getReturnRowMeta();
String[] strings = new String[rows.size()];
for (int i=0;i<strings.length;i++) {
Object[] row = rows.get(i);
strings[i] = rowMeta.getString(row, 0);
}
return strings;
}
public static final ObjectId[] convertLongList(List<Long> list)
{
ObjectId[] ids = new ObjectId[list.size()];
for (int i=0;i<ids.length;i++) ids[i] = new LongObjectId( list.get(i) );
return ids;
}
private String[] getQuotedSchemaTablenames(String[] tables) {
String quoted[] = new String[tables.length];
for (int i=0;i<quoted.length;i++) {
quoted[i] = database.getDatabaseMeta().getQuotedSchemaTableCombination(null, tables[i]);
}
return quoted;
}
public synchronized void lockRepository() throws KettleException
{
if (database.getDatabaseMeta().needsToLockAllTables())
{
database.lockTables(getQuotedSchemaTablenames(KettleDatabaseRepository.repositoryTableNames));
}
else
{
database.lockTables( getQuotedSchemaTablenames( new String[] { KettleDatabaseRepository.TABLE_R_REPOSITORY_LOG, } ));
}
}
public synchronized void unlockRepository() throws KettleException
{
if (database.getDatabaseMeta().needsToLockAllTables())
{
database.unlockTables(KettleDatabaseRepository.repositoryTableNames);
}
else
{
database.unlockTables( new String[] { KettleDatabaseRepository.TABLE_R_REPOSITORY_LOG, } );
}
}
/**
* @return the stepAttributesRowMeta
*/
public RowMetaInterface getStepAttributesRowMeta() {
return stepAttributesRowMeta;
}
public boolean isUseBatchProcessing() {
return useBatchProcessing;
}
/**
* @param stepAttributesRowMeta the stepAttributesRowMeta to set
*/
public void setStepAttributesRowMeta(RowMetaInterface stepAttributesRowMeta) {
this.stepAttributesRowMeta = stepAttributesRowMeta;
}
public synchronized ObjectId getIDWithValue(String tablename, String idfield, String lookupfield, String value) throws KettleException
{
RowMetaAndData par = new RowMetaAndData();
par.addValue(new ValueMeta("value", ValueMetaInterface.TYPE_STRING), value);
RowMetaAndData result = getOneRow("SELECT " + idfield + " FROM " + tablename+ " WHERE " + lookupfield + " = ?", par.getRowMeta(), par.getData());
if (result != null && result.getRowMeta() != null && result.getData() != null && result.isNumeric(0)) {
return new LongObjectId(result.getInteger(0, 0));
}
return null;
}
public synchronized ObjectId getIDWithValue(String tablename, String idfield, String lookupfield, String value, String lookupkey, ObjectId key) throws KettleException
{
RowMetaAndData par = new RowMetaAndData();
par.addValue(new ValueMeta("value", ValueMetaInterface.TYPE_STRING), value);
par.addValue(new ValueMeta("key", ValueMetaInterface.TYPE_INTEGER), new LongObjectId(key));
RowMetaAndData result = getOneRow("SELECT " + idfield + " FROM " + tablename + " WHERE " + lookupfield + " = ? AND "
+ lookupkey + " = ?", par.getRowMeta(), par.getData());
if (result != null && result.getRowMeta() != null && result.getData() != null && result.isNumeric(0)) {
return new LongObjectId(result.getInteger(0, 0));
}
return null;
}
public synchronized ObjectId getIDWithValue(String tablename, String idfield, String lookupkey[], ObjectId key[]) throws KettleException
{
RowMetaAndData par = new RowMetaAndData();
String sql = "SELECT " + idfield + " FROM " + tablename + " ";
for (int i = 0; i < lookupkey.length; i++)
{
if (i == 0)
sql += "WHERE ";
else
sql += "AND ";
par.addValue(new ValueMeta(lookupkey[i], ValueMetaInterface.TYPE_INTEGER), new LongObjectId(key[i]));
sql += lookupkey[i] + " = ? ";
}
RowMetaAndData result = getOneRow(sql, par.getRowMeta(), par.getData());
if (result != null && result.getRowMeta() != null && result.getData() != null && result.isNumeric(0)) {
return new LongObjectId(result.getInteger(0, 0));
}
return null;
}
public synchronized ObjectId getIDWithValue(String tablename, String idfield, String lookupfield, String value, String lookupkey[], ObjectId key[]) throws KettleException
{
RowMetaAndData par = new RowMetaAndData();
par.addValue(new ValueMeta(lookupfield, ValueMetaInterface.TYPE_STRING), value);
String sql = "SELECT " + idfield + " FROM " + tablename + " WHERE " + lookupfield + " = ? ";
for (int i = 0; i < lookupkey.length; i++)
{
par.addValue( new ValueMeta(lookupkey[i], ValueMetaInterface.TYPE_STRING), new LongObjectId(key[i]) );
sql += "AND " + lookupkey[i] + " = ? ";
}
RowMetaAndData result = getOneRow(sql, par.getRowMeta(), par.getData());
if (result != null && result.getRowMeta() != null && result.getData() != null && result.isNumeric(0)) {
return new LongObjectId(result.getInteger(0, 0));
}
return null;
}
public RowMetaAndData getOneRow(String tablename, String keyfield, ObjectId id) throws KettleException
{
String sql = "SELECT * FROM " + tablename + " WHERE " + keyfield + " = ?";
// Get the prepared statement
PreparedStatement ps = sqlMap.get(sql);
if (ps == null) {
ps = database.prepareSQL(sql);
sqlMap.put(sql, ps);
}
// Assemble the parameter (if any)
RowMetaInterface parameterMeta = new RowMeta();
parameterMeta.addValueMeta(new ValueMeta("id", ValueMetaInterface.TYPE_INTEGER));
Object[] parameterData = new Object[] { id != null ? Long.parseLong(id.getId()) : null, } ;
ResultSet resultSet = null;
try {
resultSet = database.openQuery(ps, parameterMeta, parameterData);
Object[] result = database.getRow(resultSet);
if (result==null) return new RowMetaAndData(database.getReturnRowMeta(), RowDataUtil.allocateRowData(database.getReturnRowMeta().size()));
return new RowMetaAndData(database.getReturnRowMeta(), result);
} catch(KettleException e) {
throw e;
} finally {
if (resultSet!=null) database.closeQuery(resultSet);
}
}
public RowMetaAndData getOneRow(String sql) throws KettleDatabaseException {
return database.getOneRow(sql);
}
public RowMetaAndData getOneRow(String sql, RowMetaInterface rowMeta, Object[] rowData) throws KettleDatabaseException {
return database.getOneRow(sql, rowMeta, rowData);
}
public synchronized String getStringWithID(String tablename, String keyfield, ObjectId id, String fieldname) throws KettleException
{
String sql = "SELECT " + fieldname + " FROM " + tablename + " WHERE " + keyfield + " = ?";
RowMetaAndData par = new RowMetaAndData();
par.addValue(new ValueMeta(keyfield, ValueMetaInterface.TYPE_INTEGER), id);
RowMetaAndData result = getOneRow(sql, par.getRowMeta(), par.getData());
if (result != null && result.getData()!=null)
{
return result.getString(0, null);
}
return null;
}
public List<Object[]> getRows(String sql, int limit) throws KettleDatabaseException {
return database.getRows(sql, limit);
}
public RowMetaInterface getReturnRowMeta() throws KettleDatabaseException {
return database.getReturnRowMeta();
}
public synchronized void insertTableRow(String tablename, RowMetaAndData values) throws KettleException
{
database.prepareInsert(values.getRowMeta(), tablename);
database.setValuesInsert(values);
database.insertRow();
database.closeInsert();
}
public Collection<RowMetaAndData> getDatabaseAttributes(ObjectId id_database) throws KettleDatabaseException, KettleValueException {
String sql = "SELECT * FROM " + quoteTable(KettleDatabaseRepository.TABLE_R_DATABASE_ATTRIBUTE) + " WHERE " + quote(KettleDatabaseRepository.FIELD_DATABASE_ID_DATABASE) + " = ?";
// Get the prepared statement
PreparedStatement ps = sqlMap.get(sql);
if (ps == null) {
ps = database.prepareSQL(sql);
sqlMap.put(sql, ps);
}
// Assemble the parameter (if any)
RowMetaInterface parameterMeta = new RowMeta();
parameterMeta.addValueMeta(new ValueMeta("id", ValueMetaInterface.TYPE_INTEGER));
Object[] parameterData = new Object[] { ((LongObjectId)id_database).longValue(), } ;
List<RowMetaAndData> attrs = new ArrayList<RowMetaAndData>();
ResultSet resultSet = null;
try {
resultSet = database.openQuery(ps, parameterMeta, parameterData);
List<Object[]> rows = database.getRows(resultSet, 0, null);
for (Object[] row : rows) {
RowMetaAndData rowWithMeta = new RowMetaAndData(repository.connectionDelegate.getReturnRowMeta(), row);
long id = rowWithMeta.getInteger(quote(KettleDatabaseRepository.FIELD_DATABASE_ATTRIBUTE_ID_DATABASE_ATTRIBUTE), 0);
if (id > 0) {
attrs.add(rowWithMeta);
}
}
return attrs;
} catch(KettleDatabaseException e) {
throw e;
} finally {
database.closeQuery(resultSet);
}
}
public RowMetaAndData getParameterMetaData(ObjectId...ids) throws KettleException {
RowMetaInterface parameterMeta = new RowMeta();
Object[] parameterData = new Object[ids.length];
for (int i = 0; i < ids.length; i++) {
parameterMeta.addValueMeta(new ValueMeta("id" + (i + 1), ValueMetaInterface.TYPE_INTEGER));
parameterData[i] = Long.valueOf(ids[i].getId());
}
return new RowMetaAndData(parameterMeta, parameterData);
}
public void performDelete(String sql, ObjectId...ids) throws KettleException {
try {
PreparedStatement ps = sqlMap.get(sql);
if (ps==null) {
ps = database.prepareSQL(sql);
sqlMap.put(sql, ps);
}
RowMetaAndData param = getParameterMetaData(ids);
database.setValues(param, ps);
ps.execute();
} catch(SQLException e) {
throw new KettleException("Unable to perform delete with SQL: "+sql+", ids="+ids.toString(), e);
}
}
}
|
package org.helioviewer.jhv.plugins.swhvhekplugin;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import org.helioviewer.jhv.base.time.JHVDate;
import org.helioviewer.jhv.data.container.JHVEventContainer;
import org.helioviewer.jhv.data.container.JHVEventHandler;
import org.helioviewer.jhv.data.container.cache.JHVEventCache;
import org.helioviewer.jhv.data.container.cache.JHVEventCache.SortedDateInterval;
import org.helioviewer.jhv.data.container.cache.JHVEventCacheResult;
import org.helioviewer.jhv.data.datatype.event.JHVEventParameter;
import org.helioviewer.jhv.data.datatype.event.JHVEventType;
import org.helioviewer.jhv.data.datatype.event.JHVRelatedEvents;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.layers.Layers;
import org.helioviewer.jhv.layers.LayersListener;
import org.helioviewer.jhv.viewmodel.view.View;
/**
* This class intercepts changes of the layers and request data from the
* JHVEventContainer.
*
* @author Bram Bourgoignie (Bram.Bourgoignie@oma.be)
*
*/
public class SWHVHEKData implements LayersListener, JHVEventHandler {
private static SWHVHEKData instance;
private Date beginDate = null;
private Date endDate = null;
private Map<JHVEventType, SortedMap<SortedDateInterval, JHVRelatedEvents>> data;
private SWHVHEKData() {
}
public static SWHVHEKData getSingletonInstance() {
if (instance == null) {
instance = new SWHVHEKData();
}
return instance;
}
public void reset() {
instance = null;
}
public void requestEvents() {
boolean request = false;
JHVDate first = Layers.getStartDate();
JHVDate last = Layers.getEndDate();
if (first != null) {
if (beginDate == null || first.milli < beginDate.getTime()) {
beginDate = first.getDate();
request = true;
}
}
if (last != null) {
if (endDate == null || last.milli > endDate.getTime()) {
endDate = last.getDate();
request = true;
}
}
if (request) {
JHVEventContainer.getSingletonInstance().requestForInterval(beginDate, endDate, SWHVHEKData.this);
}
}
@Override
public void layerAdded(View view) {
requestEvents();
}
@Override
public void activeLayerChanged(View view) {
}
@Override
public void newEventsReceived(Map<JHVEventType, SortedMap<SortedDateInterval, JHVRelatedEvents>> eventList) {
requestEvents();
displayEvents();
}
@Override
public void cacheUpdated() {
if (beginDate != null && endDate != null) {
beginDate = null;
endDate = null;
requestEvents();
displayEvents();
}
}
private void displayEvents() {
if (beginDate != null && endDate != null) {
Displayer.display();
}
}
public ArrayList<JHVRelatedEvents> getActiveEvents(Date currentDate) {
long ts = currentDate.getTime();
ArrayList<JHVRelatedEvents> activeEvents = new ArrayList<JHVRelatedEvents>();
if (beginDate != null && endDate != null) {
JHVEventCacheResult result = JHVEventCache.getSingletonInstance().get(beginDate, endDate, beginDate, endDate);
data = result.getAvailableEvents();
if (data != null) {
for (Entry<JHVEventType, SortedMap<SortedDateInterval, JHVRelatedEvents>> v1 : data.entrySet()) {
for (Map.Entry<JHVEventCache.SortedDateInterval, JHVRelatedEvents> v2 : v1.getValue().entrySet()) {
JHVRelatedEvents evr = v2.getValue();
if (evr.getStart() <= ts && evr.getEnd() >= ts)
activeEvents.add(evr);
}
}
}
}
return activeEvents;
}
public static double readCMESpeed(Map<String, JHVEventParameter> params) {
double speed = 500;
try {
if (params.containsKey("cme_radiallinvel"))
speed = Double.parseDouble(params.get("cme_radiallinvel").getParameterValue());
} catch (Exception e) {
}
return speed;
}
public static double readCMEPrincipalAngleDegree(Map<String, JHVEventParameter> params) {
double principalAngle = 0;
try {
if (params.containsKey("event_coord1"))
principalAngle = Double.parseDouble(params.get("event_coord1").getParameterValue()) + 90;
} catch (Exception e) {
}
return principalAngle;
}
public static double readCMEAngularWidthDegree(Map<String, JHVEventParameter> params) {
double angularWidthDegree = 0;
try {
if (params.containsKey("cme_angularwidth"))
angularWidthDegree = Double.parseDouble(params.get("cme_angularwidth").getParameterValue());
} catch (Exception e) {
}
return angularWidthDegree;
}
public Date getStart() {
return this.beginDate;
}
public Date getEnd() {
return this.endDate;
}
}
|
package net.openhft.chronicle.map.fromdocs.acid.revelations;
import net.openhft.chronicle.core.values.LongValue;
import net.openhft.chronicle.map.ChronicleMap;
import net.openhft.chronicle.map.ChronicleMapBuilder;
import net.openhft.chronicle.values.Values;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.locks.StampedLock;
import static net.openhft.chronicle.values.Values.newNativeReference;
/**
* ben.cotton@rutgers.edu
* <p>
* A totally hacked impl, awaiting OpenHFT's official ChronicleStampedLock API
* <p>
* A usable 'reference' impl will more properly belong in the Chronicle-Algorithms/ repo
* <p>
* NOTE: This impl only provides off-Heap capability for the tryXXXXX() family of
* j.u.c.l.StampedLock methosds.
*/
public class ChronicleStampedLock extends StampedLock {
ChronicleMap<String, ChronicleStampedLockVOInterface> chm; //custody of StampedLock semantics
ChronicleMap<String, LongValue> chmR; //Chronicle AtomicLong re: Reader set custody
ChronicleStampedLockVOInterface offHeapLock =
newNativeReference(ChronicleStampedLockVOInterface.class); //the off-heap ChronicleStampedLock
ChronicleStampedLockVOInterface lastWriterT =
newNativeReference(ChronicleStampedLockVOInterface.class); //needed to facilitate validate(stamp)
LongValue readLockHolderCount = Values.newNativeReference(LongValue.class); //ReaderSet cardinality
ChronicleStampedLock(String chronicelStampedLockLocality) { // path of Operand set i.e. /dev/shm/
try {
chm = offHeapLock(chronicelStampedLockLocality);
chmR = offHeapLockReaderCount(chronicelStampedLockLocality + "=ReaderCount");
chm.acquireUsing("Stamp ", offHeapLock); // K="Stamp ", V=OffHeapLock impl
chm.acquireUsing("LastWriterTime ", lastWriterT); //needed for validate
chmR.acquireUsing("ReaderCount ", readLockHolderCount);
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock constructed" +
","
);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public long tryOptimisticRead() {
(offHeapLock = chm.get("Stamp ")).setEntryLockState(0L);
long t = System.currentTimeMillis();
chm.put("Stamp ", offHeapLock);
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock saw stamp=[" + 0L + "]" +
" tryOptmisticRead() returning stamp=" +
t +
","
);
return (t);
}
@Override
public boolean validate(long stamp) {
offHeapLock = chm.get("Stamp ");
lastWriterT = chm.get("LastWriterTime ");
boolean ret = false;
/**
* If *any* Writer interacted with the offHeapLock, since event=tryOptimisticRead(),
* then FAIL the validate() invoke.
*
* Upon FAILURE, the thread on tryOptimisticRead() must apply its PESSIMISTIC policy (Thread
* has endured a DIRTY_READ.)
*
*/
if (lastWriterT.getEntryLockState() > stamp || offHeapLock.getEntryLockState() < 0L) {
ret = Boolean.FALSE;
} else {
ret = Boolean.TRUE;
}
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock validate(" +
stamp + ") returned =[" +
ret + "] " +
","
);
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock LastWriterT=[" +
lastWriterT.getEntryLockState() + "] " +
","
);
return ret;
}
@Override
public long tryWriteLock() {
long l = 0L;
offHeapLock = chm.get("Stamp ");
lastWriterT = chm.get("LastWriterTime ");
l = offHeapLock.getEntryLockState();
if (l != 0L)
return 0L;
do {
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock tryWriteLock() ?WAITING " +
" on offHeapLock.unlock(" +
offHeapLock.getEntryLockState() +
") ,"
);
offHeapLock = chm.get("Stamp ");
l = offHeapLock.getEntryLockState();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (l != 0L || readLockHolderCount.getVolatileValue() > 0);
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock tryWriteLock() PROCEEDING " +
" ,"
);
long t = System.currentTimeMillis();
offHeapLock.setEntryLockState(-t); //negative ==> Writer holds StampedLock
lastWriterT.setEntryLockState(t);
chm.put("Stamp ", offHeapLock);
chm.put("LastWriterTime ", lastWriterT);
System.out.println(
" ,@t=" + t +
" ChronicleStampedLock tryWriteLock() returned stamp=" +
offHeapLock.getEntryLockState() +
","
);
return (offHeapLock.getEntryLockState());
}
@Override
public long tryReadLock() {
long l = 0L;
offHeapLock = chm.get("Stamp ");
readLockHolderCount = chmR.get("ReaderCount ");
l = (offHeapLock = chm.get("Stamp ")).getEntryLockState();
if (l < 0L)
return (0);
do {
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock tryReadLock() ?WAITING on Writer.unlock(" +
offHeapLock.getEntryLockState() +
") ,"
);
l = (offHeapLock = chm.get("Stamp ")).getEntryLockState();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (l < 0L);
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock tryReadLock() PROCEEDING " +
//" readerCount=[" + readerCount.getReaderCount() + "]" +
" readerCount=[" +
(readLockHolderCount = chmR.get("ReaderCount ")).getVolatileValue() + "]" +
" BEFORE addAtomic(1) " +
","
);
readLockHolderCount.addAtomicValue(1); // INCREMENT the cardinality of the Reader set
chmR.put("ReaderCount ", readLockHolderCount); // and make it IPC visible
offHeapLock.setEntryLockState(
readLockHolderCount.getVolatileValue()
); // assign the Lock to most-recent Reader
chm.put("Stamp ", offHeapLock); // make it IPC visible
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock tryReadLock() returned stamp=" +
offHeapLock.getEntryLockState() +
" readerCount=[" + readLockHolderCount.getVolatileValue() + "]" +
" AFTER addAtomic(1) " +
","
);
return (offHeapLock.getEntryLockState());
}
@Override
public long writeLock() {
long l = 0L;
offHeapLock = chm.get("Stamp ");
lastWriterT = chm.get("LastWriterTime ");
do {
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock writeLock() ?WAITING " +
" on offHeapLock.unlock(" +
offHeapLock.getEntryLockState() +
") ,"
);
offHeapLock = chm.get("Stamp ");
l = offHeapLock.getEntryLockState();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (l != 0L || readLockHolderCount.getVolatileValue() > 0);
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock writeLock() PROCEEDING " +
" ,"
);
long t = System.currentTimeMillis();
offHeapLock.setEntryLockState(-t); //negative ==> Writer holds StampedLock
lastWriterT.setEntryLockState(t);
chm.put("Stamp ", offHeapLock);
chm.put("LastWriterTime ", lastWriterT);
System.out.println(
" ,@t=" + t +
" ChronicleStampedLock writeLock() returned stamp=" +
offHeapLock.getEntryLockState() +
","
);
return (offHeapLock.getEntryLockState());
}
@Override
public long readLock() {
long l = 0L;
offHeapLock = chm.get("Stamp ");
readLockHolderCount = chmR.get("ReaderCount ");
do {
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock readLock() ?WAITING on Writer.unlock(" +
offHeapLock.getEntryLockState() +
") ,"
);
l = (offHeapLock = chm.get("Stamp ")).getEntryLockState();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (l < 0L);
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock readLock() PROCEEDING " +
//" readerCount=[" + Count.getReaderCount() + "]" +
" readerCount=[" +
(readLockHolderCount = chmR.get("ReaderCount ")).getVolatileValue() + "]" +
" BEFORE addAtomic(1) " +
","
);
readLockHolderCount.addAtomicValue(1); // INCREMENT the cardinality of the Reader set
chmR.put("ReaderCount ", readLockHolderCount); // and make it IPC visible
offHeapLock.setEntryLockState(
readLockHolderCount.getVolatileValue()
); // assign the Lock to most-recent Reader
chm.put("Stamp ", offHeapLock); // make it IPC visible
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock readLock() returned stamp=" +
offHeapLock.getEntryLockState() +
" readerCount=[" + readLockHolderCount.getVolatileValue() + "]" +
" AFTER addAtomic(1) " +
","
);
return (offHeapLock.getEntryLockState());
}
@Override
public void unlock(long stamp) {
if (stamp < 0L) {
unlockWrite(stamp);
} else if (stamp > 0L) {
unlockRead(stamp);
} else {
;// lock available
}
}
@Override
public void unlockRead(long stamp) {
offHeapLock = chm.get("Stamp ");
readLockHolderCount = chmR.get("ReaderCount ");
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock unlockRead(" + stamp + ") unlocking.." +
"ReaderCount=[" +
(readLockHolderCount = chmR.get("ReaderCount ")).getVolatileValue() + "]" +
" BEFORE addAtomic(-1) " +
","
);
readLockHolderCount.addAtomicValue(-1); // DECREMENT the cardinality of the Reader set
chmR.put("ReaderCount ", readLockHolderCount); // make it IPC visible
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock unlockRead(" + stamp + ") unlocking.." +
"ReaderCount=[" +
(readLockHolderCount = chmR.get("ReaderCount ")).getVolatileValue() + "]" +
" AFTER addAtomic(-1) " +
","
);
offHeapLock.setEntryLockState(
(readLockHolderCount = chmR.get("ReaderCount ")).getVolatileValue()
);
System.out.println(
" ,@t=" + System.currentTimeMillis() +
"offHeapLock=[" + offHeapLock.getEntryLockState() + "]" +
","
);
chm.put("Stamp ", offHeapLock);
chmR.put("ReaderCount ", readLockHolderCount);
}
@Override
public void unlockWrite(long stamp) {
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock unlockWrite(" + stamp + ") unlocking..,"
);
offHeapLock = chm.get("Stamp ");
offHeapLock.setEntryLockState(0L);
chm.put("Stamp ", offHeapLock);
System.out.println(
" ,@t=" + System.currentTimeMillis() +
" ChronicleStampedLock unlockWrite(" +
(offHeapLock = chm.get("Stamp ")).getEntryLockState() +
") unlocked. set to Zero" +
","
);
}
@Override
public int getReadLockCount() {
return ((int) chmR.get("ReaderCount ").getVolatileValue());
}
@Override
public boolean isReadLocked() {
if (this.getReadLockCount() > 0)
return (Boolean.TRUE);
else
return (Boolean.FALSE);
}
@Override
public boolean isWriteLocked() {
if (this.getReadLockCount() < 0)
return (Boolean.TRUE);
else
return (Boolean.FALSE);
}
static ChronicleMap<String, ChronicleStampedLockVOInterface> offHeapLock(String operand)
throws IOException {
return ChronicleMapBuilder.of(String.class, ChronicleStampedLockVOInterface.class)
.entries(16)
.averageKeySize("123456789".length())
.createPersistedTo(
new File(
operand
)
);
}
static ChronicleMap<String, LongValue> offHeapLockReaderCount(String operand)
throws IOException {
return ChronicleMapBuilder.of(String.class, LongValue.class)
.entries(16)
.averageKeySize("123456789".length())
.createPersistedTo(
new File(
operand
)
);
}
}
|
package org.eclipse.xtext.generator.tests;
import junit.framework.Test;
import junit.framework.TestSuite;
/*
* automatically generated by org.eclipse.emf.mwe.releng.GenerateTestSuite
*
* @generated
*/
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Tests for org.eclipse.xtext.generator.tests");
suite.addTestSuite(org.eclipse.xtext.actions.AntlrParserTest.class);
suite.addTestSuite(org.eclipse.xtext.actions.PackratParserTest.class);
suite.addTestSuite(org.eclipse.xtext.common.services.DefaultTerminalConverterTest.class);
suite.addTestSuite(org.eclipse.xtext.concurrent.StateAccessTest.class);
suite.addTestSuite(org.eclipse.xtext.EcoreUtil2Test.class);
suite.addTestSuite(org.eclipse.xtext.enumrules.AntlrEnumAndReferenceTest.class);
suite.addTestSuite(org.eclipse.xtext.enumrules.AntlrParserTest.class);
suite.addTestSuite(org.eclipse.xtext.enumrules.GrammarParserTest.class);
suite.addTestSuite(org.eclipse.xtext.enumrules.PackratEnumAndReferenceTest.class);
suite.addTestSuite(org.eclipse.xtext.enumrules.PackratParserTest.class);
suite.addTestSuite(org.eclipse.xtext.enumrules.SerializationTest.class);
suite.addTestSuite(org.eclipse.xtext.generator.grammarAccess.ElementFinderTest.class);
suite.addTestSuite(org.eclipse.xtext.generator.grammarAccess.EmptyPackageAwareGrammarAccessFragmentTest.class);
suite.addTestSuite(org.eclipse.xtext.generator.grammarAccess.FragmentFakingEcoreResourceTest.class);
suite.addTestSuite(org.eclipse.xtext.generator.grammarAccess.ParserTest.class);
suite.addTestSuite(org.eclipse.xtext.generator.ManifestMergerTest.class);
suite.addTestSuite(org.eclipse.xtext.generator.resource.ResourceTest.class);
suite.addTestSuite(org.eclipse.xtext.grammarinheritance.AnotherInheritanceTest.class);
suite.addTestSuite(org.eclipse.xtext.grammarinheritance.Bug265111Test.class);
suite.addTestSuite(org.eclipse.xtext.grammarinheritance.Inheritance2Test.class);
suite.addTestSuite(org.eclipse.xtext.grammarinheritance.InheritanceTest.class);
suite.addTestSuite(org.eclipse.xtext.grammarinheritance.ToEcoreTrafoTest.class);
suite.addTestSuite(org.eclipse.xtext.GrammarUtilGetReferenceTest.class);
suite.addTestSuite(org.eclipse.xtext.GrammarUtilTest.class);
suite.addTestSuite(org.eclipse.xtext.lexer.Bug282355Test.class);
suite.addTestSuite(org.eclipse.xtext.lexer.IngoreCaseTest.class);
suite.addTestSuite(org.eclipse.xtext.lexer.LexerErrorTest.class);
suite.addTestSuite(org.eclipse.xtext.linking.Bug266082Test.class);
suite.addTestSuite(org.eclipse.xtext.linking.Bug287988Test.class);
suite.addTestSuite(org.eclipse.xtext.linking.Bug287988WithEagerLinkingTest.class);
suite.addTestSuite(org.eclipse.xtext.linking.CrossRefTest.class);
suite.addTestSuite(org.eclipse.xtext.linking.lazy.BasicLazyLinkingTest.class);
suite.addTestSuite(org.eclipse.xtext.linking.lazy.Bug281990Test.class);
suite.addTestSuite(org.eclipse.xtext.linking.lazy.Bug289059Test.class);
suite.addTestSuite(org.eclipse.xtext.linking.lazy.LazyLinkerTest.class);
suite.addTestSuite(org.eclipse.xtext.linking.lazy.LazyLinkingResourceTest.class);
suite.addTestSuite(org.eclipse.xtext.linking.lazy.LazyURIEncoderTest.class);
suite.addTestSuite(org.eclipse.xtext.linking.LinkingErrorTest.class);
suite.addTestSuite(org.eclipse.xtext.linking.PartialLinkingTest.class);
suite.addTestSuite(org.eclipse.xtext.linking.SimpleAttributeResolverTest.class);
suite.addTestSuite(org.eclipse.xtext.metamodelreferencing.tests.ExceptionTest.class);
suite.addTestSuite(org.eclipse.xtext.metamodelreferencing.tests.MetamodelRefTest.class);
suite.addTestSuite(org.eclipse.xtext.metamodelreferencing.tests.MultiGenMMTest.class);
suite.addTestSuite(org.eclipse.xtext.MweReaderTest.class);
suite.addTestSuite(org.eclipse.xtext.parseerrorhandling.ParseErrorHandlingTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.antlr.Bug289515Test.class);
suite.addTestSuite(org.eclipse.xtext.parser.antlr.Bug289524ExTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.antlr.Bug289524Test.class);
suite.addTestSuite(org.eclipse.xtext.parser.antlr.LexerProviderTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.antlr.TokenAcceptorTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.AntlrDatatypeRuleTokenTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.assignments.Bug287184Test.class);
suite.addTestSuite(org.eclipse.xtext.parser.assignments.Bug288432Test.class);
suite.addTestSuite(org.eclipse.xtext.parser.assignments.ParserBug281962Test.class);
suite.addTestSuite(org.eclipse.xtext.parser.CrossContainmentTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.datatyperules.GrammarTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.datatyperules.MetamodelTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.datatyperules.MetamodelTransformationErrorTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.datatyperules.MetamodelTransformationTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.datatyperules.PackratParserTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.datatyperules.ParserTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.datatyperules.PartialParserTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.datatyperules.SerializationTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.datatyperules.ValueConverterTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.DefaultEcoreElementFactoryTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.epatch.EpatchComparingTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.keywords.AntlrParserTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.keywords.GrammarAccessTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.keywords.PackratParserTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.OffsetInformationTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.packrat.PackratParserGenUtilTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.packrat.PerformanceTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.PartialParserCrossContainmentMultiTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.PartialParserCrossContainmentSingleTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.PartialParserReplaceTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.PartialParserTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.PartialParsingPerformanceTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.PartialParsingPointerTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.terminalrules.DynamicChannelTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.terminalrules.HiddensTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.terminalrules.InterpreterTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.terminalrules.PackratHiddensTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.terminalrules.PackratParserTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.terminalrules.ParserTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.XtextGrammarComparingTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.XtextParserBugsTest.class);
suite.addTestSuite(org.eclipse.xtext.parser.XtextParserTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.ASTChangeTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.CommentTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.EmptyModelTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.formatter.FormatterTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.formatter.XtextFormatterTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.HiddenTokensTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.impl.ParsetreeUtilLinuxAndMacTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.impl.ParsetreeUtilTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.impl.ParsetreeUtilWindowsTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.InvalidTokenTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.LengthOffsetLineTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.NodeContentAdapterTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.NodeModelTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.NodeTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.NodeUtilTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.ParseTreeUtilTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.reconstr.ComplexReconstrTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.reconstr.HiddenTokensMergerTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.reconstr.SerializationBug269362Test.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.reconstr.SerializationErrorTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.reconstr.SimpleReconstrTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.reconstr.WhitespacePreservingCallbackTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.reconstr.XtextGrammarReconcilationTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.SerializeTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.transientvalues.TransientValuesTest.class);
suite.addTestSuite(org.eclipse.xtext.parsetree.unassignedtext.UnassignedTextTest.class);
suite.addTestSuite(org.eclipse.xtext.reference.CommentOnEofBug_234135_Test.class);
suite.addTestSuite(org.eclipse.xtext.reference.LeafNodeBug_234132_Test.class);
suite.addTestSuite(org.eclipse.xtext.resource.ClassloaderClasspathUriResolverTest.class);
suite.addTestSuite(org.eclipse.xtext.resource.EObjectHandleImplTest.class);
suite.addTestSuite(org.eclipse.xtext.resource.ExternalContentSupportTest.class);
suite.addTestSuite(org.eclipse.xtext.resource.impl.DefaultImportedNamesProviderTest.class);
suite.addTestSuite(org.eclipse.xtext.resource.impl.DefaultReferenceDescriptionTest.class);
suite.addTestSuite(org.eclipse.xtext.resource.impl.DefaultResourceDescriptionDeltaTest.class);
suite.addTestSuite(org.eclipse.xtext.resource.impl.DefaultResourceDescriptionTest.class);
suite.addTestSuite(org.eclipse.xtext.resource.impl.ResourceDescriptionsBasedContainerTest.class);
suite.addTestSuite(org.eclipse.xtext.resource.impl.ResourceSetBasedResourceDescriptionsTest.class);
suite.addTestSuite(org.eclipse.xtext.resource.ResourceSetReferencingResourceSetTest.class);
suite.addTestSuite(org.eclipse.xtext.resource.XtextResourcePerformanceTest.class);
suite.addTestSuite(org.eclipse.xtext.resource.XtextResourceTest.class);
suite.addTestSuite(org.eclipse.xtext.scoping.impl.DeclarativeScopeProviderTest.class);
suite.addTestSuite(org.eclipse.xtext.scoping.impl.QualifiedNameScopeProviderTest.class);
suite.addTestSuite(org.eclipse.xtext.scoping.impl.SimpleNameScopeProviderTest.class);
suite.addTestSuite(org.eclipse.xtext.scoping.ScopesTest.class);
suite.addTestSuite(org.eclipse.xtext.scoping.ScopeTest.class);
suite.addTestSuite(org.eclipse.xtext.service.GenericModuleTest.class);
suite.addTestSuite(org.eclipse.xtext.util.ChainedIteratorTest.class);
suite.addTestSuite(org.eclipse.xtext.util.FilteringIteratorTest.class);
suite.addTestSuite(org.eclipse.xtext.util.LineFilterOutputStreamTest.class);
suite.addTestSuite(org.eclipse.xtext.util.MappingIteratorTest.class);
suite.addTestSuite(org.eclipse.xtext.util.OnChangeEvictingCacheAdapterTest.class);
suite.addTestSuite(org.eclipse.xtext.util.PolymorphicDispatcherTest.class);
suite.addTestSuite(org.eclipse.xtext.util.ReflectionTest.class);
suite.addTestSuite(org.eclipse.xtext.util.SimpleCacheTest.class);
suite.addTestSuite(org.eclipse.xtext.util.StringsTest.class);
suite.addTestSuite(org.eclipse.xtext.util.TailWriterTest.class);
suite.addTestSuite(org.eclipse.xtext.util.TuplesTest.class);
suite.addTestSuite(org.eclipse.xtext.validation.CompositeValidatorWithEObjectValidatorTest.class);
suite.addTestSuite(org.eclipse.xtext.validation.CompositeValidatorWithoutEObjectValidatorTest.class);
suite.addTestSuite(org.eclipse.xtext.validation.ConcurrentValidationTest.class);
suite.addTestSuite(org.eclipse.xtext.validation.DeclarativeValidatorTest.class);
suite.addTestSuite(org.eclipse.xtext.validation.ImportUriValidatorTest.class);
suite.addTestSuite(org.eclipse.xtext.validation.NamesAreUniqueValidationHelperTest.class);
suite.addTestSuite(org.eclipse.xtext.validation.NamesAreUniqueValidatorTest.class);
suite.addTestSuite(org.eclipse.xtext.validation.ResourceValidatorImplTest.class);
suite.addTestSuite(org.eclipse.xtext.validation.ValidatorTestingTest.class);
suite.addTestSuite(org.eclipse.xtext.valueconverter.Bug250313AntlrTest.class);
suite.addTestSuite(org.eclipse.xtext.valueconverter.Bug250313PackratTest.class);
suite.addTestSuite(org.eclipse.xtext.valueconverter.ParserComparingTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.Bug285605Test.class);
suite.addTestSuite(org.eclipse.xtext.xtext.Bug290919Test.class);
suite.addTestSuite(org.eclipse.xtext.xtext.ecoreInference.MultiValueFeatureTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.ecoreInference.UnassignedRuleCallTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.ecoreInference.Xtext2EcoreTransformerTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.ExceptionTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.KeywordInspectorTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.OverriddenValueInspectorTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.parser.packrat.XtextPackratParserTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.ResourceLoadTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.RuleWithoutInstantiationInspectorTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.ValidEntryRuleInspectorTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.XtextGrammarSerializationTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.XtextLinkerTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.XtextScopingTest.class);
suite.addTestSuite(org.eclipse.xtext.xtext.XtextValidationTest.class);
suite.addTestSuite(org.eclipse.xtext.XtextGrammarTest.class);
return suite;
}
}
|
package org.hibernate.beanvalidation.tck.util.shrinkwrap;
import java.util.ArrayList;
import java.util.List;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.webapp30.WebAppDescriptor;
import org.jboss.shrinkwrap.descriptor.api.webcommon30.WebAppVersionType;
/**
* ShrinkWrap {@link org.jboss.shrinkwrap.api.spec.WebArchive} builder for CDI TCK Arquillian test. This builder is intended to provide basic functionality
* covering common TCK needs. Use shrinkwrap API to adapt archive to advanced scenarios.
*
* @author Martin Kouba
* @author Gunnar Morling
*/
public class WebArchiveBuilder extends ArchiveBuilder<WebArchiveBuilder, WebArchive> {
private List<ResourceDescriptor> webInfResources = null;
@Override
public WebArchiveBuilder self() {
return this;
}
@Override
protected WebArchive buildInternal() {
WebArchive webArchive;
if ( getName() == null ) {
webArchive = ShrinkWrap.create( WebArchive.class );
}
else {
webArchive = ShrinkWrap.create( WebArchive.class, getName() );
}
processPackages( webArchive );
processClasses( webArchive );
processResources( webArchive );
processWebInfResources( webArchive );
WebAppDescriptor webAppDescriptor = Descriptors.create( WebAppDescriptor.class )
.version( WebAppVersionType._3_0 );
webArchive.setWebXML( new StringAsset( webAppDescriptor.exportAsString() ) );
return webArchive;
}
@Override
public WebArchiveBuilder withEmptyBeansXml() {
return withWebInfResource( EmptyAsset.INSTANCE, "beans.xml" );
}
private WebArchiveBuilder withWebInfResource(Asset asset, String target) {
if ( this.webInfResources == null ) {
this.webInfResources = new ArrayList<ResourceDescriptor>();
}
this.webInfResources.add( new ResourceDescriptor( asset, target ) );
return self();
}
private void processWebInfResources(WebArchive archive) {
if ( webInfResources == null ) {
return;
}
for ( ResourceDescriptor resource : webInfResources ) {
if ( resource.getSource() != null ) {
if ( resource.getTarget() == null ) {
archive.addAsWebInfResource( resource.getSource() );
}
else {
archive.addAsWebInfResource( resource.getSource(), resource.getTarget() );
}
}
else if ( resource.getAsset() != null ) {
archive.addAsWebInfResource( resource.getAsset(), resource.getTarget() );
}
}
}
}
|
package org.deidentifier.arx.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import org.deidentifier.arx.gui.view.impl.MainWindow;
import org.deidentifier.arx.gui.view.impl.Splash;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
/**
* Main entry point
*
* @author Prasser, Kohlmayer
*/
public class Main {
private static Splash splash = null;
public static void main(final String[] args) {
try {
if (!isOSX()){
splash = new Splash();
splash.setVisible(true);
}
System.setProperty("sun.awt.noerasebackground", "true"); //$NON-NLS-1$ //$NON-NLS-2$
MainWindow main = new MainWindow();
main.addShellListener(new ShellAdapter(){
@Override
public void shellActivated(ShellEvent arg0) {
hideSplash();
}
});
main.show();
} catch (Throwable e){
hideSplash();
JOptionPane.showMessageDialog(null, e.getMessage(), "Unexpected error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
private static void hideSplash() {
new Timer(1000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
if (splash != null) splash.setVisible(false);
}
}).start();
}
private static boolean isOSX() {
String osName = System.getProperty("os.name");
return osName.contains("OS X");
}
}
|
package gamepack.manager;
import gamepack.data.Point;
import gamepack.data.PointMatrix;
import gamepack.data.drawable.Bomb;
import gamepack.data.drawable.Tile;
import gamepack.data.drawable.TileList;
import gamepack.data.drawable.TileMatrix;
import gamepack.utility.Direction;
import java.util.ArrayList;
import java.util.Random;
import org.newdawn.slick.geom.Rectangle;
public class TileListManager
{
private TileMatrix tileMatrix;
private TileMatrix nextTileMatrix;
private final PointMatrix goodPositions;
private final int tileSize;
private final Random rand;
private int score;
//Will compute the goodPositins where Tiles will be
public TileListManager(int tileSize, ArrayList<Rectangle> rectangleList)
{
tileMatrix = new TileMatrix((int) Math.sqrt(rectangleList.size()), tileSize);
nextTileMatrix = new TileMatrix(tileMatrix);
rand = new Random();
this.tileSize = tileSize;
this.score = 0;
this.goodPositions = new PointMatrix(rectangleList);
/*int size = (int) Math.sqrt(rectangleList.size());
ArrayList<Point> pointList = null;
for(int i = 0; i < rectangleList.size(); i++)
{
Rectangle curRect = rectangleList.get(i);
if(i % size == 0)
{
if(i != 0)
this.goodPositions.add(pointList);
pointList = new ArrayList<Point>();
}
pointList.add(new Point((int) curRect.getX(), (int) curRect.getY()));
}
this.goodPositions.add(pointList);
for(int i = 0; i < goodPositions.size(); i++)
System.out.println(goodPositions.get(i));*/
//System.out.println(goodPositions);
}
//receive the tileMatrix with bad coordinates and compute the good positions
public void loadGame(TileList fakeList)
{
}
//refresh the number of deplacement possible for a bomb and maybe ... BOOOOOMM !
public void refreshBomb()
{
boolean isExplosed;
for (int i = 0; i < tileMatrix.getMatrixSize(); i++)
{
for(int j = 0 ; j < tileMatrix.getMatrixSize(); j++)
{
Tile t = this.tileMatrix.get(i, j);
if (t instanceof Bomb)
{
isExplosed = ((Bomb) t).minusRemainingMovement();
if (isExplosed)
{
this.explosion(j , i, ((Bomb) t).getExplosionRadius());
}
}
}
}
}
//Let's BOOOOOOOOM !
public void explosion(int x, int y, int explosionRadius)
{
for (int i = -explosionRadius; i <= explosionRadius; i++) {
for (int j = -explosionRadius; j < -explosionRadius; j++) {
int adjPosX = x + j;
int adjPosY = y + i;
boolean notOut = (0 <= adjPosX && adjPosX < this.tileMatrix.getMatrixSize() && 0 <= adjPosY && adjPosY < this.tileMatrix.getMatrixSize());
if (notOut) {
this.tileMatrix.deleteAt(adjPosX, adjPosY);
}
}
}
}
//Return the TileList of the TileListManager to display it and to save it
public TileMatrix getTileList()
{
return tileMatrix;
}
//Return the TileList of the TileListManager to display it and to save it
public PointMatrix getPointMatrix()
{
return goodPositions;
}
public int getScore() {
return score;
}
//Create new tiles at the right positions
public boolean generateNewTile()
{
boolean isFree;
Point currentGoodPosition;
Tile currentTile;
ArrayList<Point> goodFreePoint = new ArrayList<Point>();
//Construction of a new TileList which contain only free space for new Tile
for (int i = 0; i < goodPositions.size(); i++)
{
for(int k = 0; k < goodPositions.size();k ++)
{
currentGoodPosition = goodPositions.getAt(i,k);
isFree = true;
for (int j = 0; j < tileMatrix.getLinearSize(); j++)
{
currentTile = tileMatrix.getAtLinear(j);
if(currentTile != null)
if (currentGoodPosition.getX() == currentTile.getX() && currentGoodPosition.getY() == currentTile.getY())
{
isFree = false;
}
}
if (isFree)
{ //If any Tile in tileMatrix is equal to the current goodPosition so it's a free tile
goodFreePoint.add(currentGoodPosition);
isFree = true;
}
}
}
//If after traversing all the goodPosition any Tile is free so we return an error
if (goodFreePoint.isEmpty()) {
return false;
}
else
{
//Choose randomly a free space and add the new Tile
int randInt = rand.nextInt(goodFreePoint.size());
//Variable which contain the x position in the matrix
int xNewTile = goodPositions.getPositionsOf(goodFreePoint.get(randInt))[0];
//Variable which contain the y position in the matrix
int yNewTile = goodPositions.getPositionsOf(goodFreePoint.get(randInt))[1];
if (rand.nextInt(20) != 0) {
tileMatrix.setAt(xNewTile, yNewTile, new Bomb(goodFreePoint.get(randInt).getX(), goodFreePoint.get(randInt).getY(), this.getRandomTileValue(),tileSize));
} else {
tileMatrix.setAt(xNewTile, yNewTile, new Tile(goodFreePoint.get(randInt).getX(), goodFreePoint.get(randInt).getY(), this.getRandomTileValue(),tileSize));
}
return true;
}
}
public int getRandomTileValue()
{
int tmp;
switch (rand.nextInt(4)) {
case 0:
tmp = 4;
break;
default:
tmp = 2;
break;
}
return tmp;
}
//Give each tile his direction and his arrived Tile(null if no arrived tile, None if no Direction)
//Then it will set the arrived point (coordinates of the arrivedTile if there is one)
public void initMovement(Direction d)
{
//Initialization of the next matrice to compute on it the next state of the grid
nextTileMatrix = tileMatrix;
//TileMatrix mainMatrix = nextTileMatrix;
Tile curTile, prevTile;
int x_init, y_init, x_end, y_end, x_delta, y_delta;
boolean prevTileFus;
int size = tileMatrix.getMatrixSize();
// Compute how to parse the matrix :
if(d == Direction.Left)
{
x_init = 0;
x_end = size;
y_init = 0;
y_end = size;
x_delta = 1;
y_delta = 1;
}
else if(d == Direction.Right)
{
x_init = size-1;
x_end = 0;
y_init = 0;
y_end = size;
x_delta = -1;
y_delta = 1;
}
else if(d == Direction.Up)
{
x_init = 0;
x_end = size;
y_init =
y_end =
x_delta =
y_delta =
}
else if(d == Direction.Down)
{
x_init =
x_end =
y_init =
y_end =
x_delta =
y_delta =
}
for(int y = y_init;y!=y_end;y++)
{
prevTile = null;
for(int x = x_init;x<x_end;x++)
{
curTile = this.nextTileMatrix.get(x, y);
if(prevTile == null)
{
curTile.setPrev();
curTile.setArrivedTile(null);
curTile.setArrivedPoint(prevTile.getArrivedPoint());
prevTilefus = false;
}
else if(curTile.getValue() == prevTile.getValue() && !prevTilefus)
{
curTile.setMergedPrev(prevTile);
curTile.setArrivedTile(prevTile);
curTile.setArrivedPoint(prevTile.getArrivedPoint());
precTilefus = true;
this.score += curTile.getValue()* 2;
}
else
{
curTile.setPrev();
curTile.setArrivedTile(null);
curTile.setArrivedPoint(new Point(listX.get(listX.indexOf(precTile.getArrivedPoint().getX()) + 1), (int) curTile.getY()));
prevTilefus = false;
collumn++;
}
prevTile = curTile;
}
}
//Computation on the nextMatrix (no sort, add methods to the matrix if necessary, avoid using method with "(useless)" comment above it)
//END
}
//Move each Tile in the right direction and set them at the good position if they passe their good position
//return true if there is movement, false otherwise
public boolean manageMovement(int FPS)
{
//init
boolean trueIfMovement = false; //For the state modification in WindowGame
final float pixelPerSecond = 2000.0f;
float pixelPerFrame = 0; //Speed of the tile
for (int i = 0; i < tileMatrix.getMatrixSize(); i++)
{
for(int j = 0; j < tileMatrix.getMatrixSize(); j++)
{
//current Tile in the list
Tile currentTile = tileMatrix.get(j, i);
if(currentTile != null)
{
Direction currentDirection = currentTile.getDirection();
//if the tile has to move
if (currentDirection != Direction.None)
{
trueIfMovement = true;
//if the tile is not arrived
if (!currentTile.isArrived())
{
//move the tile depending on the FPS
pixelPerFrame = pixelPerSecond/FPS;
if (currentDirection == Direction.Left)
currentTile.move(-pixelPerFrame, 0);
else if (currentDirection == Direction.Right)
currentTile.move(pixelPerFrame, 0);
else if (currentDirection == Direction.Down)
currentTile.move(0, +pixelPerFrame);
else if (currentDirection == Direction.Up)
currentTile.move(0, -pixelPerFrame);
//if the tile has gone too far (because of low framerate etc..)
currentTile.improvePosition();
}
//if the tile is arrived, then its Direction will be set to None
else
currentTile.setDirection(Direction.None);
}
}
}
}
return trueIfMovement;
}
//call the function refreshFusion for each tile
//if refreshFusion return true, delete the current tile from the list (null + remove)
public void manageFusion()
{
for (int i = 0; i < tileMatrix.getMatrixSize(); i++)
{
for(int j = 0 ; j < tileMatrix.getMatrixSize(); j++)
{
Tile t = this.tileMatrix.get(i, j);
if(t != null)
{
if (t.getArrivedTile() != null && t.refreshFusion())
{
this.tileMatrix.setAt(i, j, null);
}
}
}
}
}
public void undo()
{
for (int i = 0; i < tileMatrix.getMatrixSize(); i++)
{
for(int j = 0 ; j < tileMatrix.getMatrixSize(); j++)
{
Tile t = this.tileMatrix.get(i, j);
if(t != null)
{
if(t.getMergedTile() != null)
{
tileMatrix.add(t.getMergedTile());
}
t.undo();
}
}
}
}
}
|
package io.miti.beetle.dbutil;
import io.miti.beetle.model.DbType;
import io.miti.beetle.util.Logger;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public final class ConnManager
{
/** Parameters of the method to add an URL to the System classes. */
private static final Class<?>[] parameters = new Class[]{URL.class};
private static final ConnManager mgr = new ConnManager();
private String url = null;
private String user = null;
private String pw = null;
private Set<String> loadedClasses = new HashSet<String>(10);
private Set<String> history = new java.util.LinkedHashSet<String>(5);
private Connection conn = null;
private ConnManager() {
// loadHistory();
}
public static ConnManager get() {
return mgr;
}
public void init(final String sUrl) {
url = sUrl;
}
public void init(final String sUrl, final String sUser, final String sPass) {
url = sUrl;
user = sUser;
pw = sPass;
if (url != null) {
addToHistory();
}
}
public String getUrl() {
return url;
}
public String getUser() {
return user;
}
public void setUser(final String sUser) {
user = sUser;
}
public void setPassword(final String sPass) {
pw = sPass;
}
public Connection getConn() {
if (conn == null) {
initConnection();
}
return conn;
}
public boolean isValid() {
return (conn != null);
}
public boolean isValid(final int timeout) {
if (conn == null) {
return false;
}
boolean timed = false;
try {
timed = conn.isValid(timeout);
} catch (SQLException e) {
timed = false;
}
return timed;
}
public void close() {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
public boolean isNull() {
return (conn == null);
}
public boolean create() {
close();
initConnection();
return (conn != null);
}
private void addToHistory() {
// Save the new URL
history.add(url);
// Update the file
// writeHistoryFile();
}
// private void writeHistoryFile() {
// if ((history == null) || history.isEmpty()) {
// return;
// final File file = new File(FILENAME);
// if (file.exists() && file.isDirectory()) {
// return;
// if (file.exists()) {
// file.delete();
// List<String> names = new ArrayList<String>(history.size());
// for (String item : history) {
// names.add(item);
// Collections.sort(names);
// try {
// PrintWriter writer = new PrintWriter(file, "UTF-8");
// for (String name : names) {
// writer.println(name);
// writer.close();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
public Iterator<String> getHistory() {
return history.iterator();
}
public boolean hasHistory() {
return (!history.isEmpty());
}
// private void loadHistory() {
// File file = new File(FILENAME);
// if (!file.exists() || file.isDirectory()) {
// return;
// try {
// BufferedReader in = new BufferedReader(new InputStreamReader(
// new FileInputStream(file), StandardCharsets.UTF_8));
// String line = null;
// while ((line = in.readLine()) != null) {
// if (!line.startsWith("
// history.add(line);
// in.close();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
private void initConnection() {
if (conn != null) {
return;
}
try {
final UrlInfo urlInfo = UrlInfo.createFromString(url);
Logger.debug("Connecting to URL " + urlInfo.url);
conn = DriverManager.getConnection(urlInfo.url, user, pw);
if (conn == null) {
System.err.println("Error: The generated connection is null");
} else {
// Connect to a schema
connectToSchema(urlInfo.schema, conn);
}
} catch (SQLException e) {
System.err.println("Exception in connection: " + e.getMessage());
}
}
public static boolean connectToSchema(String schema, final Connection conn) {
if ((schema == null) || schema.trim().isEmpty()) {
return true;
}
Logger.debug("Connecting to schema " + schema);
Statement statement = null;
boolean result = false;
try {
statement = conn.createStatement();
statement.execute("set search_path to '" + schema + "'");
result = true;
} catch (SQLException ex) {
Logger.error(ex);
} finally {
try {
statement.close();
} catch (SQLException e) {
Logger.error(e);
}
}
return result;
}
@Override
public String toString() {
return "URL: " + url + ", User: " + user + ", PW: " + pw;
}
/**
* Add a JAR file to the class path and load the driver class.
*
* @param dbType the type of database
* @return the success flag
*/
public boolean addDriverClass(final DbType dbType) {
if (dbType == null) {
Logger.error("No DB type found for the selected database");
return false;
} else if ((dbType.getJarName() == null) || dbType.getJarName().isEmpty()) {
Logger.error("No JAR file specified for the database type");
return false;
} else if ((dbType.getDriver() == null) || dbType.getDriver().isEmpty()) {
Logger.error("No driver class specified for the database type");
return false;
}
// See if we've already loaded this class
if (loadedClasses.contains(dbType.getDriver())) {
Logger.debug("Skipping the driver class since it's already loaded");
return true;
}
// See if the JAR file exists
final File jar = new File(dbType.getJarName());
if (!jar.exists() || !jar.isFile()) {
Logger.error("The JAR file was not found: " + dbType.getJarName());
return false;
}
// Load the class
boolean result = false;
try {
// Print some debug information
Logger.debug("Adding JAR file to classpath: " + jar.getAbsolutePath());
// Add the JAR file to the classpath
final URL fileUrl = jar.toURI().toURL();
Logger.debug("Loading the JAR URL " + fileUrl.toString());
try {
addURL(fileUrl);
result = true;
} catch (IOException e) {
result = false;
Logger.error(e);
}
// Load the class
if (result) {
try {
Logger.debug("Loading class " + dbType.getDriver());
Class.forName(dbType.getDriver(), true, ClassLoader.getSystemClassLoader());
// If we reach here, the result is true
result = true;
Logger.debug("JAR added and class loaded");
} catch (ClassNotFoundException e) {
result = false;
Logger.error(e);
}
}
// Store the loaded class as being loaded in the classpath
if (result) {
loadedClasses.add(dbType.getDriver());
}
} catch (MalformedURLException mue) {
Logger.error("Malformed URL exception loading class " + dbType.getDriver() + ": " + mue.getMessage());
}
return result;
}
/**
* Add the JAR file's URL to the classpath.
*
* @param u the JAR URL to add
* @throws IOException on error
*/
public static void addURL(final URL u) throws IOException {
final URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
final Class<?> sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysloader,new Object[]{ u });
} catch (Exception e) {
Logger.error(e);
throw new IOException("Error, could not add URL to system classloader");
}
}
}
|
package net.sf.jabref;
import java.util.Hashtable;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import net.sf.jabref.search.SearchExpression;
class SearchManager2 extends SidePaneComponent
implements ActionListener, KeyListener, ItemListener {
GridBagLayout gbl = new GridBagLayout() ;
GridBagConstraints con = new GridBagConstraints() ;
IncrementalSearcher incSearcher;
private JabRefFrame frame;
private JTextField searchField = new JTextField("", 12);
private JLabel lab = //new JLabel(Globals.lang("Search")+":");
new JLabel(new ImageIcon(GUIGlobals.searchIconFile));
private JPopupMenu settings = new JPopupMenu();
private JButton openset = new JButton(Globals.lang("Settings")),
escape = new JButton(Globals.lang("Clear search"));
private JabRefPreferences prefs;
private JCheckBoxMenuItem searchReq, searchOpt, searchGen,
searchAll, caseSensitive, regExpSearch;
private JCheckBox increment, select, reorder;
private ButtonGroup types = new ButtonGroup();
private SearchManager2 ths = this;
private boolean incSearch = false;
private int incSearchPos = -1; // To keep track of where we are in
// an incremental search. -1 means
// that the search is inactive.
public SearchManager2(JabRefFrame frame, JabRefPreferences prefs_,
SidePaneManager manager) {
super(manager);
this.frame = frame;
prefs = prefs_;
incSearcher = new IncrementalSearcher(prefs);
//setBorder(BorderFactory.createEtchedBorder());
searchReq = new JCheckBoxMenuItem
(Globals.lang("Search required fields"),
prefs.getBoolean("searchReq"));
searchOpt = new JCheckBoxMenuItem
(Globals.lang("Search optional fields"),
prefs.getBoolean("searchOpt"));
searchGen = new JCheckBoxMenuItem
(Globals.lang("Search general fields"),
prefs.getBoolean("searchGen"));
searchAll = new JCheckBoxMenuItem
(Globals.lang("Search all fields"),
prefs.getBoolean("searchAll"));
regExpSearch = new JCheckBoxMenuItem
(Globals.lang("Use regular expressions"),
prefs.getBoolean("regExpSearch"));
increment = new JCheckBox(Globals.lang("Incremental"), false);
select = new JCheckBox(Globals.lang("Highlight"), true);
reorder = new JCheckBox(Globals.lang("Float"), false);
// Add an item listener that makes sure we only listen for key events
// when incremental search is turned on.
increment.addItemListener(this);
reorder.addItemListener(this);
// Add the global focus listener, so a menu item can see if this field was focused when
// an action was called.
searchField.addFocusListener(Globals.focusListener);
if (searchAll.isSelected()) {
searchReq.setEnabled(false);
searchOpt.setEnabled(false);
searchGen.setEnabled(false);
}
caseSensitive = new JCheckBoxMenuItem(Globals.lang("Case sensitive"),
prefs.getBoolean("caseSensitiveSearch"));
settings.add(caseSensitive);
settings.addSeparator();
settings.add(searchReq);
settings.add(searchOpt);
settings.add(searchGen);
settings.addSeparator();
settings.add(searchAll);
settings.addSeparator();
settings.add(regExpSearch);
searchField.addActionListener(this);
searchField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
incSearch = false;
incSearchPos = -1; // Reset incremental
// search. This makes the
// incremental search reset
// once the user moves focus to
// somewhere else.
if (increment.isSelected())
searchField.setText("");
}
});
escape.addActionListener(this);
openset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton src = (JButton)e.getSource();
settings.show(src, 0, 0);
}
});
types.add(increment);
types.add(select);
types.add(reorder);
if (prefs.getBoolean("incrementS"))
increment.setSelected(true);
else if (!prefs.getBoolean("selectS"))
reorder.setSelected(true);
setLayout(gbl);
SidePaneHeader header = new SidePaneHeader
("Search", GUIGlobals.searchIconFile, this);
con.gridwidth = GridBagConstraints.REMAINDER;
con.fill = GridBagConstraints.HORIZONTAL;
con.weightx = 1;
con.insets = new Insets(0, 0, 2, 0);
gbl.setConstraints(header, con);
add(header);
con.insets = new Insets(0, 0, 0, 0);
gbl.setConstraints(searchField,con);
add(searchField) ;
gbl.setConstraints(increment, con);
add(increment);
gbl.setConstraints(select, con);
add(select);
gbl.setConstraints(reorder, con);
add(reorder);
//con.gridwidth = 1;
gbl.setConstraints(openset,con);
add(openset);
//JPanel empt = new JPanel();
//con.insets = new Insets(0, 0, 2, 0);
//con.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(escape, con);
add(escape);
searchField.getInputMap().put(prefs.getKey("Repeat incremental search"),
"repeat");
searchField.getActionMap().put("repeat", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (increment.isSelected())
repeatIncremental();
}
});
searchField.getInputMap().put(prefs.getKey("Clear search"), "escape");
searchField.getActionMap().put("escape", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
ths.actionPerformed(new ActionEvent(escape, 0, ""));
}
});
}
protected void updatePrefs() {
prefs.putBoolean("searchReq", searchReq.isSelected());
prefs.putBoolean("searchOpt", searchOpt.isSelected());
prefs.putBoolean("searchGen", searchGen.isSelected());
prefs.putBoolean("searchAll", searchAll.isSelected());
prefs.putBoolean("incrementS", increment.isSelected());
prefs.putBoolean("selectS", select.isSelected());
prefs.putBoolean("caseSensitiveSearch",
caseSensitive.isSelected());
prefs.putBoolean("regExpSearch", regExpSearch.isSelected());
}
public void startIncrementalSearch() {
increment.setSelected(true);
searchField.setText("");
searchField.requestFocus();
}
/**
* Clears and focuses the search field if it is not
* focused. Otherwise, cycles to the next search type.
*/
public void startSearch() {
if (increment.isSelected() && incSearch) {
repeatIncremental();
return;
}
if (!searchField.hasFocus()) {
searchField.setText("");
searchField.requestFocus();
} else {
if (increment.isSelected())
select.setSelected(true);
else if (select.isSelected())
reorder.setSelected(true);
else {
increment.setSelected(true);
}
increment.revalidate();
increment.repaint();
searchField.requestFocus();
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == escape) {
incSearch = false;
if (frame.basePanel() != null)
frame.basePanel().stopShowingSearchResults();
}
else if ((e.getSource() == searchField)
&& !increment.isSelected()
&& (frame.basePanel() != null)) {
updatePrefs(); // Make sure the user's choices are recorded.
// Setup search parameters common to both highlight and float.
Hashtable searchOptions = new Hashtable();
searchOptions.put("option",searchField.getText()) ;
SearchRuleSet searchRules = new SearchRuleSet() ;
SearchRule rule1;
if (prefs.getBoolean("regExpSearch"))
rule1 = new RegExpRule(prefs);
else
rule1 = new SimpleSearchRule(prefs);
try {
rule1 = new SearchExpression(prefs,searchOptions);
} catch (Exception ex) {
// JZ: for testing; this does the new search if the
// search text is in correct syntax, and the regular search otherwise
}
// } catch (PatternSyntaxException ex) {
// System.out.println(ex);
// return;
// } catch (TokenStreamException ex) {
// System.out.println(ex);
// return;
// } catch (RecognitionException ex) {
// System.out.println(ex);
// return;
searchRules.addRule(rule1) ;
if (reorder.isSelected()) {
// Float search.
DatabaseSearch search = new DatabaseSearch
(searchOptions,searchRules, frame.basePanel(),
Globals.SEARCH, true);
search.start() ;
}
else if (select.isSelected()) {
// Highlight search.
DatabaseSearch search = new DatabaseSearch
(searchOptions,searchRules, frame.basePanel(),
Globals.SEARCH, false);
search.start() ;
}
// Afterwards, select all text in the search field.
searchField.select(0,searchField.getText().length()) ;
}
}
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == increment) {
if (increment.isSelected())
searchField.addKeyListener(ths);
else
searchField.removeKeyListener(ths);
} else if (e.getSource() == reorder) {
// If this search type is disabled, remove reordering from
// all databases.
if (!reorder.isSelected()) {
frame.stopShowingSearchResults();
}
}
}
private void repeatIncremental() {
incSearchPos++;
if (frame.basePanel() != null)
goIncremental();
}
/**
* Used for incremental search. Only activated when incremental
* is selected.
*
* The variable incSearchPos keeps track of which entry was last
* checked.
*/
public void keyTyped(KeyEvent e) {
if (e.isControlDown()) {
return;
}
if (frame.basePanel() != null)
goIncremental();
}
private void goIncremental() {
incSearch = true;
SwingUtilities.invokeLater(new Thread() {
public void run() {
String text = searchField.getText();
BasePanel bp = frame.basePanel();
if (incSearchPos >= bp.getDatabase().getEntryCount()) {
frame.output("'"+text+"' : "+Globals.lang
("Incremental search failed. Repeat to search from top.")+".");
incSearchPos = -1;
return;
}
if (searchField.getText().equals("")) return;
if (incSearchPos < 0)
incSearchPos = 0;
BibtexEntry be = bp.getDatabase().getEntryById
(bp.tableModel.getNameFromNumber(incSearchPos));
while (!incSearcher.search(text, be)) {
incSearchPos++;
if (incSearchPos < bp.getDatabase().getEntryCount())
be = bp.getDatabase().getEntryById
(bp.tableModel.getNameFromNumber(incSearchPos));
else {
frame.output("'"+text+"' : "+Globals.lang
("Incremental search failed. Repeat to search from top."));
incSearchPos = -1;
return;
}
}
if (incSearchPos >= 0) {
bp.selectSingleEntry(incSearchPos);
frame.output("'"+text+"' "+Globals.lang
("found")+".");
}
}
});
}
public void componentClosing() {
BasePanel bp = frame.basePanel();
if (bp != null)
bp.stopShowingSearchResults();
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
|
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
package opennlp.common.util;
import gnu.regexp.*;
import java.io.*;
import java.util.*;
public final class PerlHelp {
/**
* Regular expressions.
*/
public static RE alphanumRE, capRE, peqRE, punctRE, wsRE,
hasCap, hasNum, hasHyph, hasAt;
static {
try {
alphanumRE = new RE("^[A-Za-z0-9]+$");
hasCap = new RE(".*[A-Z].*");
hasNum = new RE(".*[0-9].*");
hasHyph = new RE(".*-.*");
hasAt = new RE(".*@.*");
capRE = new RE("^[A-Z]\\S*$");
peqRE = new RE("\\.|!|\\?|\\\"|\\)");
punctRE = new RE("[^a-zA-Z0-9]+");
wsRE = new RE("\\s+");
}
catch (REException e) { System.out.println(e); }
}
public static String[] getParagraphs (String text) {
String[] pars = new String { text };
return pars;
}
public static String[] splitByWhitespace (String s) {
String[] segments = split(s);
return segments;
}
/*
* Calls split(String s, string delim), assuming space (" ") as the
* delimiter.
*
* @param s The string to split.
*/
public static String[] split(String s) { return split(s," "); }
/*
* Splits a string into a string array.
*
* @param delim The delimiter (or separator) to use to split the string.
*/
public static String[] split(String s, String delim) {
StringTokenizer st = new StringTokenizer(s, delim);
String[] toks = new String[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
toks[i] = st.nextToken();
i++;
}
return toks;
}
/*
* Finds the index of the nearest space before a specified index.
*
* @param sb The string buffer which contains the text being examined.
* @param seek The index to begin searching from.
* @return The index which contains the nearest space.
*/
public static int previousSpaceIndex(StringBuffer sb, int seek) {
seek
while (seek > 0) {
if (sb.charAt(seek) == ' ') {
while(seek>0 && sb.charAt(seek-1) == ' ') seek
return seek;
}
seek
}
return 0;
}
/*
* Finds the index of the nearest space after a specified index.
*
* @param sb The string buffer which contains the text being examined.
* @param seek The index to begin searching from.
* @param lastIndex The highest index of the StringBuffer sb.
* @return The index which contains the nearest space.
*/
public static int nextSpaceIndex(StringBuffer sb, int seek, int lastIndex) {
seek++;
char c;
while (seek < lastIndex) {
c = sb.charAt(seek);
if (c == ' ' || c == '\n') {
while(sb.length()>seek+1 && sb.charAt(seek+1) == ' ') seek++;
return seek;
}
seek++;
}
return lastIndex;
}
}
|
package org.apache.lucene.index;
/**
A Term represents a word from text. This is the unit of search. It is
composed of two elements, the text of the word, as a string, and the name of
the field that the text occured in, an interned string.
Note that terms may represent more than words from text fields, but also
things like dates, email addresses, urls, etc. */
public final class Term implements Comparable, java.io.Serializable {
String field;
String text;
/** Constructs a Term with the given field and text. */
public Term(String fld, String txt) {
this(fld, txt, true);
}
Term(String fld, String txt, boolean intern) {
field = intern ? fld.intern() : fld; // field names are interned
text = txt; // unless already known to be
}
/** Returns the field of this term, an interned string. The field indicates
the part of a document which this term came from. */
public final String field() { return field; }
/** Returns the text of this term. In the case of words, this is simply the
text of the word. In the case of dates and other types, this is an
encoding of the object as a string. */
public final String text() { return text; }
/** Compares two terms, returning true iff they have the same
field and text. */
public final boolean equals(Object o) {
if (o == null)
return false;
Term other = (Term)o;
return field == other.field && text.equals(other.text);
}
/** Combines the hashCode() of the field and the text. */
public final int hashCode() {
return field.hashCode() + text.hashCode();
}
public int compareTo(Object other) {
return compareTo((Term)other);
}
/** Compares two terms, returning an integer which is less than zero iff this
term belongs after the argument, equal zero iff this term is equal to the
argument, and greater than zero iff this term belongs after the argument.
The ordering of terms is first by field, then by text.*/
public final int compareTo(Term other) {
if (field == other.field) // fields are interned
return text.compareTo(other.text);
else
return field.compareTo(other.field);
}
/** Resets the field and text of a Term. */
final void set(String fld, String txt) {
field = fld;
text = txt;
}
public final String toString() { return field + ":" + text; }
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, ClassNotFoundException
{
in.defaultReadObject();
field = field.intern();
}
}
|
package org.formic.ant;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Target;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Property;
import org.apache.tools.ant.taskdefs.condition.Os;
import org.formic.Installer;
import org.formic.ant.type.Path;
import org.formic.wizard.WizardBuilder;
/**
* Ant task that initializes the installer.
*
* @author Eric Van Dewoestine (ervandew@yahoo.com)
* @version $Revision$
*/
public class InstallerTask
extends Task
{
private static final String CANCEL_TARGET = "canceled";
private String property;
private String resources;
private String steps;
private List paths = new ArrayList();
private Properties properties = new Properties();
private boolean completed;
/**
* Executes this task.
*/
public void execute ()
throws BuildException
{
Installer.setProject(getProject());
Installer.setResourceBundle(ResourceBundle.getBundle(resources));
WizardBuilder.loadSteps("/org/formic/wizard/steps.properties");
if(steps != null){
WizardBuilder.loadSteps("/" + steps.replace('.', '/') + ".properties");
}
getProperties().setProperty("formic.action", getOwningTarget().getName());
// for unix machines, check if running in console mode.
if(Os.isFamily("unix")){
String console = getProject().getProperty("formic.console");
getProperties().setProperty("formic.console",
console != null ? console : "false");
}
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run () {
// run canceled target if install canceled and target exists.
if(!isCompleted()){
canceled();
}
}
});
completed = Installer.run(getProperties(), paths);
if(property != null && completed){
getProject().setProperty(property, String.valueOf(completed));
}
}
/**
* Determines if the installer completed without being canceled.
*
* @return True if completed, false if canceled or aborted.
*/
private boolean isCompleted ()
{
return completed;
}
/**
* Invoked if the installer is canceled, which in turn executes the 'canceled'
* target of the installer script.
*/
private void canceled ()
{
Target target = (Target)getProject().getTargets().get(CANCEL_TARGET);
if(target != null){
target.execute();
}
}
/**
* Sets the property that will be set upon successful completion of the
* install wizard.
*
* @param property The property name.
*/
public void setProperty (String property)
{
this.property = property;
}
/**
* Sets the resources to use during the installation process.
*
* @param resources The resources.
*/
public void setResources (String resources)
{
this.resources = resources;
}
/**
* Sets the classpath resource containing the mappings for step names to
* step classes.
*
* @param steps The steps.
*/
public void setSteps (String steps)
{
this.steps = steps;
}
/**
* Adds the configured Path instance.
*
* @param _path The path.
*/
public void addConfiguredPath (Path _path)
{
paths.add(_path);
}
/**
* Adds the configured Property instance.
*
* @param _property The property.
*/
public void addConfiguredProperty (Property _property)
{
properties.setProperty(_property.getName(), _property.getValue());
}
/**
* Gets this tasks configured properties.
*
* @return The Properties.
*/
public Properties getProperties ()
{
return properties;
}
}
|
package org.orbeon.oxf.util;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.log4j.Logger;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.pipeline.StaticExternalContext;
import org.orbeon.oxf.pipeline.api.ExternalContext;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.resources.URLFactory;
import org.orbeon.oxf.resources.handler.HTTPURLConnection;
import org.orbeon.oxf.xml.ContentHandlerAdapter;
import org.orbeon.oxf.xml.XMLUtils;
import org.orbeon.oxf.xml.dom4j.LocationData;
import org.orbeon.saxon.om.FastStringBuffer;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NetUtils {
private static Logger logger = LoggerFactory.createLogger(NetUtils.class);
public static final String DYNAMIC_RESOURCES_SESSION_KEY = "orbeon.resources.dynamic.";
// Resources are served by the XForms server. It is not ideal to refer to XForms-related functionality from here.
public static final String DYNAMIC_RESOURCES_PATH = "/xforms-server/dynamic/";
private static final Pattern PATTERN_NO_AMP;
private static final Pattern PATTERN_AMP;
// private static final Pattern PATTERN_AMP_AMP;
public static final String DEFAULT_URL_ENCODING = "utf-8";
private static final SimpleDateFormat dateHeaderFormats[] = {
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US),
new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US),
new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US)
};
private static final TimeZone gmtZone = TimeZone.getTimeZone("GMT");
private static FileItemFactory fileItemFactory;
public static final int REQUEST_SCOPE = 0;
public static final int SESSION_SCOPE = 1;
public static final int APPLICATION_SCOPE = 2;
/**
* Return true if the document was modified since the given date, based on the If-Modified-Since
* header. If the request method was not "GET", or if no valid lastModified value was provided,
* consider the document modified.
*/
public static boolean checkIfModifiedSince(HttpServletRequest request, long lastModified) {
// Do the check only for the GET method
if (!"GET".equals(request.getMethod()) || lastModified <= 0)
return true;
// Check dates
String ifModifiedHeader = request.getHeader("If-Modified-Since");
if (logger.isDebugEnabled())
logger.debug("Found If-Modified-Since header");
if (ifModifiedHeader != null) {
try {
long dateTime = getDateHeader(ifModifiedHeader);
if (lastModified <= (dateTime + 1000)) {
if (logger.isDebugEnabled())
logger.debug("Sending SC_NOT_MODIFIED response");
return false;
}
} catch (Exception e) {// used to be ParseException, but NumberFormatException may be thrown as well
// Ignore
}
}
return true;
}
/**
* Return a request path info that looks like what one would expect. The path starts with a "/", relative to the
* servlet context. If the servlet was included or forwarded to, return the path by which the *current* servlet was
* invoked, NOT the path of the calling servlet.
*
* Request path = servlet path + path info.
*/
public static String getRequestPathInfo(HttpServletRequest request) {
// Get servlet path
String servletPath = (String) request.getAttribute("javax.servlet.include.servlet_path");
if (servletPath == null) {
servletPath = request.getServletPath();
if (servletPath == null)
servletPath = "";
}
// Get path info
String pathInfo = (String) request.getAttribute("javax.servlet.include.path_info");
if (pathInfo == null) {
pathInfo = request.getPathInfo();
if (pathInfo == null)
pathInfo = "";
}
// Concatenate servlet path and path info, avoiding a double slash
String requestPath = servletPath.endsWith("/") && pathInfo.startsWith("/")
? servletPath + pathInfo.substring(1)
: servletPath + pathInfo;
// Add starting slash if missing
if (!requestPath.startsWith("/"))
requestPath = "/" + requestPath;
return requestPath;
}
/**
* Get the last modification date of a URL.
*
* * @return last modified timestamp, null if le 0
*/
public static Long getLastModifiedAsLong(URL url) throws IOException {
final long connectionLastModified = getLastModified(url);
// Zero and negative values often have a special meaning, make sure to normalize here
return connectionLastModified <= 0 ? null : new Long(connectionLastModified);
}
/**
* Get the last modification date of a URL.
*
* * @return last modified timestamp "as is"
*/
public static long getLastModified(URL url) throws IOException {
final URLConnection urlConnection = url.openConnection();
if (urlConnection instanceof HttpURLConnection)
((HttpURLConnection) urlConnection).setRequestMethod("HEAD");
try {
return getLastModified(urlConnection);
} finally {
urlConnection.getInputStream().close();
}
}
/**
* Get the last modification date of an open URLConnection.
*
* This handles the (broken at some point in the Java libraries) case of the file: protocol.
*
* * @return last modified timestamp, null if le 0
*/
public static Long getLastModifiedAsLong(URLConnection urlConnection) {
final long connectionLastModified = getLastModified(urlConnection);
// Zero and negative values often have a special meaning, make sure to normalize here
return connectionLastModified <= 0 ? null : new Long(connectionLastModified);
}
/**
* Get the last modification date of an open URLConnection.
*
* This handles the (broken at some point in the Java libraries) case of the file: protocol.
*
* @return last modified timestamp "as is"
*/
public static long getLastModified(URLConnection urlConnection) {
try {
long lastModified = urlConnection.getLastModified();
if (lastModified == 0 && "file".equals(urlConnection.getURL().getProtocol()))
lastModified = new File(URLDecoder.decode(urlConnection.getURL().getFile(), DEFAULT_URL_ENCODING)).lastModified();
return lastModified;
} catch (UnsupportedEncodingException e) {
// Should not happen as we are using a required encoding
throw new OXFException(e);
}
}
/**
* Check if an URL is relative to another URL.
*/
public static boolean relativeURL(URL url1, URL url2) {
return ((url1.getProtocol() == null && url2.getProtocol() == null) || url1.getProtocol().equals(url2.getProtocol()))
&& ((url1.getAuthority() == null && url2.getAuthority() == null) || url1.getAuthority().equals(url2.getAuthority()))
&& ((url1.getPath() == null && url2.getPath() == null) || url2.getPath().startsWith(url1.getPath()));
}
public static void copyStream(InputStream is, OutputStream os) throws IOException {
int count;
byte[] buffer = new byte[1024];
while ((count = is.read(buffer)) > 0)
os.write(buffer, 0, count);
}
public static void copyStream(Reader reader, Writer writer) throws IOException {
int count;
char[] buffer = new char[1024];
while ((count = reader.read(buffer)) > 0)
writer.write(buffer, 0, count);
}
public static String readStreamAsString(Reader reader) throws IOException {
final StringWriter writer = new StringWriter();
copyStream(reader, writer);
return writer.toString();
}
public static String getContentTypeCharset(String contentType) {
final Map parameters = getContentTypeParameters(contentType);
return (String) ((parameters == null) ? null : parameters.get("charset"));
}
public static Map getContentTypeParameters(String contentType) {
if (contentType == null)
return null;
// Check whether there may be parameters
final int semicolumnIndex = contentType.indexOf(";");
if (semicolumnIndex == -1)
return null;
// Tokenize
final StringTokenizer st = new StringTokenizer(contentType, ";");
if (!st.hasMoreTokens())
return null; // should not happen as there should be at least the content type
st.nextToken();
// No parameters
if (!st.hasMoreTokens())
return null;
// Parse parameters
final Map parameters = new HashMap();
while (st.hasMoreTokens()) {
final String parameter = st.nextToken().trim();
final int equalIndex = parameter.indexOf('=');
if (equalIndex == -1)
continue;
final String name = parameter.substring(0, equalIndex).trim();
final String value = parameter.substring(equalIndex + 1).trim();
parameters.put(name, value);
}
return parameters;
}
public static Map getCharsetHeaderCharsets(String header) {
if (header == null)
return null;
int semicolumnIndex = header.indexOf(";");
final String charsets;
if (semicolumnIndex == -1)
charsets = header.trim();
else
charsets = header.substring(0, semicolumnIndex).trim();
final StringTokenizer st = new StringTokenizer(charsets, ",");
final Map charsetsMap = new HashMap();
while (st.hasMoreTokens()) {
charsetsMap.put(st.nextToken(), "");
}
return charsetsMap;
}
public static String getContentTypeMediaType(String contentType) {
if (contentType == null || contentType.equalsIgnoreCase("content/unknown"))
return null;
int semicolumnIndex = contentType.indexOf(";");
if (semicolumnIndex == -1)
return contentType;
return contentType.substring(0, semicolumnIndex).trim();
}
/**
* Convert an Enumeration of String into an array.
*/
public static String[] stringEnumerationToArray(Enumeration enumeration) {
List values = new ArrayList();
while (enumeration.hasMoreElements())
values.add(enumeration.nextElement());
String[] stringValues = new String[values.size()];
values.toArray(stringValues);
return stringValues;
}
/**
* @param queryString a query string of the form n1=v1&n2=v2&... to decode. May be null.
* @param acceptAmp -> "&" if true, "&" if false
*
* @return a Map of String[] indexed by name, an empty Map if the query string was null
*/
public static Map decodeQueryString(final CharSequence queryString, final boolean acceptAmp) {
final Map ret = new TreeMap();
if (queryString != null) {
final Matcher m = acceptAmp ? PATTERN_AMP.matcher(queryString) : PATTERN_NO_AMP.matcher(queryString);
int mtchEnd = 0;
while (m.find()) {
mtchEnd = m.end();
try {
// Group 0 is the whole match, e.g. a=b, while group 1 is the first group
// denoted ( with parens ) in the expression. Hence we start with group 1.
String nam = m.group(1);
nam = URLDecoder.decode(nam, NetUtils.DEFAULT_URL_ENCODING);
String val = m.group(2);
val = URLDecoder.decode(val, NetUtils.DEFAULT_URL_ENCODING);
NetUtils.addValueToStringArrayMap(ret, nam, val);
} catch (final java.io.UnsupportedEncodingException e) {
// Should not happen as we are using a required encoding
throw new OXFException(e);
}
}
if (queryString.length() != mtchEnd) {
// There was garbage at the end of the query.
throw new OXFException("Malformed URL: " + queryString);
}
}
return ret;
}
/**
* Make sure a query string is made of valid pairs name/value.
*/
public static String normalizeQuery(String query, boolean acceptAmp) {
if (query == null)
return null;
return encodeQueryString(decodeQueryString(query, acceptAmp));
}
/**
* Encode a query string. The input Map contains names indexing String[].
*/
public static String encodeQueryString(Map parameters) {
StringBuffer sb = new StringBuffer();
boolean first = true;
try {
for (Iterator i = parameters.keySet().iterator(); i.hasNext();) {
String name = (String) i.next();
String[] values = (String[]) parameters.get(name);
for (int j = 0; j < values.length; j++) {
if (!first)
sb.append('&');
sb.append(URLEncoder.encode(name, NetUtils.DEFAULT_URL_ENCODING));
sb.append('=');
sb.append(URLEncoder.encode(values[j], NetUtils.DEFAULT_URL_ENCODING));
first = false;
}
}
} catch (UnsupportedEncodingException e) {
// Should not happen as we are using a required encoding
throw new OXFException(e);
}
return sb.toString();
}
public static void addValueToStringArrayMap(Map map, String name, String value) {
String[] currentValue = (String[]) map.get(name);
if (currentValue == null) {
map.put(name, new String[]{value});
} else {
String[] newValue = new String[currentValue.length + 1];
System.arraycopy(currentValue, 0, newValue, 0, currentValue.length);
newValue[currentValue.length] = value;
map.put(name, newValue);
}
}
public static void addValuesToStringArrayMap(Map map, String name, String[] values) {
String[] currentValues = (String[]) map.get(name);
if (currentValues == null) {
map.put(name, values);
} else {
String[] newValues = new String[currentValues.length + values.length];
System.arraycopy(currentValues, 0, newValues, 0, currentValues.length);
System.arraycopy(values, 0, newValues, currentValues.length, values.length);
map.put(name, newValues);
}
}
/**
* Canonicalize a string of the form "a/b/../../c/./d/". The string may start and end with a
* "/". Occurrences of "..." or other similar patterns are ignored. Also, contiguous "/" are
* left as is.
*/
public static String canonicalizePathString(String path) {
StringTokenizer st = new StringTokenizer(path, "/", true);
Stack elements = new Stack();
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (s.equals("..")) {
elements.pop();
} else if (s.equals(".")) {
;// Do nothing
} else {
elements.push(s);
}
}
StringBuffer sb = new StringBuffer();
int count = 0;
for (Iterator i = elements.iterator(); i.hasNext(); count++) {
String s = (String) i.next();
if (count > 0 || path.startsWith("/"))
sb.append("/");
sb.append(s);
}
if (path.endsWith("/"))
sb.append("/");
return sb.toString();
}
/**
* Combine a path info and a parameters map to form a path info with a query string.
*/
public static String pathInfoParametersToPathInfoQueryString(String pathInfo, Map parameters) throws IOException {
StringBuffer redirectURL = new StringBuffer(pathInfo);
if (parameters != null) {
boolean first = true;
for (Iterator i = parameters.keySet().iterator(); i.hasNext();) {
String name = (String) i.next();
String[] values = (String[]) parameters.get(name);
for (int j = 0; j < values.length; j++) {
redirectURL.append(first ? "?" : "&");
redirectURL.append(URLEncoder.encode(name, NetUtils.DEFAULT_URL_ENCODING));
redirectURL.append("=");
redirectURL.append(URLEncoder.encode(values[j], NetUtils.DEFAULT_URL_ENCODING));
first = false;
}
}
}
return redirectURL.toString();
}
/**
* Check whether a URL starts with a protocol.
*
* We consider that a protocol consists only of ASCII letters and must be at least two
* characters long, to avoid confusion with Windows drive letters.
*/
public static boolean urlHasProtocol(String urlString) {
int colonIndex = urlString.indexOf(":");
// No protocol is there is no colon or if there is only one character in the protocol
if (colonIndex == -1 || colonIndex == 1)
return false;
// Check that there is a protocol
boolean allChar = true;
for (int i = 0; i < colonIndex; i++) {
char c = urlString.charAt(i);
if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z')) {
allChar = false;
break;
}
}
return allChar;
}
/**
* Resolve a URI against a base URI. (Be sure to pay attention to the order or parameters.)
*
* @param href URI to resolve
* @param base URI base
* @return resolved URI
*/
public static String resolveURI(String href, String base) {
final String resolvedURIString;
if (base != null) {
final URI baseURI;
try {
baseURI = new URI(base);
} catch (URISyntaxException e) {
throw new OXFException(e);
}
resolvedURIString = baseURI.resolve(href).normalize().toString();// normalize to remove "..", etc.
} else {
resolvedURIString = href;
}
return resolvedURIString;
}
public static String headersToString(HttpServletRequest request) {
final StringBuffer sb = new StringBuffer();
for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
final String name = (String) e.nextElement();
sb.append(name);
sb.append("=");
for (Enumeration f = request.getHeaders(name); f.hasMoreElements();) {
final String value = (String) f.nextElement();
sb.append(value);
if (f.hasMoreElements())
sb.append(",");
}
if (e.hasMoreElements())
sb.append("|");
}
return sb.toString();
}
public static String readURIToLocalURI(String uri) throws URISyntaxException, IOException {
final PipelineContext pipelineContext = StaticExternalContext.getStaticContext().getPipelineContext();
final URLConnection urlConnection = new URI(uri).toURL().openConnection();
InputStream inputStream = null;
try {
inputStream = urlConnection.getInputStream();
return inputStreamToAnyURI(pipelineContext, inputStream, REQUEST_SCOPE);
} finally {
if (inputStream != null) inputStream.close();
}
}
public static byte[] base64StringToByteArray(String base64String) {
return Base64.decode(base64String);
}
/**
* Convert a String in xs:base64Binary to an xs:anyURI.
*
* NOTE: The implementation creates a temporary file. The Pipeline Context is required so
* that the file can be deleted when no longer used.
*/
public static String base64BinaryToAnyURI(PipelineContext pipelineContext, String value, int scope) {
// Convert Base64 to binary first
final byte[] bytes = base64StringToByteArray(value);
return inputStreamToAnyURI(pipelineContext, new ByteArrayInputStream(bytes), scope);
}
/**
* Read an InputStream into a byte array.
*
* @param is InputStream
* @return byte array
*/
public static byte[] inputStreamToByteArray(InputStream is) {
try {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
copyStream(new BufferedInputStream(is), os);
os.close();
return os.toByteArray();
} catch (Exception e) {
throw new OXFException(e);
}
}
/**
* Read a URI into a byte array.
*
* @param uri URI to read
* @return byte array
*/
public static byte[] uriToByteArray(String uri) {
InputStream is = null;
try {
is = new URI(uri).toURL().openStream();
return inputStreamToByteArray(is);
} catch (Exception e) {
throw new OXFException(e);
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
throw new OXFException(e);
}
}
}
/**
* Convert an InputStream to an xs:anyURI.
*
* The implementation creates a temporary file. The PipelineContext is required so that the file can be deleted
* when no longer used.
*/
public static String inputStreamToAnyURI(PipelineContext pipelineContext, InputStream inputStream, int scope) {
// Get FileItem
final FileItem fileItem = prepareFileItem(pipelineContext, scope);
// Write to file
OutputStream os = null;
try {
os = fileItem.getOutputStream();
copyStream(inputStream, os);
} catch (IOException e) {
throw new OXFException(e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
throw new OXFException(e);
}
}
}
// Create file if it doesn't exist (necessary when the file size is 0)
final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation();
try {
storeLocation.createNewFile();
} catch (IOException e) {
throw new OXFException(e);
}
// Return a file URL
return storeLocation.toURI().toString();
}
/**
* Return a FileItem which is going to be automatically destroyed upon destruction of the request, session or
* application.
*/
public static FileItem prepareFileItem(PipelineContext pipelineContext, int scope) {
// We use the commons fileupload utilities to save a file
if (fileItemFactory == null)
fileItemFactory = new DiskFileItemFactory(0, SystemUtils.getTemporaryDirectory());
final FileItem fileItem = fileItemFactory.createItem("dummy", "dummy", false, null);
// Make sure the file is deleted appropriately
if (scope == REQUEST_SCOPE) {
deleteFileOnRequestEnd(pipelineContext, fileItem);
} else if (scope == SESSION_SCOPE) {
deleteFileOnSessionTermination(pipelineContext, fileItem);
} else if (scope == APPLICATION_SCOPE) {
deleteFileOnContextDestroyed(pipelineContext, fileItem);
} else {
throw new OXFException("Invalid context requested: " + scope);
}
// Return FileItem object
return fileItem;
}
/**
* Add listener to fileItem which is going to be automatically destroyed at the end of request
*
* @param pipelineContext PipelineContext
* @param fileItem FileItem
*/
public static void deleteFileOnRequestEnd(PipelineContext pipelineContext, final FileItem fileItem) {
// Make sure the file is deleted at the end of request
pipelineContext.addContextListener(new PipelineContext.ContextListenerAdapter() {
public void contextDestroyed(boolean success) {
deleteFileItem(fileItem, REQUEST_SCOPE);
}
});
}
/**
* Add listener to fileItem which is going to be automatically destroyed on session destruction
*
* @param pipelineContext PipelineContext
* @param fileItem FileItem
*/
public static void deleteFileOnSessionTermination(PipelineContext pipelineContext, final FileItem fileItem) {
// Try to delete the file on exit and on session termination
final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
final ExternalContext.Session session = externalContext.getSession(false);
if (session != null) {
session.addListener(new ExternalContext.Session.SessionListener() {
public void sessionDestroyed() {
deleteFileItem(fileItem, SESSION_SCOPE);
}
});
} else {
logger.debug("No existing session found so cannot register temporary file deletion upon session destruction: " + fileItem.getName());
}
}
/**
* Add listener to fileItem which is going to be automatically destroyed when the servlet is destroyed
*
* @param pipelineContext PipelineContext
* @param fileItem FileItem
*/
public static void deleteFileOnContextDestroyed(PipelineContext pipelineContext, final FileItem fileItem) {
// Try to delete the file on exit and on session termination
final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
ExternalContext.Application application = externalContext.getApplication();
if (application != null) {
application.addListener(new ExternalContext.Application.ApplicationListener() {
public void servletDestroyed() {
deleteFileItem(fileItem, APPLICATION_SCOPE);
}
});
} else {
logger.debug("No application object found so cannot register temporary file deletion upon session destruction: " + fileItem.getName());
}
}
private static void deleteFileItem(FileItem fileItem, int scope) {
if (logger.isDebugEnabled() && fileItem instanceof DiskFileItem) {
final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation();
if (storeLocation != null) {
final String temporaryFileName = storeLocation.getAbsolutePath();
final String scopeString = (scope == REQUEST_SCOPE) ? "request" : (scope == SESSION_SCOPE) ? "session" : "application";
logger.debug("Deleting temporary " + scopeString + "-scoped file: " + temporaryFileName);
}
}
fileItem.delete();
}
/**
* Convert a String in xs:anyURI to an xs:base64Binary.
*
* The URI has to be a URL. It is read entirely
*/
public static String anyURIToBase64Binary(String value) {
InputStream is = null;
try {
// Read from URL and convert to Base64
is = new URL(value).openStream();
final StringBuffer sb = new StringBuffer();
XMLUtils.inputStreamToBase64Characters(is, new ContentHandlerAdapter() {
public void characters(char ch[], int start, int length) {
sb.append(ch, start, length);
}
});
// Return Base64 String
return sb.toString();
} catch (IOException e) {
throw new OXFException(e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new OXFException(e);
}
}
}
}
public static void anyURIToOutputStream(String value, OutputStream outputStream) {
InputStream is = null;
try {
is = new URL(value).openStream();
copyStream(is, outputStream);
} catch (IOException e) {
throw new OXFException(e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new OXFException(e);
}
}
}
}
* Return the charset associated with a text/* Content-Type header. If a charset is present, return it. Otherwise,
* guess depending on whether the mediatype is text/xml or not.
*
* @param contentType Content-Type header value
* @return charset
*/
public static String getTextCharsetFromContentType(String contentType) {
final String charset;
final String connectionCharset = getContentTypeCharset(contentType);
if (connectionCharset != null) {
charset = connectionCharset;
} else {
// RFC 3023: "Conformant with [RFC2046], if a text/xml entity is
// received with the charset parameter omitted, MIME processors and
// XML processors MUST use the default charset value of
// "us-ascii"[ASCII]. In cases where the XML MIME entity is
// transmitted via HTTP, the default charset value is still
// "us-ascii". (Note: There is an inconsistency between this
// specification and HTTP/1.1, which uses ISO-8859-1[ISO8859] as the
// default for a historical reason. Since XML is a new format, a new
// default should be chosen for better I18N. US-ASCII was chosen,
// since it is the intersection of UTF-8 and ISO-8859-1 and since it
// is already used by MIME.)"
if (XMLUtils.isXMLMediatype(contentType))
charset = DEFAULT_TEXT_XML_READING_ENCODING;
else
charset = DEFAULT_HTTP_TEXT_READING_ENCODING;
}
return charset;
}
/**
* Test whether the user agent is Trident.
*
* @param request incoming request
* @return true if Trident is identified
*/
public static boolean isRenderingEngineTrident(ExternalContext.Request request) {
final Object userAgentHeader = request.getHeaderValuesMap().get("user-agent");
if (userAgentHeader == null)
return false;
final String userAgent = ((String[]) userAgentHeader)[0].toLowerCase();
final String lowerCaseUserAgent = userAgent.toLowerCase();
return lowerCaseUserAgent.indexOf("msie") != -1 && lowerCaseUserAgent.indexOf("opera") == -1;
}
/**
* Test whether the user agent is IE 6 or earlier.
*
* @param request incoming request
* @return true if IE 6 or earlier is identified
*/
public static boolean isRenderingEngineIE6OrEarlier(ExternalContext.Request request) {
final Object userAgentHeader = request.getHeaderValuesMap().get("user-agent");
if (userAgentHeader == null)
return false;
final String userAgent = ((String[]) userAgentHeader)[0].toLowerCase();
final int msieIndex = userAgent.indexOf("msie");
final boolean isIE = msieIndex != -1 && userAgent.indexOf("opera") == -1;
if (!isIE)
return false;
final String versionString = userAgent.substring(msieIndex + 4, userAgent.indexOf(';', msieIndex + 5)).trim();
final int dotIndex = versionString.indexOf('.');
final int version;
if (dotIndex == -1) {
version = Integer.parseInt(versionString);
} else {
version = Integer.parseInt(versionString.substring(0, dotIndex));
}
return version <= 6;
}
/**
* Create an absolute URL from an action string and a search string.
*
* @param action absolute URL or absolute path
* @param queryString optional query string to append to the action URL
* @param externalContext current ExternalContext
* @return an absolute URL
*/
public static URL createAbsoluteURL(String action, String queryString, ExternalContext externalContext) {
URL resultURL;
try {
final String actionString;
{
final StringBuffer updatedActionStringBuffer = new StringBuffer(action);
if (queryString != null && queryString.length() > 0) {
if (action.indexOf('?') == -1)
updatedActionStringBuffer.append('?');
else
updatedActionStringBuffer.append('&');
updatedActionStringBuffer.append(queryString);
}
actionString = updatedActionStringBuffer.toString();
}
if (actionString.startsWith("/")) {
// Case of path absolute
final String requestURL = externalContext.getRequest().getRequestURL();
resultURL = URLFactory.createURL(requestURL, actionString);
} else if (urlHasProtocol(actionString)) {
// Case of absolute URL
resultURL = URLFactory.createURL(actionString);
} else {
throw new OXFException("Invalid URL: " + actionString);
}
} catch (MalformedURLException e) {
throw new OXFException("Invalid URL: " + action, e);
}
return resultURL;
}
/**
* Remove the first path element of a path. Return null if there is only one path element
*
* E.g. /foo/bar => /bar?a=b
*
* @param path path to modify
* @return modified path or null
*/
public static String removeFirstPathElement(String path) {
final int secondSlashIndex = path.indexOf('/', 1);
if (secondSlashIndex == -1)
return null;
return path.substring(secondSlashIndex);
}
/**
* Return the first path element of a path. If there is only one path element, return the entire path.
*
* E.g. /foo/bar => /foo
*
* @param path path to analyze
* @return first path element
*/
public static String getFirstPathElement(String path) {
final int secondSlashIndex = path.indexOf('/', 1);
if (secondSlashIndex == -1)
return path;
return path.substring(0, secondSlashIndex);
}
/**
* Perform a connection to the given URL with the given parameters.
*
* This handles:
*
* o PUTting or POSTing a body
* o handling username and password
* o setting HTTP heades
* o forwarding session cookies
* o forwarding specified HTTP headers
* o managing SOAP POST and GET a la XForms 1.1 (should this be here?)
*/
public static ConnectionResult openConnection(ExternalContext externalContext, IndentedLogger indentedLogger,
String httpMethod, final URL connectionURL, String username, String password, String contentType,
byte[] messageBody, Map headerNameValues, String headersToForward) {
// Get the headers to forward if any
final Map headersMap = (externalContext.getRequest() != null) ?
getHeadersMap(externalContext, indentedLogger, username, headerNameValues, headersToForward) : headerNameValues;
// Open the connection
return openConnection(indentedLogger, httpMethod, connectionURL, username, password, contentType, messageBody, headersMap);
}
/**
* Get header names and values to send given:
*
* o the incoming request
* o a list of headers names and values to set
* o authentication information including username
* o a list of headers to forward
*/
public static Map getHeadersMap(ExternalContext externalContext, IndentedLogger indentedLogger, String username,
Map headerNameValues, String headersToForward) {
// Resulting header names and values to set
final LinkedHashMap headersMap = new LinkedHashMap();
// Get header forwarding information
final Map headersToForwardMap = getHeadersToForward(headersToForward);
// Set headers if provided
if (headerNameValues != null && headerNameValues.size() > 0) {
for (Iterator i = headerNameValues.entrySet().iterator(); i.hasNext();) {
final Map.Entry currentEntry = (Map.Entry) i.next();
final String currentHeaderName = (String) currentEntry.getKey();
final String currentHeaderValue = (String) currentEntry.getValue();
// Set header
headersMap.put(currentHeaderName, currentHeaderValue);
// Remove from list of headers to forward below
if (headersToForwardMap != null)
headersToForwardMap.remove(currentHeaderName.toLowerCase());
}
}
// Forward cookies for session handling
final Map requestHeadersMap = externalContext.getRequest().getHeaderMap();
boolean sessionCookieSet = false;
if (username == null) {
// START NEW ALGORITHM
// 1. If there is an incoming JSESSIONID cookie, use it. The reason is that there is not necessarily an
// obvious mapping between "session id" and JSESSIONID cookie value. With Tomcat, this works, but with e.g.
// Websphere, you get session id="foobar" and JSESSIONID=0000foobar:-1. So we must first try to get the
// incoming JSESSIONID. To do this, we get the cookie, then serialize it as a header.
// TODO: ExternalContext must provide direct access to cookies
final Object nativeRequest = externalContext.getNativeRequest();
if (nativeRequest instanceof HttpServletRequest) {
final HttpServletRequest httpServletRequest = (HttpServletRequest) nativeRequest;
final Cookie[] cookies = httpServletRequest.getCookies();
StringBuffer sb = new StringBuffer();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
final Cookie cookie = cookies[i];
// This is the standard JSESSIONID cookie
final boolean isJsessionId = cookie.getName().equals("JSESSIONID");
// Remember if we've seen JSESSIONID
sessionCookieSet |= isJsessionId;
// Forward JSESSIONID and JSESSIONIDSSO for JBoss
if (isJsessionId || cookie.getName().equals("JSESSIONIDSSO")) {
// Multiple cookies in the header, separated with ";"
if (sb.length() > 0)
sb.append("; ");
sb.append(cookie.getName());
sb.append('=');
sb.append(cookie.getValue());
}
}
if (sb.length() > 0) {
// One or more cookies were set
final String cookieString = sb.toString();
indentedLogger.logDebug("connection", "forwarding cookies", new String[] { "cookie", cookieString });
headersMap.put("Cookie", cookieString);
// CookieTools.getCookieHeaderValue(cookie, sb);
}
}
}
// 2. If there is no incoming JSESSIONID cookie, try to make our own cookie. This may fail with e.g.
// Websphere.
if (!sessionCookieSet) {
final ExternalContext.Session session = externalContext.getSession(false);
if (session != null) {
// This will work with Tomcat, but may not work with other app servers
headersMap.put("Cookie", "JSESSIONID=" + session.getId());
if (indentedLogger.isDebugEnabled()) {
String incomingSessionHeader = null;
final String[] cookieHeaders = (String[]) externalContext.getRequest( ).getHeaderValuesMap().get("cookie");
if (cookieHeaders != null) {
for (int i = 0; i < cookieHeaders.length; i++) {
final String cookie = cookieHeaders[i];
if (cookie.indexOf("JSESSIONID") != -1) {
incomingSessionHeader = cookie;
}
}
}
String incomingSessionCookie = null;
if (externalContext.getNativeRequest() instanceof HttpServletRequest) {
final Cookie[] cookies = ((HttpServletRequest) externalContext.getNativeRequest()).getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
final Cookie cookie = cookies[i];
if (cookie.getName().equals("JSESSIONID")) {
incomingSessionCookie = cookie.getValue();
}
}
}
}
indentedLogger.logDebug("connection", "setting cookie",
new String[] {
"new session", Boolean.toString(session.isNew()),
"session id", session.getId(),
"requested session id", externalContext.getRequest().getRequestedSessionId(),
"incoming JSESSIONID cookie", incomingSessionCookie,
"incoming JSESSIONID header", incomingSessionHeader
});
}
}
}
// END NEW ALGORITHM
}
// Forward headers if needed
// NOTE: Forwarding the "Cookie" header may yield unpredictable results because of the above work done w/ JSESSIONID
if (headersToForwardMap != null) {
for (Iterator i = headersToForwardMap.entrySet().iterator(); i.hasNext();) {
final Map.Entry currentEntry = (Map.Entry) i.next();
final String currentHeaderName = (String) currentEntry.getValue();
final String currentHeaderNameLowercase = (String) currentEntry.getKey();
// Get incoming header value (Map contains values in lowercase!)
final String currentIncomingHeaderValue = (String) requestHeadersMap.get(currentHeaderNameLowercase);
// Forward header if present
if (currentIncomingHeaderValue != null) {
final boolean isAuthorizationHeader = currentHeaderNameLowercase.equals("authorization");
if (!isAuthorizationHeader || isAuthorizationHeader && username == null) {
// Only forward Authorization header if there is no username provided
indentedLogger.logDebug("connection", "forwarding header",
new String[] { "name", currentHeaderName, "value", currentIncomingHeaderValue});
headersMap.put(currentHeaderName, currentIncomingHeaderValue);
} else {
// Just log this information
indentedLogger.logDebug("connection",
"not forwarding Authorization header because username is present");
}
}
}
}
return headersMap;
}
public static ConnectionResult openConnection(IndentedLogger indentedLogger,
String httpMethod, final URL connectionURL, String username, String password,
String contentType, byte[] messageBody, Map headersMap) {
// Perform connection
final String scheme = connectionURL.getProtocol();
if (scheme.equals("http") || scheme.equals("https") || (httpMethod.equals("GET") && (scheme.equals("file") || scheme.equals("oxf")))) {
// http MUST be supported
// https SHOULD be supported
// file SHOULD be supported
try {
if (indentedLogger.isDebugEnabled()) {
final URI connectionURI;
try {
String userInfo = connectionURL.getUserInfo();
if (userInfo != null) {
final int colonIndex = userInfo.indexOf(':');
if (colonIndex != -1)
userInfo = userInfo.substring(0, colonIndex + 1) + "xxxxxxxx";// hide password in logs
}
connectionURI = new URI(connectionURL.getProtocol(), userInfo, connectionURL.getHost(),
connectionURL.getPort(), connectionURL.getPath(), connectionURL.getQuery(), connectionURL.getRef());
} catch (URISyntaxException e) {
throw new OXFException(e);
}
indentedLogger.logDebug("connection", "opening URL connection",
new String[] { "URL", connectionURI.toString() });
}
final URLConnection urlConnection = connectionURL.openConnection();
final HTTPURLConnection httpURLConnection = (urlConnection instanceof HTTPURLConnection) ? (HTTPURLConnection) urlConnection : null;
// Whether a message body must be sent
final boolean hasRequestBody = httpMethod.equals("POST") || httpMethod.equals("PUT");
// Case of empty body
if (messageBody == null)
messageBody = new byte[0];
urlConnection.setDoInput(true);
urlConnection.setDoOutput(hasRequestBody);
if (httpURLConnection != null) {
httpURLConnection.setRequestMethod(httpMethod);
if (username != null) {
httpURLConnection.setUsername(username);
if (password != null)
httpURLConnection.setPassword(password);
}
}
final String contentTypeMediaType = getContentTypeMediaType(contentType);
if (hasRequestBody) {
if (httpMethod.equals("POST") && "application/soap+xml".equals(contentTypeMediaType)) {
// SOAP POST
indentedLogger.logDebug("connection", "found SOAP POST");
final Map parameters = getContentTypeParameters(contentType);
final FastStringBuffer sb = new FastStringBuffer("text/xml");
// Extract charset parameter if present
// TODO: We have the body as bytes already, using the xforms:submission/@encoding attribute, so this is not right.
if (parameters != null) {
final String charsetParameter = (String) parameters.get("charset");
if (charsetParameter != null) {
// Append charset parameter
sb.append("; ");
sb.append(charsetParameter);
}
}
// Set new content type
urlConnection.setRequestProperty("Content-Type", sb.toString());
// Extract action parameter if present
if (parameters != null) {
final String actionParameter = (String) parameters.get("action");
if (actionParameter != null) {
// Set SOAPAction header
urlConnection.setRequestProperty("SOAPAction", actionParameter);
indentedLogger.logDebug("connection", "setting header",
new String[] { "SOAPAction", actionParameter });
}
}
} else {
urlConnection.setRequestProperty("Content-Type", (contentType != null) ? contentType : "application/xml");
}
} else {
if (httpMethod.equals("GET") && "application/soap+xml".equals(contentTypeMediaType)) {
// SOAP GET
indentedLogger.logDebug("connection", "found SOAP GET");
final Map parameters = getContentTypeParameters(contentType);
final FastStringBuffer sb = new FastStringBuffer("application/soap+xml");
// Extract charset parameter if present
if (parameters != null) {
final String charsetParameter = (String) parameters.get("charset");
if (charsetParameter != null) {
// Append charset parameter
sb.append("; ");
sb.append(charsetParameter);
}
}
// Set Accept header with optional charset
urlConnection.setRequestProperty("Accept", sb.toString());
}
}
// Set headers if provided
if (headersMap != null && headersMap.size() > 0) {
for (Iterator i = headersMap.entrySet().iterator(); i.hasNext();) {
final Map.Entry currentEntry = (Map.Entry) i.next();
final String currentHeaderName = (String) currentEntry.getKey();
final String currentHeaderValue = (String) currentEntry.getValue();
// Set header
urlConnection.setRequestProperty(currentHeaderName, currentHeaderValue);
}
}
// Write request body if needed
if (hasRequestBody) {
// Log message mody for debugging purposes
if (indentedLogger.isDebugEnabled())
logRequestBody(indentedLogger, contentType, messageBody);
// Set request body on connection
httpURLConnection.setRequestBody(messageBody);
}
urlConnection.connect();
// Create result
final ConnectionResult connectionResult = new ConnectionResult(connectionURL.toExternalForm()) {
public void close() {
if (getResponseInputStream() != null) {
try {
getResponseInputStream().close();
} catch (IOException e) {
throw new OXFException("Exception while closing input stream for action: " + connectionURL);
}
}
if (httpURLConnection != null)
httpURLConnection.disconnect();
}
};
// Get response information that needs to be forwarded
connectionResult.statusCode = (httpURLConnection != null) ? httpURLConnection.getResponseCode() : 200;
final String responseContentType = urlConnection.getContentType();
connectionResult.setResponseContentType(responseContentType != null ? responseContentType : "application/xml");
connectionResult.responseHeaders = urlConnection.getHeaderFields();
connectionResult.setLastModified(NetUtils.getLastModifiedAsLong(urlConnection));
connectionResult.setResponseInputStream(urlConnection.getInputStream());
return connectionResult;
} catch (IOException e) {
throw new ValidationException(e, new LocationData(connectionURL.toExternalForm(), -1, -1));
}
} else if (!httpMethod.equals("GET") && (scheme.equals("file") || scheme.equals("oxf"))) {
// TODO: implement writing to file: and oxf:
// SHOULD be supported (should probably support oxf: as well)
throw new OXFException("submission URL scheme not yet implemented: " + scheme);
} else if (scheme.equals("mailto")) {
// TODO: implement sending mail
// MAY be supported
throw new OXFException("submission URL scheme not yet implemented: " + scheme);
} else {
throw new OXFException("submission URL scheme not supported: " + scheme);
}
}
/**
* Get user-specified list of headers to forward.
*
* @param headersToForward space-separated list of headers to forward
* @return Map<String, String> lowercase header name to user-specified header name or null if null String passed
*/
public static Map getHeadersToForward(String headersToForward) {
if (headersToForward == null)
return null;
final Map result = new HashMap();
for (final StringTokenizer st = new StringTokenizer(headersToForward, ", "); st.hasMoreTokens();) {
final String currentHeaderName = st.nextToken().trim();
final String currentHeaderNameLowercase = currentHeaderName.toLowerCase();
result.put(currentHeaderNameLowercase, currentHeaderName);
}
return result;
}
public static void logRequestBody(IndentedLogger indentedLogger, String mediatype, byte[] messageBody) throws UnsupportedEncodingException {
if (XMLUtils.isXMLMediatype(mediatype) || XMLUtils.isTextContentType(mediatype) || (mediatype != null && mediatype.equals("application/x-www-form-urlencoded"))) {
indentedLogger.logDebug("submission", "setting request body",
new String[] { "mediatype", mediatype, "body", new String(messageBody, "UTF-8")});
} else {
indentedLogger.logDebug("submission", "setting binary request body", new String[] { "mediatype", mediatype });
}
}
/**
* Transform an URI accessible from the server into a URI accessible from the client. The mapping expires with the
* session.
*
* @param pipelineContext PipelineContext to obtain session
* @param uri server URI to transform
* @param contentType type of the content referred to by the URI, or null if unknown
* @param lastModified last modification timestamp
* @return client URI
*/
public static String proxyURI(PipelineContext pipelineContext, String uri, String filename, String contentType, long lastModified) {
// Create a digest, so that for a given URI we always get the same key
final String digest = SecureUtils.digestString(uri, "MD5", "hex");
// Get session
final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
final ExternalContext.Session session = externalContext.getSession(true);// NOTE: We force session creation here. Should we? What's the alternative?
if (session != null) {
// Store mapping into session
session.getAttributesMap(ExternalContext.Session.APPLICATION_SCOPE).put(DYNAMIC_RESOURCES_SESSION_KEY + digest,
new DynamicResource(uri, filename, contentType, -1, lastModified));
}
// Rewrite new URI to absolute path without the context
return externalContext.getResponse().rewriteResourceURL(DYNAMIC_RESOURCES_PATH + digest,
ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_NO_CONTEXT);
}
public static class DynamicResource {
private String uri;
private String filename;
private String contentType;
private long size;
private long lastModified;
public DynamicResource(String uri, String filename, String contentType, long size, long lastModified) {
this.uri = uri;
this.filename = filename;
this.contentType = contentType;
this.size = size;
this.lastModified = lastModified;
}
public String getURI() {
return uri;
}
public String getFilename() {
return filename;
}
public String getContentType() {
return contentType;
}
public long getSize() {
return size;
}
public long getLastModified() {
return lastModified;
}
}
}
|
package org.jaxen;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.jaxen.dom.DOMXPath;
import org.jaxen.dom.NamespaceNode;
import org.w3c.dom.Attr;
import junit.framework.TestCase;
/**
* <p>
* Tests for org.jaxen.BaseXPath.
* </p>
*
* @author Elliotte Rusty Harold
* @version 1.1b4
*
*/
public class BaseXPathTest extends TestCase {
private org.w3c.dom.Document doc;
public BaseXPathTest(String name) {
super(name);
}
protected void setUp() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
doc = factory.newDocumentBuilder().newDocument();
}
public void testSelectSingleNodeForContext() throws JaxenException {
BaseXPath xpath = new BaseXPath("1 + 2");
String stringValue = xpath.stringValueOf(xpath);
assertEquals("3", stringValue);
Number numberValue = xpath.numberValueOf(xpath);
assertEquals(3, numberValue.doubleValue(), 0.00001);
}
public void testEvaluateString() throws JaxenException {
org.w3c.dom.Element a = doc.createElementNS("", "a");
org.w3c.dom.Element b = doc.createElementNS("", "b");
doc.appendChild(a);
org.w3c.dom.Element x1 = doc.createElementNS("", "x");
x1.appendChild(doc.createTextNode("1"));
a.appendChild(x1);
a.appendChild(b);
org.w3c.dom.Element x2 = doc.createElementNS("", "x");
org.w3c.dom.Element x3 = doc.createElementNS("", "x");
org.w3c.dom.Element x4 = doc.createElementNS("", "x");
a.appendChild(x4);
b.appendChild(x2);
b.appendChild(x3);
x2.appendChild(doc.createTextNode("2"));
x3.appendChild(doc.createTextNode("3"));
x4.appendChild(doc.createTextNode("4"));
List result = xpath.selectNodes(doc);
assertEquals(4, result.size());
assertEquals(x1, result.get(0));
assertEquals(x2, result.get(1));
assertEquals(x3, result.get(2));
assertEquals(x4, result.get(3));
}
// test case for JAXEN-55
public void testDescendantAxis() throws JaxenException {
BaseXPath xpath = new DOMXPath("/descendant::x");
org.w3c.dom.Element a = doc.createElementNS("", "a");
org.w3c.dom.Element b = doc.createElementNS("", "b");
doc.appendChild(a);
org.w3c.dom.Element x1 = doc.createElementNS("", "x");
x1.appendChild(doc.createTextNode("1"));
a.appendChild(x1);
a.appendChild(b);
org.w3c.dom.Element x2 = doc.createElementNS("", "x");
org.w3c.dom.Element x3 = doc.createElementNS("", "x");
org.w3c.dom.Element x4 = doc.createElementNS("", "x");
a.appendChild(x4);
b.appendChild(x2);
b.appendChild(x3);
x2.appendChild(doc.createTextNode("2"));
x3.appendChild(doc.createTextNode("3"));
x4.appendChild(doc.createTextNode("4"));
List result = xpath.selectNodes(doc);
assertEquals(4, result.size());
assertEquals(x1, result.get(0));
assertEquals(x2, result.get(1));
assertEquals(x3, result.get(2));
assertEquals(x4, result.get(3));
}
public void testDescendantAxisWithAttributes() throws JaxenException {
BaseXPath xpath = new DOMXPath("/descendant::x/@*");
org.w3c.dom.Element a = doc.createElementNS("", "a");
org.w3c.dom.Element b = doc.createElementNS("", "b");
doc.appendChild(a);
org.w3c.dom.Element x1 = doc.createElementNS("", "x");
a.appendChild(x1);
a.appendChild(b);
org.w3c.dom.Element x2 = doc.createElementNS("", "x");
org.w3c.dom.Element x3 = doc.createElementNS("", "x");
org.w3c.dom.Element x4 = doc.createElementNS("", "x");
a.appendChild(x4);
b.appendChild(x2);
b.appendChild(x3);
Attr a1 = doc.createAttribute("name");
a1.setNodeValue("1");
x1.setAttributeNode(a1);
Attr a2 = doc.createAttribute("name");
a2.setNodeValue("2");
x2.setAttributeNode(a2);
Attr a3 = doc.createAttribute("name");
a3.setNodeValue("3");
x3.setAttributeNode(a3);
Attr a4 = doc.createAttribute("name");
a4.setNodeValue("4");
x4.setAttributeNode(a4);
List result = xpath.selectNodes(doc);
assertEquals(4, result.size());
assertEquals(a1, result.get(0));
assertEquals(a2, result.get(1));
assertEquals(a3, result.get(2));
assertEquals(a4, result.get(3));
}
public void testDescendantAxisWithNamespaceNodes() throws JaxenException {
BaseXPath xpath = new DOMXPath("/descendant::x/namespace::node()");
org.w3c.dom.Element a = doc.createElementNS("", "a");
org.w3c.dom.Element b = doc.createElementNS("", "b");
doc.appendChild(a);
org.w3c.dom.Element x1 = doc.createElementNS("", "x");
a.appendChild(x1);
a.appendChild(b);
org.w3c.dom.Element x2 = doc.createElementNS("", "x");
org.w3c.dom.Element x3 = doc.createElementNS("", "x");
org.w3c.dom.Element x4 = doc.createElementNS("", "x");
a.appendChild(x4);
b.appendChild(x2);
b.appendChild(x3);
Attr a1 = doc.createAttributeNS("http:
a1.setNodeValue("http:
x1.setAttributeNode(a1);
Attr a2 = doc.createAttributeNS("http:
a2.setNodeValue("http:
x2.setAttributeNode(a2);
Attr a3 = doc.createAttributeNS("http:
a3.setNodeValue("http:
x3.setAttributeNode(a3);
Attr a4 = doc.createAttributeNS("http:
a4.setNodeValue("http:
x4.setAttributeNode(a4);
List result = xpath.selectNodes(doc);
assertEquals(8, result.size());
Iterator iterator = result.iterator();
StringBuffer sb = new StringBuffer(4);
while (iterator.hasNext()) {
NamespaceNode ns = (NamespaceNode) iterator.next();
if (ns.getNodeValue().equals("http:
String name = ns.getNodeName();
sb.append(name);
}
}
assertEquals("abcd", sb.toString());
}
public void testMultipleAttributesOnElement() throws JaxenException {
BaseXPath xpath = new DOMXPath("/descendant::x/@*");
org.w3c.dom.Element a = doc.createElementNS("", "a");
org.w3c.dom.Element b = doc.createElementNS("", "b");
doc.appendChild(a);
org.w3c.dom.Element x1 = doc.createElementNS("", "x");
a.appendChild(x1);
a.appendChild(b);
Attr a1 = doc.createAttribute("name1");
a1.setNodeValue("1");
x1.setAttributeNode(a1);
Attr a2 = doc.createAttribute("name2");
a2.setNodeValue("2");
x1.setAttributeNode(a2);
Attr a3 = doc.createAttribute("name3");
a3.setNodeValue("3");
x1.setAttributeNode(a3);
Attr a4 = doc.createAttribute("name4");
a4.setNodeValue("4");
x1.setAttributeNode(a4);
List result = xpath.selectNodes(doc);
assertEquals(4, result.size());
assertTrue(result.contains(a1));
assertTrue(result.contains(a2));
assertTrue(result.contains(a3));
assertTrue(result.contains(a4));
}
public void testXMLNamespaceAttributeOrderOnAncestorAxis()
throws IOException, JaxenException {
org.w3c.dom.Element superroot = doc.createElement("superroot");
doc.appendChild(superroot);
org.w3c.dom.Element root = doc.createElement("root");
superroot.appendChild(root);
org.w3c.dom.Attr p0 = doc.createAttributeNS("http:
p0.setValue("p0");
superroot.setAttributeNodeNS(p0);
org.w3c.dom.Attr p1 = doc.createAttributeNS("http:
p1.setValue("p1");
root.setAttributeNodeNS(p1);
org.w3c.dom.Element child = doc.createElement("child312");
root.appendChild(child);
BaseXPath xpath = new DOMXPath("ancestor::*/@xml:*");
List result = xpath.selectNodes(child);
assertEquals(2, result.size());
assertEquals(p0, result.get(0));
assertEquals(p1, result.get(1));
}
public void testDescendantAxisWithAttributesAndChildren() throws JaxenException {
BaseXPath xpath = new DOMXPath("/descendant::x/@* | /descendant::x");
org.w3c.dom.Element a = doc.createElementNS("", "a");
org.w3c.dom.Element b = doc.createElementNS("", "b");
doc.appendChild(a);
org.w3c.dom.Element x1 = doc.createElementNS("", "x");
a.appendChild(x1);
a.appendChild(b);
org.w3c.dom.Element x2 = doc.createElementNS("", "x");
org.w3c.dom.Element x3 = doc.createElementNS("", "x");
org.w3c.dom.Element x4 = doc.createElementNS("", "x");
a.appendChild(x4);
b.appendChild(x2);
b.appendChild(x3);
Attr a1 = doc.createAttribute("name");
a1.setNodeValue("1");
x1.setAttributeNode(a1);
Attr a2 = doc.createAttribute("name");
a2.setNodeValue("2");
x2.setAttributeNode(a2);
Attr a3 = doc.createAttribute("name");
a3.setNodeValue("3");
x3.setAttributeNode(a3);
Attr a4 = doc.createAttribute("name");
a4.setNodeValue("4");
x4.setAttributeNode(a4);
List result = xpath.selectNodes(doc);
assertEquals(8, result.size());
assertEquals(x1, result.get(0));
assertEquals(a1, result.get(1));
assertEquals(x2, result.get(2));
assertEquals(a2, result.get(3));
assertEquals(x3, result.get(4));
assertEquals(a3, result.get(5));
assertEquals(x4, result.get(6));
assertEquals(a4, result.get(7));
}
public void testAncestorAxisWithAttributes() throws JaxenException {
BaseXPath xpath = new DOMXPath("ancestor::*/@*");
org.w3c.dom.Element a = doc.createElementNS("", "a");
org.w3c.dom.Element b = doc.createElementNS("", "b");
doc.appendChild(a);
a.appendChild(b);
org.w3c.dom.Element x3 = doc.createElementNS("", "x");
b.appendChild(x3);
Attr a1 = doc.createAttribute("name");
a1.setNodeValue("1");
a.setAttributeNode(a1);
Attr a2 = doc.createAttribute("name");
a2.setNodeValue("2");
b.setAttributeNode(a2);
Attr a3 = doc.createAttribute("name");
x3.setNodeValue("3");
x3.setAttributeNode(a3);
List result = xpath.selectNodes(x3);
assertEquals(2, result.size());
assertEquals(a1, result.get(0));
assertEquals(a2, result.get(1));
}
// test for Jaxen-83
public void testPrincipalNodeTypeOfSelfAxisIsElement() throws JaxenException {
BaseXPath xpath = new DOMXPath("child/@*[self::test]");
org.w3c.dom.Element a = doc.createElementNS("", "child");
org.w3c.dom.Attr test = doc.createAttributeNS("", "test");
test.setValue("value");
a.setAttributeNode(test);
doc.appendChild(a);
List result = xpath.selectNodes(doc);
assertEquals(0, result.size());
}
// test to make sure Jaxen-83 fix doesn't go too far
public void testSelfAxisWithNodeTestCanReturnNonPrincipalNodeType() throws JaxenException {
BaseXPath xpath = new DOMXPath("child/@*[self::node()]");
org.w3c.dom.Element a = doc.createElementNS("", "child");
org.w3c.dom.Attr test = doc.createAttributeNS("", "test");
test.setValue("value");
a.setAttributeNode(test);
doc.appendChild(a);
List result = xpath.selectNodes(doc);
assertEquals(1, result.size());
}
// another Jaxen-55 test to try to pin down exactly what does
// and doesn't work
public void testDescendantOrSelfAxis() throws JaxenException {
BaseXPath xpath = new DOMXPath("/descendant-or-self::x");
org.w3c.dom.Element a = doc.createElementNS("", "a");
org.w3c.dom.Element b = doc.createElementNS("", "b");
doc.appendChild(a);
org.w3c.dom.Element x1 = doc.createElementNS("", "x");
x1.appendChild(doc.createTextNode("1"));
a.appendChild(x1);
a.appendChild(b);
org.w3c.dom.Element x2 = doc.createElementNS("", "x");
org.w3c.dom.Element x3 = doc.createElementNS("", "x");
org.w3c.dom.Element x4 = doc.createElementNS("", "x");
a.appendChild(x4);
b.appendChild(x2);
b.appendChild(x3);
x2.appendChild(doc.createTextNode("2"));
x3.appendChild(doc.createTextNode("3"));
x4.appendChild(doc.createTextNode("4"));
List result = xpath.selectNodes(doc);
assertEquals(4, result.size());
assertEquals(x1, result.get(0));
assertEquals(x2, result.get(1));
assertEquals(x3, result.get(2));
assertEquals(x4, result.get(3));
}
public void testDuplicateNodes() throws JaxenException {
|
package inprotk.carchase2;
import inprotk.carchase2.Configuration.CarState;
import inprotk.carchase2.World.Street;
import inprotk.carchase2.World.WorldPoint;
import java.util.LinkedList;
import processing.core.PApplet;
import processing.core.PImage;
import processing.core.PVector;
public class CarChaseViewer extends PApplet {
private static final long serialVersionUID = 1L;
private static final float CAR_SCALE = 1f / 4.3f;
private static final int CURVE_WIDTH = 50;
private LinkedList<Segment> segments;
private PImage map;
private PImage car;
private WorldPoint start;
private WorldPoint end;
private Street previousStreet;
private Street currentStreet;
private int speed;
private int prevSpeed;
private int direction;
private int previousDirection;
private float carAngle;
private PVector carPosition;
private int startMillis;
private int duration;
private boolean animating;
private float previousTimelinePosition;
private Object objectToNotifyOnSetup;
public int sketchWidth() {
return 1024;
}
public int sketchHeight() {
return 768;
}
public String sketchRenderer() {
return JAVA2D;
}
public void setup() {
map = loadImage(CarChase.get().getConfigFilename("mapWithStreetNames.png"));
car = loadImage(CarChase.getFilename("data/car.png"));
textFont(createFont("ArialMT-Bold", 15));
frameRate(CarChase.get().frameRate());
prevSpeed = -1;
carAngle = -10;
segments = new LinkedList<>();
synchronized(objectToNotifyOnSetup) {
if (objectToNotifyOnSetup != null) objectToNotifyOnSetup.notify();
}
image(map, 0, 0);
}
// Called on update
public void draw(){
update();
render();
}
public void update() {
if (segments.size() == 0) return;
Segment segment = segments.peek();
if (segment.getPosition() >= 1 && animating) {
segments.pop();
if (segments.size() == 0) {
CarChase.get().configuration().markDone();
animating = false;
}
}
if (!animating) return;
segment.update();
float position = segment.getPosition();
CarChase.get().configuration().checkSpeed(CarChase.get().getTime(), speed);
if (segment instanceof CircleSegment) return;
if (previousTimelinePosition > position) previousTimelinePosition = position;
if (previousTimelinePosition == position) return;
int prevDistance1 = direction * (int) (previousTimelinePosition * end.distanceTo(start));
int prevDistance2 = -direction * (int) ((1 - previousTimelinePosition) * end.distanceTo(start));
int distance1 = direction * (int) (position * end.distanceTo(start));
int distance2 = -direction * (int) ((1 - position) * end.distanceTo(start));
if (prevDistance1 > distance1) {
int dist1 = distance1;
distance1 = prevDistance1;
prevDistance1 = dist1;
}
if (prevDistance2 > distance2) {
int dist2 = distance2;
distance2 = prevDistance2;
prevDistance2 = dist2;
}
CarChaseTTS tts = CarChase.get().tts();
CarState state1 = new CarState(currentStreet.name, previousStreet.name, start.name, end.name, start.name, direction, previousDirection, prevDistance1, distance1, speed, prevSpeed);
CarState state2 = new CarState(currentStreet.name, previousStreet.name, start.name, end.name, end.name, direction, previousDirection, prevDistance2, distance2, speed, prevSpeed);
tts.matchAndTrigger(state1);
tts.matchAndTrigger(state2);
prevSpeed = speed;
previousTimelinePosition = position;
}
public void render() {
background(255);
image(map, 0, 0);
if (segments.size() == 0) return;
// Render Car
carAngle = segments.peek().getAngle();
carPosition = segments.peek().getAbsCarPosition();
pushMatrix();
translate(carPosition.x, carPosition.y);
rotate(carAngle + HALF_PI);
translate(-car.width / 2 * CAR_SCALE, -car.height / 2 * CAR_SCALE);
translate(20, 0);
scale(CAR_SCALE, CAR_SCALE);
image(car, 0, 0);
stroke(0,255,0);
popMatrix();
if (CarChase.get().frameRate() < 6)
saveFrame("../processing-recordings/v3fun/" + CarChase.get().getConfigName() + "/
}
public int getTime() {
return CarChase.get().getTime();
}
public void notifyOnSetup(Object o) {
objectToNotifyOnSetup = o;
}
public void executeDriveAction(final DriveAction a) {
if (a.percent > 0) segments.clear();
animating = true;
previousStreet = currentStreet == null ? a.street : currentStreet;
currentStreet = a.street;
start = a.start;
end = a.end;
speed = (int) (20 * a.speed);
previousDirection = direction;
direction = a.direction;
final int millisToSkip = a.percent > 0 ? (int) (lineDuration(start, end, a.speed) * a.percent) : 0;
previousTimelinePosition = a.percent > 0 ? a.percent : 0;
float carStartAngle = carAngle;
float carTargetAngle = atan2(end.y - start.y, end.x - start.x);
if (carAngle == -10) carAngle = carStartAngle = carTargetAngle;
carTargetAngle = (carTargetAngle + TWO_PI) % TWO_PI;
carTargetAngle += (indexAbsMin(carTargetAngle - TWO_PI - carAngle, carTargetAngle - carAngle, carTargetAngle + TWO_PI - carAngle) - 1) * TWO_PI;
int rotationDuration = 0;
if (carStartAngle != carTargetAngle && a.percent == 0) {
boolean inverse = carStartAngle < carTargetAngle;
rotationDuration = (int) (2 * Math.abs(carAngle - carTargetAngle) * (20 / a.speed) * (!inverse ? 1.4 : 1.2));
segments.add(new CircleSegment(start, rotationDuration, getTime() - millisToSkip, carStartAngle, carTargetAngle));
}
segments.add(new LineSegment(start, end, a.speed, getTime() - millisToSkip + rotationDuration));
duration = rotationDuration + segments.peekLast().duration;
startMillis = getTime() - millisToSkip;
}
private static int indexAbsMin(float a, float ... b) {
float min = abs(a);
int index = 0;
for (int i = 0; i < b.length; i++) {
if (abs(b[i]) < min) {
min = abs(b[i]);
index = i + 1;
}
}
return index;
}
public float interrupt() {
if (!animating) return 0;
animating = false;
float position = map(getTime() - startMillis, 0, duration, 0, 1);
return position;
}
public static class DriveAction {
public int /*duration, */direction;
public float speed;
public WorldPoint start, end;
public Street street;
public float percent;
public DriveAction(WorldPoint start, WorldPoint end, Street street, int direction, int duration, float speed, float percent) {
this.start = start;
this.end = end;
this.direction = direction;
//this.duration = duration;
this.speed = speed;
this.street = street;
this.percent = percent;
}
}
private static PVector wp2vec(WorldPoint p) {
return new PVector(p.x, p.y);
}
private abstract class Segment {
protected PVector startPoint;
protected PVector endPoint;
protected PVector carPosition;
protected int duration;
protected int startTime;
protected float carAngle;
public Segment(WorldPoint start, WorldPoint end, int duration, int startTime) {
startPoint = wp2vec(start);
endPoint = wp2vec(end);
this.duration = duration;
this.startTime = startTime;
carAngle = -100;
}
public abstract void update();
public PVector getAbsCarPosition() {
if (carPosition == null) update();
return carPosition;
}
public float getAngle() {
if (carAngle == -100) update();
return carAngle;
}
public float getPosition() {
int millis = getTime() - startTime;
return map(millis, 0, duration, 0, 1);
}
}
private class LineSegment extends Segment {
public LineSegment(WorldPoint start, WorldPoint end, float speed, int startTime) {
super(start, end, -1, startTime);
float theta = PVector.sub(endPoint, startPoint).heading();
float x = -CURVE_WIDTH * cos(theta) + endPoint.x;
float y = -CURVE_WIDTH * sin(theta) + endPoint.y;
this.endPoint = new PVector(x, y);
x = CURVE_WIDTH * cos(theta) + startPoint.x;
y = CURVE_WIDTH * sin(theta) + startPoint.y;
this.startPoint = new PVector(x, y);
carAngle = theta;
this.duration = lineDuration(start, end, speed);
}
@Override
public void update() {
this.carPosition = PVector.lerp(startPoint, endPoint, getPosition());
}
}
private class CircleSegment extends Segment {
private PVector mid;
private float radius;
private float angleStart, angleEnd;
private boolean inverse;
public CircleSegment(WorldPoint pt, int duration,
int startTime, float anglePr, float angleNe) {
super(pt, pt, duration, startTime);
float x = CURVE_WIDTH * cos(angleNe) + pt.x;
float y = CURVE_WIDTH * sin(angleNe) + pt.y;
this.endPoint = new PVector(x, y);
x = -CURVE_WIDTH * cos(anglePr) + pt.x;
y = -CURVE_WIDTH * sin(anglePr) + pt.y;
this.startPoint = new PVector(x, y);
this.angleStart = anglePr;
this.angleEnd = angleNe;
inverse = angleStart < angleEnd;
radius = cotan(angleDistance(angleStart, angleEnd)/ 2)*CURVE_WIDTH*2;
mid = PVector.add(PVector.mult(PVector.fromAngle(angleStart + HALF_PI * (inverse ? 1 : -1)), radius/2), startPoint);
if (inverse) {
angleStart += PI;
angleEnd += PI;
}
}
@Override
public void update() {
carAngle = map(getPosition(), 0, 1, angleStart, angleEnd);
this.carPosition = PVector.add(PVector.mult(PVector.fromAngle(carAngle+HALF_PI), radius / 2), mid);
carAngle -= inverse ? PI : 0;
}
}
private float angleDistance(float angle1, float angle2) {
float dist1 = angle1 - angle2;
float dist2 = TWO_PI - angle2 + angle1;
return min(abs(dist1), abs(dist2));
}
private float cotan(float f) {
return 1/tan(f);
}
private int lineDuration(WorldPoint start, WorldPoint end, float speed) {
PVector startPoint = wp2vec(start), endPoint = wp2vec(end);
float theta = PVector.sub(endPoint, startPoint).heading();
float x = -CURVE_WIDTH * cos(theta) + endPoint.x;
float y = -CURVE_WIDTH * sin(theta) + endPoint.y;
endPoint = new PVector(x, y);
x = CURVE_WIDTH * cos(theta) + startPoint.x;
y = CURVE_WIDTH * sin(theta) + startPoint.y;
startPoint = new PVector(x, y);
carAngle = theta;
return (int) (startPoint.dist(endPoint) / speed);
}
}
|
package inprotk.carchase2;
import java.util.ArrayList;
import java.util.List;
import inprotk.carchase2.Configuration.CarState;
import inprotk.carchase2.World.Street;
import inprotk.carchase2.World.WorldPoint;
import processing.core.PApplet;
import processing.core.PImage;
import processing.core.PVector;
public class CarChaseViewer extends PApplet {
private static final long serialVersionUID = 1L;
private static final float CAR_SCALE = 1f / 4.3f;
private PImage map;
private PImage car;
private PVector carPosition;
private PVector startPoint;
private PVector endPoint;
private float carAngle;
private float carStartAngle;
private float carTargetAngle;
private int rotationDuration;
private int transitionDuration;
private int startMillis;
private Street previousStreet;
private Street currentStreet;
private WorldPoint start;
private WorldPoint end;
private int speed;
private int prevSpeed;
private int direction;
private int previousDirection;
private boolean animating;
private boolean setup;
private float previousTimelinePosition;
private Object objectToNotifyOnSetup;
public int sketchWidth() {
return 1024;
}
public int sketchHeight() {
return 768;
}
public String sketchRenderer() {
return JAVA2D;
}
public void setup() {
map = loadImage(CarChase.get().getConfigFilename("mapWithStreetNames.png"));
car = loadImage(CarChase.getFilename("data/car.png"));
textFont(createFont("ArialMT-Bold", 15));
frameRate(CarChase.get().frameRate());
prevSpeed = -1;
carAngle = carStartAngle = carTargetAngle = -10;
setup = true;
synchronized(objectToNotifyOnSetup) {
if (objectToNotifyOnSetup != null) objectToNotifyOnSetup.notify();
}
}
// Called on update
public void draw(){
update();
render();
}
public void update() {
int millis = getTime() - startMillis;
float rotationPercent = map(millis, 0, rotationDuration, 0, 1);
rotationPercent = min(1, rotationPercent);
float position = map(millis, 0, transitionDuration, 0, 1);
if (position >= 1 && animating) {
CarChase.get().configuration().markDone();
animating = false;
position = 1;
}
carAngle = lerp(carStartAngle, carTargetAngle, rotationPercent);
carPosition = PVector.lerp(startPoint, endPoint, position);
if (!animating) return;
CarChase.get().configuration().checkSpeed(CarChase.get().getTime(), speed);
if (previousTimelinePosition > position) previousTimelinePosition = position;
if (previousTimelinePosition == position) return;
int prevDistance1 = direction * (int) (previousTimelinePosition * end.distanceTo(start));
int prevDistance2 = -direction * (int) ((1 - previousTimelinePosition) * end.distanceTo(start));
int distance1 = direction * (int) (position * end.distanceTo(start));
int distance2 = -direction * (int) ((1 - position) * end.distanceTo(start));
if (prevDistance1 > distance1) {
int dist1 = distance1;
distance1 = prevDistance1;
prevDistance1 = dist1;
}
if (prevDistance2 > distance2) {
int dist2 = distance2;
distance2 = prevDistance2;
prevDistance2 = dist2;
}
CarChaseTTS tts = CarChase.get().tts();
CarState state1 = new CarState(currentStreet.name, previousStreet.name, start.name, end.name, start.name, direction, previousDirection, prevDistance1, distance1, speed, prevSpeed);
CarState state2 = new CarState(currentStreet.name, previousStreet.name, start.name, end.name, end.name, direction, previousDirection, prevDistance2, distance2, speed, prevSpeed);
tts.matchAndTrigger(state1);
tts.matchAndTrigger(state2);
prevSpeed = speed;
previousTimelinePosition = position;
}
public void render() {
background(255);
image(map, 0, 0);
if (carPosition == null) return;
// Render Car
pushMatrix();
translate(carPosition.x, carPosition.y);
rotate(carAngle + HALF_PI);
translate(-car.width / 2 * CAR_SCALE, -car.height / 2 * CAR_SCALE);
translate(25, -10);
scale(CAR_SCALE, CAR_SCALE);
image(car, 0, 0);
popMatrix();
//saveFrame("../processing-recordings/" + CarChase.get().getConfigName() + "/
}
public int getTime() {
return CarChase.get().getTime();
}
public void notifyOnSetup(Object o) {
objectToNotifyOnSetup = o;
}
public void executeDriveAction(final DriveAction a) {
animating = true;
previousStreet = currentStreet == null ? a.street : currentStreet;
currentStreet = a.street;
start = a.start;
end = a.end;
speed = (int) (20 * a.speed);
previousDirection = direction;
direction = a.direction;
startPoint = wp2vec(a.start); // the start position is the previous' target
endPoint = wp2vec(a.end);
final int millisToSkip = a.percent > 0 ? (int) (a.duration * a.percent) : 0;
previousTimelinePosition = a.percent > 0 ? a.percent : 0;
carStartAngle = carAngle;
carAngle = carTargetAngle;
carTargetAngle = atan2(endPoint.y - startPoint.y, endPoint.x - startPoint.x);
if (carAngle == -10) carAngle = carStartAngle = carTargetAngle;
carTargetAngle = (carTargetAngle + TWO_PI) % TWO_PI;
carTargetAngle += (indexAbsMin(carTargetAngle - TWO_PI - carAngle, carTargetAngle - carAngle) - 1) * TWO_PI;
rotationDuration = a.percent > 0 ? 0 : (int) (2 * Math.abs(carAngle - carTargetAngle) * (20 / a.speed));
transitionDuration = a.duration;
startMillis = getTime() - millisToSkip;
}
private static int indexAbsMin(float a, float ... b) {
float min = abs(a);
int index = 0;
for (int i = 0; i < b.length; i++) {
if (abs(b[i]) < min) {
min = abs(b[i]);
index = i + 1;
}
}
return index;
}
public float interrupt() {
if (!animating) return 0;
animating = false;
float position = map(getTime() - startMillis, 0, transitionDuration, 0, 1);
return position;
}
public static class DriveAction {
public int duration, direction;
public float speed;
public WorldPoint start, end;
public Street street;
public float percent;
public DriveAction(WorldPoint start, WorldPoint end, Street street, int direction, int duration, float speed, float percent) {
this.start = start;
this.end = end;
this.direction = direction;
this.duration = duration;
this.speed = speed;
this.street = street;
this.percent = percent;
}
}
private static PVector wp2vec(WorldPoint p) {
return new PVector(p.x, p.y);
}
}
|
package org.luaj.vm2.lib.jse;
import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaError;
import org.luaj.vm2.LuaString;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.IoLib;
import org.luaj.vm2.lib.LibFunction;
public class JseIoLib extends IoLib {
protected File wrapStdin() throws IOException {
return new StdinFile();
}
protected File wrapStdout() throws IOException {
return new StdoutFile(FTYPE_STDOUT);
}
protected File wrapStderr() throws IOException {
return new StdoutFile(FTYPE_STDERR);
}
protected File openFile( String filename, boolean readMode, boolean appendMode, boolean updateMode, boolean binaryMode ) throws IOException {
RandomAccessFile f = new RandomAccessFile(filename,readMode? "r": "rw");
if ( appendMode ) {
f.seek(f.length());
} else {
if ( ! readMode )
f.setLength(0);
}
return new FileImpl( f );
}
protected File openProgram(String prog, String mode) throws IOException {
final Process p = Runtime.getRuntime().exec(prog);
return "w".equals(mode)?
new FileImpl( p.getOutputStream() ):
new FileImpl( p.getInputStream() );
}
protected File tmpFile() throws IOException {
java.io.File f = java.io.File.createTempFile(".luaj","bin");
f.deleteOnExit();
return new FileImpl( new RandomAccessFile(f,"rw") );
}
private static void notimplemented() {
throw new LuaError("not implemented");
}
private final class FileImpl extends File {
private final RandomAccessFile file;
private final InputStream is;
private final OutputStream os;
private boolean closed = false;
private boolean nobuffer = false;
private FileImpl( RandomAccessFile file, InputStream is, OutputStream os ) {
this.file = file;
this.is = is!=null? is.markSupported()? is: new BufferedInputStream(is): null;
this.os = os;
}
private FileImpl( RandomAccessFile f ) {
this( f, null, null );
}
private FileImpl( InputStream i ) {
this( null, i, null );
}
private FileImpl( OutputStream o ) {
this( null, null, o );
}
public String tojstring() {
return "file (" + (this.closed ? "closed" : this.hashCode()) + ")";
}
public boolean isstdfile() {
return file == null;
}
public void close() throws IOException {
closed = true;
if ( file != null ) {
file.close();
}
}
public void flush() throws IOException {
if ( os != null )
os.flush();
}
public void write(LuaString s) throws IOException {
if ( os != null )
os.write( s.m_bytes, s.m_offset, s.m_length );
else if ( file != null )
file.write( s.m_bytes, s.m_offset, s.m_length );
else
notimplemented();
if ( nobuffer )
flush();
}
public boolean isclosed() {
return closed;
}
public int seek(String option, int pos) throws IOException {
if ( file != null ) {
if ( "set".equals(option) ) {
file.seek(pos);
} else if ( "end".equals(option) ) {
file.seek(file.length()+pos);
} else {
file.seek(file.getFilePointer()+pos);
}
return (int) file.getFilePointer();
}
notimplemented();
return 0;
}
public void setvbuf(String mode, int size) {
nobuffer = "no".equals(mode);
}
// get length remaining to read
public int remaining() throws IOException {
return file!=null? (int) (file.length()-file.getFilePointer()): -1;
}
// peek ahead one character
public int peek() throws IOException {
if ( is != null ) {
is.mark(1);
int c = is.read();
is.reset();
return c;
} else if ( file != null ) {
long fp = file.getFilePointer();
int c = file.read();
file.seek(fp);
return c;
}
notimplemented();
return 0;
}
// return char if read, -1 if eof, throw IOException on other exception
public int read() throws IOException {
if ( is != null )
return is.read();
else if ( file != null ) {
return file.read();
}
notimplemented();
return 0;
}
// return number of bytes read if positive, -1 if eof, throws IOException
public int read(byte[] bytes, int offset, int length) throws IOException {
if (file!=null) {
return file.read(bytes, offset, length);
} else if (is!=null) {
return is.read(bytes, offset, length);
} else {
notimplemented();
}
return length;
}
}
private final class StdoutFile extends File {
private final int file_type;
private StdoutFile(int file_type) {
this.file_type = file_type;
}
public String tojstring() {
return "file ("+this.hashCode()+")";
}
private final PrintStream getPrintStream() {
return file_type == FTYPE_STDERR?
globals.STDERR:
globals.STDOUT;
}
public void write(LuaString string) throws IOException {
getPrintStream().write(string.m_bytes, string.m_offset, string.m_length);
}
public void flush() throws IOException {
getPrintStream().flush();
}
public boolean isstdfile() {
return true;
}
public void close() throws IOException {
// do not close std files.
}
public boolean isclosed() {
return false;
}
public int seek(String option, int bytecount) throws IOException {
return 0;
}
public void setvbuf(String mode, int size) {
}
public int remaining() throws IOException {
return 0;
}
public int peek() throws IOException, EOFException {
return 0;
}
public int read() throws IOException, EOFException {
return 0;
}
public int read(byte[] bytes, int offset, int length)
throws IOException {
return 0;
}
}
private final class StdinFile extends File {
private StdinFile() {
}
public String tojstring() {
return "file ("+this.hashCode()+")";
}
public void write(LuaString string) throws IOException {
}
public void flush() throws IOException {
}
public boolean isstdfile() {
return true;
}
public void close() throws IOException {
// do not close std files.
}
public boolean isclosed() {
return false;
}
public int seek(String option, int bytecount) throws IOException {
return 0;
}
public void setvbuf(String mode, int size) {
}
public int remaining() throws IOException {
return -1;
}
public int peek() throws IOException, EOFException {
globals.STDIN.mark(1);
int c = globals.STDIN.read();
globals.STDIN.reset();
return c;
}
public int read() throws IOException, EOFException {
return globals.STDIN.read();
}
public int read(byte[] bytes, int offset, int length)
throws IOException {
return globals.STDIN.read(bytes, offset, length);
}
}
}
|
package nxt;
import nxt.BlockchainProcessor.BlockNotAcceptedException;
import nxt.NxtException.NotValidException;
import nxt.at.AT_Block;
import nxt.at.AT_Constants;
import nxt.at.AT_Controller;
import nxt.at.AT_Exception;
import nxt.crypto.Crypto;
import nxt.db.Db;
import nxt.db.DbIterator;
import nxt.db.DerivedDbTable;
import nxt.db.FilteringIterator;
import nxt.peer.Peer;
import nxt.peer.Peers;
import nxt.util.Convert;
import nxt.util.JSON;
import nxt.util.Listener;
import nxt.util.Listeners;
import nxt.util.Logger;
import nxt.util.ThreadPool;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;
import org.json.simple.JSONValue;
import fr.cryptohash.Shabal256;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Semaphore;
final class BlockchainProcessorImpl implements BlockchainProcessor {
public static final int BLOCKCACHEMB = Nxt.getIntProperty("burst.blockCacheMB") == 0 ? 40 : Nxt.getIntProperty("blockCacheMB");
public static boolean oclVerify = Nxt.getBooleanProperty("burst.oclVerify");
public static final int oclThreshold = Nxt.getIntProperty("burst.oclThreshold") == 0 ? 50 : Nxt.getIntProperty("burst.oclThreshold");
public static final int oclWaitThreshold = Nxt.getIntProperty("burst.oclWaitThreshold") == 0 ? 2000 : Nxt.getIntProperty("burst.oclWaitThreshold");
private static final Semaphore gpuUsage = new Semaphore(2);
private static final BlockchainProcessorImpl instance = new BlockchainProcessorImpl();
static BlockchainProcessorImpl getInstance() {
return instance;
}
private final BlockchainImpl blockchain = BlockchainImpl.getInstance();
private final List<DerivedDbTable> derivedTables = new CopyOnWriteArrayList<>();
private final boolean trimDerivedTables = Nxt.getBooleanProperty("nxt.trimDerivedTables");
private volatile int lastTrimHeight;
private final Listeners<Block, Event> blockListeners = new Listeners<>();
private volatile Peer lastBlockchainFeeder;
private volatile int lastBlockchainFeederHeight;
private volatile boolean getMoreBlocks = true;
// blockCache for faster sync
public static final Map<Long, Block> blockCache = new HashMap<Long, Block>();
public static final Map<Long, Long> reverseCache = new HashMap<Long, Long>();
public static final List<Long> unverified = new LinkedList<Long>();
private static int blockCacheSize = 0;
private volatile boolean isScanning;
private volatile boolean forceScan = Nxt.getBooleanProperty("nxt.forceScan");
private volatile boolean validateAtScan = Nxt.getBooleanProperty("nxt.forceValidate");
// Last downloaded block:
private Long lastDownloaded = 0L;
private final Runnable debugInfoThread = new Runnable() {
@Override
public void run() {
Logger.logMessage("Unverified blocks: " + String.valueOf(unverified.size()));
Logger.logMessage("Blocks in cache: " + String.valueOf(blockCache.size()));
Logger.logMessage("Bytes in cache: " + String.valueOf(blockCacheSize));
}
};
private final Runnable pocVerificationThread = new Runnable() {
@Override
public void run() {
for(;;) {
if(oclVerify) {
boolean gpuAcquired = false;
try {
List<BlockImpl> blocks = new LinkedList<>();
synchronized (blockCache) {
if (unverified.size() == 0) {
return;
}
int verifiedCached = blockCache.size() - unverified.size();
if(verifiedCached >= oclWaitThreshold && unverified.size() < OCLPoC.getMaxItems() / 2) {
return;
}
if (unverified.size() < oclThreshold) {
Long blockId = BlockchainProcessorImpl.unverified.get(0);
BlockchainProcessorImpl.unverified.remove(blockId);
blocks.add((BlockImpl) BlockchainProcessorImpl.blockCache.get(blockId));
} else {
if (!gpuUsage.tryAcquire()) {
System.out.println("already max locked");
return;
}
gpuAcquired = true;
while (unverified.size() > 0 && blocks.size() < OCLPoC.getMaxItems()) {
Long blockId = BlockchainProcessorImpl.unverified.get(0);
BlockchainProcessorImpl.unverified.remove(blockId);
blocks.add((BlockImpl) BlockchainProcessorImpl.blockCache.get(blockId));
}
}
}
try {
if(blocks.size() > 1) {
OCLPoC.validatePoC(blocks);
}
else {
blocks.get(0).preVerify();
}
}
catch (OCLPoC.PreValidateFailException e) {
e.printStackTrace();
blacklistClean(e.getBlock(), e);
}
catch (BlockNotAcceptedException e) { // only thrown from cpu prevalidate
e.printStackTrace();
blacklistClean(blocks.get(0), e);
}
}
finally {
if(gpuAcquired) {
gpuUsage.release();
}
}
}
else {
BlockImpl block;
synchronized (BlockchainProcessorImpl.blockCache) {
if (BlockchainProcessorImpl.unverified.size() == 0)
return;
Long blockId = BlockchainProcessorImpl.unverified.get(0);
BlockchainProcessorImpl.unverified.remove(blockId);
block = (BlockImpl) BlockchainProcessorImpl.blockCache.get(blockId);
}
try {
block.preVerify();
} catch (BlockchainProcessor.BlockNotAcceptedException e) {
blacklistClean(block, e);
}
}
}
}
};
private final Runnable blockImporterThread = new Runnable() {
@Override
public void run() {
synchronized (blockchain) {
for(;;) {
Long lastId = blockchain.getLastBlock().getId();
Long currentBlockId;
BlockImpl currentBlock;
synchronized(BlockchainProcessorImpl.blockCache) {
if(!BlockchainProcessorImpl.reverseCache.containsKey(lastId))
return;
currentBlockId = BlockchainProcessorImpl.reverseCache.get(lastId);
currentBlock = (BlockImpl)BlockchainProcessorImpl.blockCache.get(currentBlockId);
}
try {
if(!currentBlock.isVerified()) {
currentBlock.preVerify();
return;
}
pushBlock(currentBlock);
} catch (BlockNotAcceptedException e) {
Logger.logMessage("Block not accepted");
/*currentBlock.getPeer().blacklist(e);
synchronized(BlockchainProcessorImpl.blockCache) {
long removeId = lastId;
while(reverseCache.containsKey(removeId)) {
long id = reverseCache.get(removeId);
reverseCache.remove(removeId);
blockCacheSize -= ((BlockImpl)blockCache.get(id)).getByteLength();
blockCache.remove(id);
removeId = id;
}
}*/
blacklistClean(currentBlock, e);
return;
}
// Clean up cache
synchronized(BlockchainProcessorImpl.blockCache) {
BlockchainProcessorImpl.reverseCache.remove(lastId);
BlockchainProcessorImpl.blockCache.remove(currentBlockId);
blockCacheSize -= currentBlock.getByteLength();
/*if (blockchain.getLastBlock().getId() == block.getPreviousBlockId()) {
} else if (!BlockDb.hasBlock(block.getId())) {
forkBlocks.add(block);
}*/
}
}
}
}
};
private void blacklistClean(BlockImpl block, Exception e) {
block.getPeer().blacklist(e);
long removeId = block.getId();
synchronized (BlockchainProcessorImpl.blockCache) {
reverseCache.remove(block.getPreviousBlockId());
blockCache.remove(block.getId());
while(reverseCache.containsKey(removeId)) {
long id = reverseCache.get(removeId);
reverseCache.remove(removeId);
blockCacheSize -= ((BlockImpl)blockCache.get(id)).getByteLength();
blockCache.remove(id);
removeId = id;
}
}
}
private final Runnable getMoreBlocksThread = new Runnable() {
private final JSONStreamAware getCumulativeDifficultyRequest;
{
JSONObject request = new JSONObject();
request.put("requestType", "getCumulativeDifficulty");
getCumulativeDifficultyRequest = JSON.prepareRequest(request);
}
private boolean peerHasMore;
@Override
public void run() {
try {
try {
if (!getMoreBlocks) {
return;
}
if(blockCacheSize > BLOCKCACHEMB * 1024 * 1024)
return;
peerHasMore = true;
Peer peer = Peers.getAnyPeer(Peer.State.CONNECTED, true);
if (peer == null) {
return;
}
JSONObject response = peer.send(getCumulativeDifficultyRequest);
if (response == null) {
return;
}
BigInteger curCumulativeDifficulty = blockchain.getLastBlock().getCumulativeDifficulty();
String peerCumulativeDifficulty = (String) response.get("cumulativeDifficulty");
if (peerCumulativeDifficulty == null) {
return;
}
BigInteger betterCumulativeDifficulty = new BigInteger(peerCumulativeDifficulty);
if (betterCumulativeDifficulty.compareTo(curCumulativeDifficulty) < 0) {
return;
}
if (response.get("blockchainHeight") != null) {
lastBlockchainFeeder = peer;
lastBlockchainFeederHeight = ((Long) response.get("blockchainHeight")).intValue();
}
if (betterCumulativeDifficulty.equals(curCumulativeDifficulty)) {
return;
}
long commonBlockId = Genesis.GENESIS_BLOCK_ID;
if (blockchain.getLastBlock().getId() != Genesis.GENESIS_BLOCK_ID) {
commonBlockId = getCommonMilestoneBlockId(peer);
}
if (commonBlockId == 0 || !peerHasMore) {
return;
}
commonBlockId = getCommonBlockId(peer, commonBlockId);
if (commonBlockId == 0 || !peerHasMore) {
return;
}
final Block commonBlock = BlockDb.findBlock(commonBlockId);
if (commonBlock == null || blockchain.getHeight() - commonBlock.getHeight() >= 720) {
return;
}
long currentBlockId = (lastDownloaded == 0 ? commonBlockId : lastDownloaded);
if(commonBlock.getHeight() < blockchain.getLastBlock().getHeight()) { // fork point
currentBlockId = commonBlockId;
}
else {
synchronized (blockCache) {
long checkBlockId = currentBlockId;
while (checkBlockId != blockchain.getLastBlock().getId()) {
if (blockCache.get(checkBlockId) == null) {
currentBlockId = blockchain.getLastBlock().getId();
break;
}
checkBlockId = blockCache.get(checkBlockId).getPreviousBlockId();
}
}
}
List<BlockImpl> forkBlocks = new ArrayList<>();
boolean processedAll = true;
int requestCount = 0;
outer:
while (forkBlocks.size() < 1440 && requestCount++ < 10 && ((blockCacheSize < BLOCKCACHEMB * 1024 * 1024) || forkBlocks.size() > 0)) { // fork decision could be wrong if cut off so ignore cache size for forks
//Logger.logMessage("Downloading " + String.valueOf(currentBlockId));
JSONArray nextBlocks = getNextBlocks(peer, currentBlockId);
if (nextBlocks == null || nextBlocks.size() == 0) {
break;
}
// Insert Blocks to blockCache
synchronized(BlockchainProcessorImpl.blockCache) {
for(Object o : nextBlocks) {
BlockImpl block;
JSONObject blockData = (JSONObject) o;
try {
block = BlockImpl.parseBlock(blockData);
if(block.getPreviousBlockId() != currentBlockId) { // ensure peer isn't cluttering cache with unrequested stuff
Logger.logMessage("Peer sent unrequested block. Blacklisting...");
peer.blacklist();
return;
}
lastDownloaded = currentBlockId = block.getId();
if(blockCache.containsKey(block.getId()) || BlockDb.hasBlock(block.getId())) {
continue;
}
block.setPeer(peer);
int blockSize = blockData.toString().length();
blockCacheSize += blockSize;
block.setByteLength(blockSize);
Long prevId = Convert.parseUnsignedLong((String) blockData.get("previousBlock"));
// Try to find previous Block:
if(BlockchainProcessorImpl.blockCache.containsKey(prevId)) {
block.setHeight(BlockchainProcessorImpl.blockCache.get(prevId).getHeight() + 1);
} else {
// First in cache? Get from blockchain:
BlockImpl prevBlock = (BlockImpl)Nxt.getBlockchain().getBlock(prevId);
if(prevBlock == null) {
// We may be on a fork: Add all other Blocks to forkQueue:
if(forkBlocks.size() > 0) {
block.setHeight(forkBlocks.get(forkBlocks.size() - 1).getHeight() + 1);
forkBlocks.add(block);
} else {
Logger.logMessage("Previous Block with ID " + String.valueOf(prevId) + " not found. Blacklisting ...");
peer.blacklist();
return;
}
}
Long altBlockId = null;
if(forkBlocks.size() == 0) {
try {
altBlockId = BlockDb.findBlockIdAtHeight(prevBlock.getHeight() + 1);
} catch (Exception e) {}
if(altBlockId != null) {
if(altBlockId.longValue() != block.getId()) {
// fork
forkBlocks.add(block);
}
else {
continue; // don't clutter cache with stuff we already have
}
}
block.setHeight(prevBlock.getHeight() + 1);
}
}
//Logger.logMessage("Block Height " + String.valueOf(block.getHeight()) + " ID " + String.valueOf(block.getId()));
if(forkBlocks.size() == 0) { // keep old cache separate from fork. blindly adding to reverseCache could cause it to end up in an uncleanable state
// Add to Blockcache
BlockchainProcessorImpl.blockCache.put(lastDownloaded, block);
// Add to reverse cache
BlockchainProcessorImpl.reverseCache.put(prevId, currentBlockId);
// Mark for threaded poc verification
BlockchainProcessorImpl.unverified.add(lastDownloaded);
}
} catch (RuntimeException | NxtException.ValidationException e) {
Logger.logMessage("Failed to parse block: " + e.toString(), e);
peer.blacklist(e);
return;
} catch (Exception e) {
}
}
}
}
if(forkBlocks.size() > 0 && blockchain.getHeight() - commonBlock.getHeight() < 720) {
processFork(forkBlocks.get(0).getPeer(), forkBlocks, commonBlock);
}
} catch (NxtException.StopException e) {
Logger.logMessage("Blockchain download stopped: " + e.getMessage());
} catch (Exception e) {
Logger.logMessage("Error in blockchain download thread", e);
}
} catch (Throwable t) {
Logger.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString());
t.printStackTrace();
System.exit(1);
}
}
private long getCommonMilestoneBlockId(Peer peer) {
String lastMilestoneBlockId = null;
while (true) {
JSONObject milestoneBlockIdsRequest = new JSONObject();
milestoneBlockIdsRequest.put("requestType", "getMilestoneBlockIds");
if (lastMilestoneBlockId == null) {
milestoneBlockIdsRequest.put("lastBlockId", blockchain.getLastBlock().getStringId());
} else {
milestoneBlockIdsRequest.put("lastMilestoneBlockId", lastMilestoneBlockId);
}
JSONObject response = peer.send(JSON.prepareRequest(milestoneBlockIdsRequest));
if (response == null) {
return 0;
}
JSONArray milestoneBlockIds = (JSONArray) response.get("milestoneBlockIds");
if (milestoneBlockIds == null) {
return 0;
}
if (milestoneBlockIds.isEmpty()) {
return Genesis.GENESIS_BLOCK_ID;
}
// prevent overloading with blockIds
if (milestoneBlockIds.size() > 20) {
Logger.logDebugMessage("Obsolete or rogue peer " + peer.getPeerAddress() + " sends too many milestoneBlockIds, blacklisting");
peer.blacklist();
return 0;
}
if (Boolean.TRUE.equals(response.get("last"))) {
peerHasMore = false;
}
for (Object milestoneBlockId : milestoneBlockIds) {
long blockId = Convert.parseUnsignedLong((String) milestoneBlockId);
if (BlockDb.hasBlock(blockId)) {
if (lastMilestoneBlockId == null && milestoneBlockIds.size() > 1) {
peerHasMore = false;
}
return blockId;
}
lastMilestoneBlockId = (String) milestoneBlockId;
}
}
}
private long getCommonBlockId(Peer peer, long commonBlockId) {
while (true) {
JSONObject request = new JSONObject();
request.put("requestType", "getNextBlockIds");
request.put("blockId", Convert.toUnsignedLong(commonBlockId));
JSONObject response = peer.send(JSON.prepareRequest(request));
if (response == null) {
return 0;
}
JSONArray nextBlockIds = (JSONArray) response.get("nextBlockIds");
if (nextBlockIds == null || nextBlockIds.size() == 0) {
return 0;
}
// prevent overloading with blockIds
if (nextBlockIds.size() > 1440) {
Logger.logDebugMessage("Obsolete or rogue peer " + peer.getPeerAddress() + " sends too many nextBlockIds, blacklisting");
peer.blacklist();
return 0;
}
for (Object nextBlockId : nextBlockIds) {
long blockId = Convert.parseUnsignedLong((String) nextBlockId);
if (! BlockDb.hasBlock(blockId)) {
return commonBlockId;
}
commonBlockId = blockId;
}
}
}
private JSONArray getNextBlocks(Peer peer, long curBlockId) {
JSONObject request = new JSONObject();
request.put("requestType", "getNextBlocks");
request.put("blockId", Convert.toUnsignedLong(curBlockId));
JSONObject response = peer.send(JSON.prepareRequest(request));
if (response == null) {
return null;
}
JSONArray nextBlocks = (JSONArray) response.get("nextBlocks");
if (nextBlocks == null) {
return null;
}
// prevent overloading with blocks
if (nextBlocks.size() > 1440) {
Logger.logDebugMessage("Obsolete or rogue peer " + peer.getPeerAddress() + " sends too many nextBlocks, blacklisting");
peer.blacklist();
return null;
}
return nextBlocks;
}
private void processFork(Peer peer, final List<BlockImpl> forkBlocks, final Block commonBlock) {
synchronized (blockchain) {
BigInteger curCumulativeDifficulty = blockchain.getLastBlock().getCumulativeDifficulty();
List<BlockImpl> myPoppedOffBlocks = popOffTo(commonBlock);
int pushedForkBlocks = 0;
if (blockchain.getLastBlock().getId() == commonBlock.getId()) {
for (BlockImpl block : forkBlocks) {
if (blockchain.getLastBlock().getId() == block.getPreviousBlockId()) {
try {
pushBlock(block);
pushedForkBlocks += 1;
} catch (BlockNotAcceptedException e) {
peer.blacklist(e);
break;
}
}
}
}
if (pushedForkBlocks > 0 && blockchain.getLastBlock().getCumulativeDifficulty().compareTo(curCumulativeDifficulty) < 0) {
Logger.logDebugMessage("Pop off caused by peer " + peer.getPeerAddress() + ", blacklisting");
peer.blacklist();
List<BlockImpl> peerPoppedOffBlocks = popOffTo(commonBlock);
pushedForkBlocks = 0;
for (BlockImpl block : peerPoppedOffBlocks) {
TransactionProcessorImpl.getInstance().processLater(block.getTransactions());
}
}
if (pushedForkBlocks == 0) {
for (int i = myPoppedOffBlocks.size() - 1; i >= 0; i
BlockImpl block = myPoppedOffBlocks.remove(i);
try {
pushBlock(block);
} catch (BlockNotAcceptedException e) {
Logger.logErrorMessage("Popped off block no longer acceptable: " + block.getJSONObject().toJSONString(), e);
break;
}
}
} else {
for (BlockImpl block : myPoppedOffBlocks) {
TransactionProcessorImpl.getInstance().processLater(block.getTransactions());
}
}
} // synchronized
synchronized (blockCache) { // cache may no longer correspond with current chain, so dump it
blockCache.clear();
reverseCache.clear();
unverified.clear();
lastDownloaded = blockchain.getLastBlock().getId();
blockCacheSize = 0;
}
}
};
private BlockchainProcessorImpl() {
blockListeners.addListener(new Listener<Block>() {
@Override
public void notify(Block block) {
if (block.getHeight() % 5000 == 0) {
Logger.logMessage("processed block " + block.getHeight());
}
}
}, Event.BLOCK_SCANNED);
blockListeners.addListener(new Listener<Block>() {
@Override
public void notify(Block block) {
if (block.getHeight() % 5000 == 0) {
Logger.logMessage("processed block " + block.getHeight());
Db.analyzeTables();
}
}
}, Event.BLOCK_PUSHED);
if (trimDerivedTables) {
blockListeners.addListener(new Listener<Block>() {
@Override
public void notify(Block block) {
if (block.getHeight() % 1440 == 0) {
lastTrimHeight = Math.max(block.getHeight() - Constants.MAX_ROLLBACK, 0);
if (lastTrimHeight > 0) {
for (DerivedDbTable table : derivedTables) {
table.trim(lastTrimHeight);
}
}
}
}
}, Event.AFTER_BLOCK_APPLY);
}
blockListeners.addListener(new Listener<Block>() {
@Override
public void notify(Block block) {
Db.analyzeTables();
}
}, Event.RESCAN_END);
ThreadPool.runBeforeStart(new Runnable() {
@Override
public void run() {
addGenesisBlock();
if (forceScan) {
scan(0);
}
}
}, false);
ThreadPool.scheduleThread("GetMoreBlocks", getMoreBlocksThread, 2);
ThreadPool.scheduleThread("ImportBlocks", blockImporterThread, 10);
ThreadPool.scheduleThreadCores("VerifyPoc", pocVerificationThread, 9);
//ThreadPool.scheduleThread("Info", debugInfoThread, 5);
}
@Override
public boolean addListener(Listener<Block> listener, BlockchainProcessor.Event eventType) {
return blockListeners.addListener(listener, eventType);
}
@Override
public boolean removeListener(Listener<Block> listener, Event eventType) {
return blockListeners.removeListener(listener, eventType);
}
@Override
public void registerDerivedTable(DerivedDbTable table) {
derivedTables.add(table);
}
@Override
public Peer getLastBlockchainFeeder() {
return lastBlockchainFeeder;
}
@Override
public int getLastBlockchainFeederHeight() {
return lastBlockchainFeederHeight;
}
@Override
public boolean isScanning() {
return isScanning;
}
@Override
public int getMinRollbackHeight() {
return trimDerivedTables ? (lastTrimHeight > 0 ? lastTrimHeight : Math.max(blockchain.getHeight() - Constants.MAX_ROLLBACK, 0)) : 0;
}
@Override
public void processPeerBlock(JSONObject request) throws NxtException {
BlockImpl block = BlockImpl.parseBlock(request);
pushBlock(block);
}
@Override
public List<BlockImpl> popOffTo(int height) {
return popOffTo(blockchain.getBlockAtHeight(height));
}
@Override
public void fullReset() {
synchronized (blockchain) {
//BlockDb.deleteBlock(Genesis.GENESIS_BLOCK_ID); // fails with stack overflow in H2
BlockDb.deleteAll();
addGenesisBlock();
scan(0);
}
}
@Override
public void forceScanAtStart() {
forceScan = true;
}
@Override
public void validateAtNextScan() {
validateAtScan = true;
}
void setGetMoreBlocks(boolean getMoreBlocks) {
this.getMoreBlocks = getMoreBlocks;
}
private void addBlock(BlockImpl block) {
try (Connection con = Db.getConnection()) {
BlockDb.saveBlock(con, block);
blockchain.setLastBlock(block);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
private void addGenesisBlock() {
if (BlockDb.hasBlock(Genesis.GENESIS_BLOCK_ID)) {
Logger.logMessage("Genesis block already in database");
BlockImpl lastBlock = BlockDb.findLastBlock();
blockchain.setLastBlock(lastBlock);
Logger.logMessage("Last block height: " + lastBlock.getHeight());
return;
}
Logger.logMessage("Genesis block not in database, starting from scratch");
try {
List<TransactionImpl> transactions = new ArrayList<>();
MessageDigest digest = Crypto.sha256();
for (Transaction transaction : transactions) {
digest.update(transaction.getBytes());
}
ByteBuffer bf = ByteBuffer.allocate( 0 );
bf.order( ByteOrder.LITTLE_ENDIAN );
byte[] byteATs = bf.array();
BlockImpl genesisBlock = new BlockImpl(-1, 0, 0, 0, 0, transactions.size() * 128, digest.digest(),
Genesis.CREATOR_PUBLIC_KEY, new byte[32], Genesis.GENESIS_BLOCK_SIGNATURE, null, transactions, 0, byteATs);
genesisBlock.setPrevious(null);
addBlock(genesisBlock);
} catch (NxtException.ValidationException e) {
Logger.logMessage(e.getMessage());
throw new RuntimeException(e.toString(), e);
}
}
private void pushBlock(final BlockImpl block) throws BlockNotAcceptedException {
int curTime = Nxt.getEpochTime();
synchronized (blockchain) {
TransactionProcessorImpl transactionProcessor = TransactionProcessorImpl.getInstance();
BlockImpl previousLastBlock = null;
try {
Db.beginTransaction();
previousLastBlock = blockchain.getLastBlock();
if (previousLastBlock.getId() != block.getPreviousBlockId()) {
throw new BlockOutOfOrderException("Previous block id doesn't match");
}
if (block.getVersion() != getBlockVersion(previousLastBlock.getHeight())) {
throw new BlockNotAcceptedException("Invalid version " + block.getVersion());
}
if (block.getVersion() != 1 && !Arrays.equals(Crypto.sha256().digest(previousLastBlock.getBytes()), block.getPreviousBlockHash())) {
throw new BlockNotAcceptedException("Previous block hash doesn't match");
}
if (block.getTimestamp() > curTime + 15 || block.getTimestamp() <= previousLastBlock.getTimestamp()) {
throw new BlockOutOfOrderException("Invalid timestamp: " + block.getTimestamp()
+ " current time is " + curTime + ", previous block timestamp is " + previousLastBlock.getTimestamp());
}
if (block.getId() == 0L || BlockDb.hasBlock(block.getId())) {
throw new BlockNotAcceptedException("Duplicate block or invalid id");
}
if (!block.verifyGenerationSignature()) {
throw new BlockNotAcceptedException("Generation signature verification failed");
}
if (!block.verifyBlockSignature()) {
throw new BlockNotAcceptedException("Block signature verification failed");
}
Map<TransactionType, Set<String>> duplicates = new HashMap<>();
long calculatedTotalAmount = 0;
long calculatedTotalFee = 0;
MessageDigest digest = Crypto.sha256();
for (TransactionImpl transaction : block.getTransactions()) {
if (transaction.getTimestamp() > curTime + 15) {
throw new BlockOutOfOrderException("Invalid transaction timestamp: " + transaction.getTimestamp()
+ ", current time is " + curTime);
}
if (transaction.getTimestamp() > block.getTimestamp() + 15
|| transaction.getExpiration() < block.getTimestamp()) {
throw new TransactionNotAcceptedException("Invalid transaction timestamp " + transaction.getTimestamp()
+ " for transaction " + transaction.getStringId() + ", current time is " + curTime
+ ", block timestamp is " + block.getTimestamp(), transaction);
}
if (TransactionDb.hasTransaction(transaction.getId())) {
throw new TransactionNotAcceptedException("Transaction " + transaction.getStringId()
+ " is already in the blockchain", transaction);
}
if (transaction.getReferencedTransactionFullHash() != null) {
if ((previousLastBlock.getHeight() < Constants.REFERENCED_TRANSACTION_FULL_HASH_BLOCK
&& !TransactionDb.hasTransaction(Convert.fullHashToId(transaction.getReferencedTransactionFullHash())))
|| (previousLastBlock.getHeight() >= Constants.REFERENCED_TRANSACTION_FULL_HASH_BLOCK
&& !hasAllReferencedTransactions(transaction, transaction.getTimestamp(), 0))) {
throw new TransactionNotAcceptedException("Missing or invalid referenced transaction "
+ transaction.getReferencedTransactionFullHash()
+ " for transaction " + transaction.getStringId(), transaction);
}
}
if (transaction.getVersion() != transactionProcessor.getTransactionVersion(previousLastBlock.getHeight())) {
throw new TransactionNotAcceptedException("Invalid transaction version " + transaction.getVersion()
+ " at height " + previousLastBlock.getHeight(), transaction);
}
/*if (!transaction.verifySignature()) { // moved to preVerify
throw new TransactionNotAcceptedException("Signature verification failed for transaction "
+ transaction.getStringId() + " at height " + previousLastBlock.getHeight(), transaction);
}*/
if(!transaction.verifyPublicKey()) {
throw new TransactionNotAcceptedException("Wrong public key in transaction " + transaction.getStringId() + " at height " + previousLastBlock.getHeight(), transaction);
}
if (Nxt.getBlockchain().getHeight() >= Constants.AUTOMATED_TRANSACTION_BLOCK) {
if (!EconomicClustering.verifyFork(transaction)) {
Logger.logDebugMessage("Block " + block.getStringId() + " height " + (previousLastBlock.getHeight() + 1)
+ " contains transaction that was generated on a fork: "
+ transaction.getStringId() + " ecBlockHeight " + transaction.getECBlockHeight() + " ecBlockId "
+ Convert.toUnsignedLong(transaction.getECBlockId()));
throw new TransactionNotAcceptedException("Transaction belongs to a different fork", transaction);
}
}
if (transaction.getId() == 0L) {
throw new TransactionNotAcceptedException("Invalid transaction id", transaction);
}
if (transaction.isDuplicate(duplicates)) {
throw new TransactionNotAcceptedException("Transaction is a duplicate: "
+ transaction.getStringId(), transaction);
}
try {
transaction.validate();
} catch (NxtException.ValidationException e) {
throw new TransactionNotAcceptedException(e.getMessage(), transaction);
}
calculatedTotalAmount += transaction.getAmountNQT();
calculatedTotalFee += transaction.getFeeNQT();
digest.update(transaction.getBytes());
}
if (calculatedTotalAmount > block.getTotalAmountNQT() || calculatedTotalFee > block.getTotalFeeNQT()) {
throw new BlockNotAcceptedException("Total amount or fee don't match transaction totals");
}
if (!Arrays.equals(digest.digest(), block.getPayloadHash())) {
throw new BlockNotAcceptedException("Payload hash doesn't match");
}
long remainingAmount = Convert.safeSubtract(block.getTotalAmountNQT(), calculatedTotalAmount);
long remainingFee = Convert.safeSubtract(block.getTotalFeeNQT(), calculatedTotalFee);
block.setPrevious(previousLastBlock);
blockListeners.notify(block, Event.BEFORE_BLOCK_ACCEPT);
transactionProcessor.requeueAllUnconfirmedTransactions();
Account.flushAccountTable();
addBlock(block);
accept(block, remainingAmount, remainingFee);
for (DerivedDbTable table : derivedTables) {
table.finish();
}
Db.commitTransaction();
} catch (Exception e) {
Db.rollbackTransaction();
blockchain.setLastBlock(previousLastBlock);
throw e;
} finally {
Db.endTransaction();
}
} // synchronized
blockListeners.notify(block, Event.BLOCK_PUSHED);
if (block.getTimestamp() >= Nxt.getEpochTime() - 15) {
Peers.sendToSomePeers(block);
}
}
private void accept(BlockImpl block, Long remainingAmount, Long remainingFee) throws TransactionNotAcceptedException, BlockNotAcceptedException {
Subscription.clearRemovals();
TransactionProcessorImpl transactionProcessor = TransactionProcessorImpl.getInstance();
for (TransactionImpl transaction : block.getTransactions()) {
if (! transaction.applyUnconfirmed()) {
throw new TransactionNotAcceptedException("Double spending transaction: " + transaction.getStringId(), transaction);
}
}
long calculatedRemainingAmount = 0;
long calculatedRemainingFee = 0;
//ATs
AT_Block atBlock;
AT.clearPendingFees();
AT.clearPendingTransactions();
try {
atBlock = AT_Controller.validateATs( block.getBlockATs() , Nxt.getBlockchain().getHeight());
} catch (NoSuchAlgorithmException e) {
//should never reach that point
throw new BlockNotAcceptedException( "md5 does not exist" );
} catch (AT_Exception e) {
throw new BlockNotAcceptedException("ats are not matching at block height " + Nxt.getBlockchain().getHeight() );
}
calculatedRemainingAmount += atBlock.getTotalAmount();
calculatedRemainingFee += atBlock.getTotalFees();
//ATs
if(Subscription.isEnabled()) {
calculatedRemainingFee += Subscription.applyUnconfirmed(block.getTimestamp());
}
if(remainingAmount != null && remainingAmount.longValue() != calculatedRemainingAmount) {
throw new BlockNotAcceptedException("Calculated remaining amount doesn't add up");
}
if(remainingFee != null && remainingFee.longValue() != calculatedRemainingFee) {
throw new BlockNotAcceptedException("Calculated remaining fee doesn't add up");
}
blockListeners.notify(block, Event.BEFORE_BLOCK_APPLY);
block.apply();
Subscription.applyConfirmed(block);
if(Escrow.isEnabled()) {
Escrow.updateOnBlock(block);
}
blockListeners.notify(block, Event.AFTER_BLOCK_APPLY);
if (block.getTransactions().size() > 0) {
transactionProcessor.notifyListeners(block.getTransactions(), TransactionProcessor.Event.ADDED_CONFIRMED_TRANSACTIONS);
}
}
private List<BlockImpl> popOffTo(Block commonBlock) {
synchronized (blockchain) {
if (commonBlock.getHeight() < getMinRollbackHeight()) {
throw new IllegalArgumentException("Rollback to height " + commonBlock.getHeight() + " not suppported, "
+ "current height " + Nxt.getBlockchain().getHeight());
}
if (! blockchain.hasBlock(commonBlock.getId())) {
Logger.logDebugMessage("Block " + commonBlock.getStringId() + " not found in blockchain, nothing to pop off");
return Collections.emptyList();
}
List<BlockImpl> poppedOffBlocks = new ArrayList<>();
try {
Db.beginTransaction();
BlockImpl block = blockchain.getLastBlock();
Logger.logDebugMessage("Rollback from " + block.getHeight() + " to " + commonBlock.getHeight());
while (block.getId() != commonBlock.getId() && block.getId() != Genesis.GENESIS_BLOCK_ID) {
poppedOffBlocks.add(block);
block = popLastBlock();
}
for (DerivedDbTable table : derivedTables) {
table.rollback(commonBlock.getHeight());
}
Db.commitTransaction();
} catch (RuntimeException e) {
Db.rollbackTransaction();
Logger.logDebugMessage("Error popping off to " + commonBlock.getHeight(), e);
throw e;
} finally {
Db.endTransaction();
}
return poppedOffBlocks;
} // synchronized
}
private BlockImpl popLastBlock() {
BlockImpl block = blockchain.getLastBlock();
if (block.getId() == Genesis.GENESIS_BLOCK_ID) {
throw new RuntimeException("Cannot pop off genesis block");
}
BlockImpl previousBlock = BlockDb.findBlock(block.getPreviousBlockId());
blockchain.setLastBlock(block, previousBlock);
for (TransactionImpl transaction : block.getTransactions()) {
transaction.unsetBlock();
}
BlockDb.deleteBlocksFrom(block.getId());
blockListeners.notify(block, Event.BLOCK_POPPED);
return previousBlock;
}
int getBlockVersion(int previousBlockHeight) {
return previousBlockHeight < Constants.TRANSPARENT_FORGING_BLOCK ? 1
: previousBlockHeight < Constants.NQT_BLOCK ? 2
: 3;
}
void generateBlock(String secretPhrase, byte[] publicKey, Long nonce) throws BlockNotAcceptedException {
TransactionProcessorImpl transactionProcessor = TransactionProcessorImpl.getInstance();
List<TransactionImpl> orderedUnconfirmedTransactions = new ArrayList<>();
try (FilteringIterator<TransactionImpl> transactions = new FilteringIterator<>(transactionProcessor.getAllUnconfirmedTransactions(),
new FilteringIterator.Filter<TransactionImpl>() {
@Override
public boolean ok(TransactionImpl transaction) {
return hasAllReferencedTransactions(transaction, transaction.getTimestamp(), 0);
}
})) {
for (TransactionImpl transaction : transactions) {
orderedUnconfirmedTransactions.add(transaction);
}
}
BlockImpl previousBlock = blockchain.getLastBlock();
SortedSet<TransactionImpl> blockTransactions = new TreeSet<>();
Map<TransactionType, Set<String>> duplicates = new HashMap<>();
long totalAmountNQT = 0;
long totalFeeNQT = 0;
int payloadLength = 0;
int blockTimestamp = Nxt.getEpochTime();
while (payloadLength <= Constants.MAX_PAYLOAD_LENGTH && blockTransactions.size() <= Constants.MAX_NUMBER_OF_TRANSACTIONS) {
int prevNumberOfNewTransactions = blockTransactions.size();
for (TransactionImpl transaction : orderedUnconfirmedTransactions) {
if(blockTransactions.size() >= Constants.MAX_NUMBER_OF_TRANSACTIONS) {
break;
}
int transactionLength = transaction.getSize();
if (blockTransactions.contains(transaction) || payloadLength + transactionLength > Constants.MAX_PAYLOAD_LENGTH) {
continue;
}
if (transaction.getVersion() != transactionProcessor.getTransactionVersion(previousBlock.getHeight())) {
continue;
}
if (transaction.getTimestamp() > blockTimestamp + 15 || transaction.getExpiration() < blockTimestamp) {
continue;
}
if (Nxt.getBlockchain().getHeight() >= Constants.AUTOMATED_TRANSACTION_BLOCK) {
if (!EconomicClustering.verifyFork(transaction)) {
Logger.logDebugMessage("Including transaction that was generated on a fork: " + transaction.getStringId()
+ " ecBlockHeight " + transaction.getECBlockHeight() + " ecBlockId " + Convert.toUnsignedLong(transaction.getECBlockId()));
continue;
}
}
if (transaction.isDuplicate(duplicates)) {
continue;
}
try {
transaction.validate();
} catch (NxtException.NotCurrentlyValidException e) {
continue;
} catch (NxtException.ValidationException e) {
transactionProcessor.removeUnconfirmedTransaction(transaction);
continue;
}
blockTransactions.add(transaction);
payloadLength += transactionLength;
totalAmountNQT += transaction.getAmountNQT();
totalFeeNQT += transaction.getFeeNQT();
}
if (blockTransactions.size() == prevNumberOfNewTransactions) {
break;
}
}
if(Subscription.isEnabled()) {
synchronized(blockchain) {
Subscription.clearRemovals();
try {
Db.beginTransaction();
transactionProcessor.requeueAllUnconfirmedTransactions();
//transactionProcessor.processTransactions(newTransactions, false);
for(TransactionImpl transaction : blockTransactions) {
transaction.applyUnconfirmed();
}
totalFeeNQT += Subscription.calculateFees(blockTimestamp);
}
finally {
Db.rollbackTransaction();
Db.endTransaction();
}
}
}
//final byte[] publicKey = Crypto.getPublicKey(secretPhrase);
//ATs for block
AT.clearPendingFees();
AT.clearPendingTransactions();
AT_Block atBlock = AT_Controller.getCurrentBlockATs( Constants.MAX_PAYLOAD_LENGTH - payloadLength , previousBlock.getHeight() + 1 );
byte[] byteATs = atBlock.getBytesForBlock();
//digesting AT Bytes
if (byteATs!=null)
{
payloadLength += byteATs.length;
totalFeeNQT += atBlock.getTotalFees();
totalAmountNQT += atBlock.getTotalAmount();
}
//ATs for block
MessageDigest digest = Crypto.sha256();
for (Transaction transaction : blockTransactions) {
digest.update(transaction.getBytes());
}
byte[] payloadHash = digest.digest();
byte[] generationSignature = Nxt.getGenerator().calculateGenerationSignature(previousBlock.getGenerationSignature(), previousBlock.getGeneratorId());
BlockImpl block;
byte[] previousBlockHash = Crypto.sha256().digest(previousBlock.getBytes());
try {
block = new BlockImpl(getBlockVersion(previousBlock.getHeight()), blockTimestamp, previousBlock.getId(), totalAmountNQT, totalFeeNQT, payloadLength,
payloadHash, publicKey, generationSignature, null, previousBlockHash, new ArrayList<>(blockTransactions), nonce, byteATs);
} catch (NxtException.ValidationException e) {
// shouldn't happen because all transactions are already validated
Logger.logMessage("Error generating block", e);
return;
}
block.sign(secretPhrase);
block.setPrevious(previousBlock);
try {
pushBlock(block);
blockListeners.notify(block, Event.BLOCK_GENERATED);
Logger.logDebugMessage("Account " + Convert.toUnsignedLong(block.getGeneratorId()) + " generated block " + block.getStringId()
+ " at height " + block.getHeight());
} catch (TransactionNotAcceptedException e) {
Logger.logDebugMessage("Generate block failed: " + e.getMessage());
Transaction transaction = e.getTransaction();
Logger.logDebugMessage("Removing invalid transaction: " + transaction.getStringId());
transactionProcessor.removeUnconfirmedTransaction((TransactionImpl) transaction);
throw e;
} catch (BlockNotAcceptedException e) {
Logger.logDebugMessage("Generate block failed: " + e.getMessage());
throw e;
}
}
private boolean hasAllReferencedTransactions(Transaction transaction, int timestamp, int count) {
if (transaction.getReferencedTransactionFullHash() == null) {
return timestamp - transaction.getTimestamp() < 60 * 1440 * 60 && count < 10;
}
transaction = TransactionDb.findTransactionByFullHash(transaction.getReferencedTransactionFullHash());
if(!Subscription.isEnabled()) {
if(transaction != null && transaction.getSignature() == null) {
transaction = null;
}
}
return transaction != null && hasAllReferencedTransactions(transaction, timestamp, count + 1);
}
@Override
public void scan(int height) {
synchronized (blockchain) {
TransactionProcessorImpl transactionProcessor = TransactionProcessorImpl.getInstance();
int blockchainHeight = Nxt.getBlockchain().getHeight();
if (height > blockchainHeight + 1) {
throw new IllegalArgumentException("Rollback height " + (height - 1) + " exceeds current blockchain height of " + blockchainHeight);
}
if (height > 0 && height < getMinRollbackHeight()) {
Logger.logMessage("Rollback of more than " + Constants.MAX_ROLLBACK + " blocks not supported, will do a full scan");
height = 0;
}
if (height < 0) {
height = 0;
}
isScanning = true;
Logger.logMessage("Scanning blockchain starting from height " + height + "...");
if (validateAtScan) {
Logger.logDebugMessage("Also verifying signatures and validating transactions...");
}
try (Connection con = Db.beginTransaction();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM block WHERE height >= ? ORDER BY db_id ASC")) {
transactionProcessor.requeueAllUnconfirmedTransactions();
Account.flushAccountTable();
for (DerivedDbTable table : derivedTables) {
if (height == 0) {
table.truncate();
} else {
table.rollback(height - 1);
}
}
pstmt.setInt(1, height);
try (ResultSet rs = pstmt.executeQuery()) {
BlockImpl currentBlock = BlockDb.findBlockAtHeight(height);
blockListeners.notify(currentBlock, Event.RESCAN_BEGIN);
long currentBlockId = currentBlock.getId();
if (height == 0) {
blockchain.setLastBlock(currentBlock); // special case to avoid no last block
//Account.addOrGetAccount(Genesis.CREATOR_ID).apply(Genesis.CREATOR_PUBLIC_KEY, 0);
} else {
blockchain.setLastBlock(BlockDb.findBlockAtHeight(height - 1));
}
while (rs.next()) {
try {
currentBlock = BlockDb.loadBlock(con, rs);
if (currentBlock.getId() != currentBlockId) {
if(currentBlockId == Genesis.GENESIS_BLOCK_ID) {
Logger.logDebugMessage("Wrong genesis block id set. Should be: " + Convert.toUnsignedLong(currentBlock.getId()));
}
throw new NxtException.NotValidException("Database blocks in the wrong order!");
}
if (validateAtScan && currentBlockId != Genesis.GENESIS_BLOCK_ID) {
if (!currentBlock.verifyBlockSignature()) {
throw new NxtException.NotValidException("Invalid block signature");
}
if (!currentBlock.verifyGenerationSignature()) {
throw new NxtException.NotValidException("Invalid block generation signature");
}
if (currentBlock.getVersion() != getBlockVersion(blockchain.getHeight())) {
throw new NxtException.NotValidException("Invalid block version");
}
byte[] blockBytes = currentBlock.getBytes();
JSONObject blockJSON = (JSONObject) JSONValue.parse(currentBlock.getJSONObject().toJSONString());
if (!Arrays.equals(blockBytes, BlockImpl.parseBlock(blockJSON).getBytes())) {
throw new NxtException.NotValidException("Block JSON cannot be parsed back to the same block");
}
for (TransactionImpl transaction : currentBlock.getTransactions()) {
/*if (!transaction.verifySignature()) { // moved to preVerify
throw new NxtException.NotValidException("Invalid transaction signature");
}*/
if(!transaction.verifyPublicKey()) {
throw new NxtException.NotValidException("Wrong transaction public key");
}
if (transaction.getVersion() != transactionProcessor.getTransactionVersion(blockchain.getHeight())) {
throw new NxtException.NotValidException("Invalid transaction version");
}
/*
if (!EconomicClustering.verifyFork(transaction)) {
Logger.logDebugMessage("Found transaction that was generated on a fork: " + transaction.getStringId()
+ " in block " + currentBlock.getStringId() + " at height " + currentBlock.getHeight()
+ " ecBlockHeight " + transaction.getECBlockHeight() + " ecBlockId " + Convert.toUnsignedLong(transaction.getECBlockId()));
//throw new NxtException.NotValidException("Invalid transaction fork");
}
*/
transaction.validate();
byte[] transactionBytes = transaction.getBytes();
if (currentBlock.getHeight() > Constants.NQT_BLOCK
&& !Arrays.equals(transactionBytes, transactionProcessor.parseTransaction(transactionBytes).getBytes())) {
throw new NxtException.NotValidException("Transaction bytes cannot be parsed back to the same transaction");
}
JSONObject transactionJSON = (JSONObject) JSONValue.parse(transaction.getJSONObject().toJSONString());
if (!Arrays.equals(transactionBytes, transactionProcessor.parseTransaction(transactionJSON).getBytes())) {
throw new NxtException.NotValidException("Transaction JSON cannot be parsed back to the same transaction");
}
}
}
blockListeners.notify(currentBlock, Event.BEFORE_BLOCK_ACCEPT);
blockchain.setLastBlock(currentBlock);
accept(currentBlock, null, null);
currentBlockId = currentBlock.getNextBlockId();
Db.commitTransaction();
} catch (NxtException | RuntimeException e) {
Db.rollbackTransaction();
Logger.logDebugMessage(e.toString(), e);
Logger.logDebugMessage("Applying block " + Convert.toUnsignedLong(currentBlockId) + " at height "
+ (currentBlock == null ? 0 : currentBlock.getHeight()) + " failed, deleting from database");
if (currentBlock != null) {
transactionProcessor.processLater(currentBlock.getTransactions());
}
while (rs.next()) {
try {
currentBlock = BlockDb.loadBlock(con, rs);
transactionProcessor.processLater(currentBlock.getTransactions());
} catch (NxtException.ValidationException ignore) {
}
}
BlockDb.deleteBlocksFrom(currentBlockId);
blockchain.setLastBlock(BlockDb.findLastBlock());
}
blockListeners.notify(currentBlock, Event.BLOCK_SCANNED);
}
Db.endTransaction();
blockListeners.notify(currentBlock, Event.RESCAN_END);
}
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
validateAtScan = false;
Logger.logMessage("...done at height " + Nxt.getBlockchain().getHeight());
isScanning = false;
} // synchronized
}
}
|
package nxt.at;
public class AT_Machine_Processor{
protected AT_Machine_State machineData;
private Fun fun = new Fun();
private int getFun(){
if (machineData.getMachineState().pc + 2>=machineData.getCsize())
return -1;
else
{
fun.fun = (machineData.getAp_code()).getShort(machineData.getMachineState().pc+1);
}
return 0;
}
private int getAddr(boolean is_code)
{
if (machineData.getMachineState().pc+4>=machineData.getCsize())
return -1;
else
{
fun.addr1 = (machineData.getAp_code()).getInt((machineData.getAp_code()).position()+machineData.getMachineState().pc+1);
if (!validAddr(fun.addr1, is_code))
return -1;
else
return 0;
}
}
private int getAddrs()
{
if (machineData.getMachineState().pc + 4 + 4>=machineData.getCsize())
return -1;
else
{
fun.addr1 = (machineData.getAp_code()).getInt(machineData.getMachineState().pc+1);
fun.addr2 = (machineData.getAp_code()).getInt(machineData.getMachineState().pc+1+4);
if (!validAddr(fun.addr1, false) || !validAddr(fun.addr2, false))
return -1;
else
return 0;
}
}
private int getAddrOff()
{
if (machineData.getMachineState().pc + 4 + 1>=machineData.getCsize())
return -1;
else
{
fun.addr1 = (machineData.getAp_code()).getInt(machineData.getMachineState().pc+1);
fun.off = (machineData.getAp_code()).get( machineData.getMachineState().pc+1+4);
System.out.println(fun.addr1);
if (!validAddr(fun.addr1, false) ||
!validAddr(machineData.getMachineState().pc+fun.off, true))
return -1;
else
return 0;
}
}
private int getAddrsOff()
{
if (machineData.getMachineState().pc + 4 + 4+1>=machineData.getCsize())
return -1;
else
{
fun.addr1 = (machineData.getAp_code()).getInt(machineData.getMachineState().pc+1);
fun.addr2 = (machineData.getAp_code()).getInt(machineData.getMachineState().pc+1+4);
fun.off = (machineData.getAp_code()).get( machineData.getMachineState().pc+1+4+4);
if (!validAddr(fun.addr1, false) ||
!validAddr(fun.addr2, false) ||
!validAddr(machineData.getMachineState().pc+fun.off, true))
return -1;
else
return 0;
}
}
private int getFunAddr()
{
System.out.println("pc counter: "+machineData.getMachineState().pc);
if (machineData.getMachineState().pc + 4 + 4>=machineData.getCsize())
return -1;
else
{
fun.fun = (machineData.getAp_code()).getShort( machineData.getMachineState().pc+1);
fun.addr1 = (machineData.getAp_code()).getInt((machineData.getMachineState().pc+1+2));
System.out.println("fun: "+fun.fun+" fun.addr1 :"+fun.addr1);
if (!validAddr(fun.addr1, false))
return -1;
else
return 0;
}
}
private int getFunAddrs()
{
if (machineData.getMachineState().pc + 4 + 4 + 2>=machineData.getCsize())
return -1;
else
{
fun.fun = (machineData.getAp_code()).getShort( machineData.getMachineState().pc+1);
fun.addr3 = (machineData.getAp_code()).getInt(machineData.getMachineState().pc+1+2);
fun.addr2 = (machineData.getAp_code()).getInt(machineData.getMachineState().pc+1+2+4);
if (!validAddr(fun.addr3, false) ||
!validAddr(fun.addr2, false))
return -1;
else
return 0;
}
}
private int getAddressVal()
{
if (machineData.getMachineState().pc + 4 + 8>=machineData.getCsize())
return -1;
else
{
fun.addr1 = (machineData.getAp_code()).getInt(machineData.getMachineState().pc+1);
fun.val = (machineData.getAp_code()).getLong(machineData.getMachineState().pc+1+4);
if (!validAddr(fun.addr1, false))
return -1;
else
return 0;
}
}
private boolean validAddr(int addr, boolean is_code)
{
if(addr<0)
return false;
if(!is_code && (((long)addr)*8+8>((long)Integer.MAX_VALUE) ||
addr*8+8>machineData.getDsize()))
return false;
if(is_code && addr>=machineData.getCsize())
return false;
return true;
}
private class Fun
{
short fun;
int addr1;
int addr2;
long val;
byte off;
int addr3;
}
public AT_Machine_Processor( AT_Machine_State machineData )
{
this.machineData = machineData;
//NXT_AT_Controller.dumpBytes(machineData.getAp_code(), 0, machineData.getAp_code().array().length);
}
protected int processOp(boolean disassemble,boolean determine_jumps) {
int rc = 0;
if (machineData.getCsize()<1 || machineData.getMachineState().pc>=machineData.getCsize())
return 0;
if (determine_jumps)
{
machineData.getMachineState().jumps.add(machineData.getMachineState().pc);
}
byte op = (machineData.getAp_code()).get(machineData.getMachineState().pc);
System.out.println("OpCode : "+op);
if (op>0 && disassemble && !determine_jumps)
{
System.out.print(String.format("%8x", machineData.getMachineState().pc).replace(' ', '0'));
if (machineData.getMachineState().pc == machineData.getMachineState().opc)
System.out.print("* ");
else
System.out.print(" ");
}
if ( op == OpCode.e_op_code_NOP){
if ( disassemble ){
if (! determine_jumps )
System.out.println("NOP");
++rc;
}
else while (true){
++rc;
++machineData.getMachineState().pc;
if (machineData.getMachineState().pc>=machineData.getCsize() || (machineData.getAp_code()).get(machineData.getMachineState().pc) != OpCode.e_op_code_NOP)
break;
}
}
else if ( op == OpCode.e_op_code_SET_VAL)
{
rc = getAddressVal();
if (rc==0 || disassemble)
{
rc = 1 + 4 + 8;
if (disassemble)
{
if (!determine_jumps)
System.out.println("SET @"+String.format("%8s",fun.addr1).replace(' ','0')+" "+String.format("#%16s",Long.toHexString(fun.val)).replace(' ', '0'));
}
else
{
machineData.getMachineState().pc += rc;
machineData.getAp_data().putLong(fun.addr1*8,fun.val);
machineData.getAp_data().clear();
}
}
}
else if (op== OpCode.e_op_code_SET_DAT)
{
rc = getAddrs();
if (rc==0 || disassemble)
{
rc = 1+4+4;
if (disassemble)
{
if (!determine_jumps)
System.out.println( "SET @"+String.format("%8s", fun.addr1).replace(' ', '0')+
" $"+String.format("%8s",fun.addr2).replace(' ', '0'));
}
else
{
machineData.getMachineState().pc+=rc;
machineData.getAp_data().putLong(fun.addr1*8,machineData.getAp_data().getLong(fun.addr2*8));
machineData.getAp_data().clear();
}
}
}
else if( op == OpCode.e_op_code_CLR_DAT )
{
rc = getAddr(false );
if( rc == 0 || disassemble)
{
rc = 1 + 4;
if( disassemble )
{
if( !determine_jumps )
System.out.println("CLR @"+String.format("%8s",fun.addr1));
}
else
{
machineData.getMachineState().pc = rc;
machineData.getAp_data().putLong( fun.addr1*8,(long)0);
machineData.getAp_data().clear();
}
}
}
else if (op==OpCode.e_op_code_INC_DAT||op==OpCode.e_op_code_DEC_DAT||op==OpCode.e_op_code_NOT_DAT)
{
rc = getAddr(false);
if (rc==0 || disassemble)
{
rc = 1+4;
if (disassemble )
{
if (!determine_jumps)
{
if (op==OpCode.e_op_code_INC_DAT)
{
System.out.print("INC @");
}
else if (op==OpCode.e_op_code_DEC_DAT)
{
System.out.print("DEC @");
}
else if (op==OpCode.e_op_code_NOT_DAT)
{
System.out.print("NOT @");
}
System.out.println(String.format("%8", fun.addr1).replace(' ', '0'));
}
}
else
{
machineData.getMachineState().pc +=rc;
if (op==OpCode.e_op_code_INC_DAT)
{
long incData = machineData.getAp_data().getLong((fun.addr1*8));
incData++;
machineData.getAp_data().putLong((fun.addr1*8), incData);
machineData.getAp_data().clear();
}
else if (op==OpCode.e_op_code_DEC_DAT)
{
long incData = machineData.getAp_data().getLong((fun.addr1*8));
incData
machineData.getAp_data().putLong((fun.addr1*8), incData);
machineData.getAp_data().clear();
}
else if (op==OpCode.e_op_code_NOT_DAT)
{
long incData = machineData.getAp_data().getLong((fun.addr1*8));
machineData.getAp_data().putLong((fun.addr1*8), ~incData);
machineData.getAp_data().clear();
}
}
}
}
else if (op==OpCode.e_op_code_ADD_DAT||op==OpCode.e_op_code_SUB_DAT||op==OpCode.e_op_code_MUL_DAT||op==OpCode.e_op_code_DIV_DAT)
{
rc = getAddrs();
if (rc==0 || disassemble)
{
rc = 1+4+4;
if (disassemble)
{
if (!determine_jumps)
{
if (op==OpCode.e_op_code_ADD_DAT)
{
System.out.print("ADD @");
}
else if (op==OpCode.e_op_code_SUB_DAT)
{
System.out.print("SUB @");
}
else if (op==OpCode.e_op_code_MUL_DAT)
{
System.out.print("MUL @");
}
else if (op==OpCode.e_op_code_DIV_DAT)
{
System.out.print("DIV @");
}
System.out.println(String.format("%8x", fun.addr1).replace(' ', '0')+" $"+String.format("%8s", fun.addr2).replace(' ','0'));
}
}
else
{
long val = machineData.getAp_data().getLong( fun.addr2*8);
if (op==OpCode.e_op_code_DIV_DAT && val==0)
rc=-2;
else
{
machineData.getMachineState().pc+=rc;
if (op==OpCode.e_op_code_ADD_DAT)
{
long addData1 = machineData.getAp_data().getLong((fun.addr1*8));
long addData2 = machineData.getAp_data().getLong((fun.addr2*8));
machineData.getAp_data().putLong((fun.addr1*8), addData1+addData2);
machineData.getAp_data().clear();
}
else if (op==OpCode.e_op_code_SUB_DAT)
{
long addData1 = machineData.getAp_data().getLong((fun.addr1*8));
long addData2 = machineData.getAp_data().getLong((fun.addr2*8));
machineData.getAp_data().putLong((fun.addr1*8), addData1-addData2);
machineData.getAp_data().clear();
}
else if (op==OpCode.e_op_code_MUL_DAT)
{
long addData1 = machineData.getAp_data().getLong((fun.addr1*8));
long addData2 = machineData.getAp_data().getLong((fun.addr2*8));
machineData.getAp_data().putLong((fun.addr1*8), addData1*addData2);
machineData.getAp_data().clear();
}
else if (op==OpCode.e_op_code_DIV_DAT)
{
long addData1 = machineData.getAp_data().getLong((fun.addr1*8));
long addData2 = machineData.getAp_data().getLong((fun.addr2*8));
machineData.getAp_data().putLong((fun.addr1*8), addData1/addData2);
machineData.getAp_data().clear();
}
}
}
}
}
else if (op==OpCode.e_op_code_BOR_DAT||op==OpCode.e_op_code_AND_DAT||op==OpCode.e_op_code_XOR_DAT)
{
rc = getAddrs();
if (rc==0 || disassemble)
{
rc = 1+4+4;
if (disassemble)
{
if (!determine_jumps)
{
if (op==OpCode.e_op_code_BOR_DAT)
{
System.out.print("BOR @");
}
else if (op==OpCode.e_op_code_AND_DAT)
{
System.out.print("AND @");
}
else if (op==OpCode.e_op_code_XOR_DAT)
{
System.out.print("XOR @");
}
System.out.println(String.format("%16s $%16s", fun.addr1,fun.addr2).replace(' ', '0'));
}
}
else
{
machineData.getMachineState().pc +=rc;
long val = machineData.getAp_data().getLong( fun.addr2*8);
if (op==OpCode.e_op_code_BOR_DAT)
{
long incData = machineData.getAp_data().getLong((fun.addr1*8));
machineData.getAp_data().putLong((fun.addr1*8), incData|val);
machineData.getAp_data().clear();
}
else if (op==OpCode.e_op_code_AND_DAT)
{
long incData = machineData.getAp_data().getLong((fun.addr1*8));
machineData.getAp_data().putLong((fun.addr1*8), incData&val);
machineData.getAp_data().clear();
}
else if (op==OpCode.e_op_code_XOR_DAT)
{
long incData = machineData.getAp_data().getLong((fun.addr1*8));
machineData.getAp_data().putLong((fun.addr1*8), incData^val);
machineData.getAp_data().clear();
}
}
}
}
else if (op==OpCode.e_op_code_IND_DAT)
{
rc = getAddrs();
if (rc==0)
{
rc = 1+4+4;
if (disassemble)
{
if (!determine_jumps)
System.out.println("SET @"+
String.format("%8s",fun.addr1).replace(' ', '0')+" "+
String.format("$($%8s",fun.addr2).replace(' ', '0'));
}
else
{
long addr = machineData.getAp_data().getLong( fun.addr2*8);
if (!validAddr((int)addr, false))
rc=-1;
else
{
machineData.getMachineState().pc+=rc;
long val = machineData.getAp_data().getLong( (int)addr*8 );
machineData.getAp_data().putLong(fun.addr1*8, val);
machineData.getAp_data().clear();
}
}
}
}
else if ( op == OpCode.e_op_code_IDX_DAT) {
int addr1,addr2;
rc=getAddrs();
addr1=fun.addr1;
addr2=fun.addr2;
int size = 4 + 4;
if (rc==0 || disassemble){
(machineData.getAp_code()).position(size);
rc = getAddr( false );
(machineData.getAp_code()).position((machineData.getAp_code()).position()-size);
if (rc==0 || disassemble){
rc=13;
if (disassemble){
if (!determine_jumps)
System.out.println("");
}
else
{
long base=machineData.getAp_data().getLong( addr2*8);
long offs=machineData.getAp_data().getLong( fun.addr1*8);
long addr=base+offs;
System.out.println(fun.addr1);
if (!validAddr((int)addr, false))
rc=-1;
else
{
machineData.getMachineState().pc+=rc;
machineData.getAp_data().putLong(addr1*8,machineData.getAp_data().getLong((int)addr*8));
machineData.getAp_data().clear();
}
}
}
}
}
else if (op==OpCode.e_op_code_PSH_DAT||op==OpCode.e_op_code_POP_DAT)
{
rc = getAddr(false);
if (rc==0 || disassemble)
{
rc = 1 + 4;
if (disassemble)
{
if (!determine_jumps)
{
if (op==OpCode.e_op_code_PSH_DAT)
System.out.print("PSH $");
else
System.out.print("POP @");
System.out.println(String.format("%8s",fun.addr1).replace(' ', '0'));
}
}
else if ((op==OpCode.e_op_code_PSH_DAT&&machineData.getMachineState().us==(machineData.getC_user_stack_bytes()/8))||
(op==OpCode.e_op_code_POP_DAT && machineData.getMachineState().us==0))
{
rc=-1;
}
else
{
machineData.getMachineState().pc+=rc;
if (op==OpCode.e_op_code_PSH_DAT)
{
long val = machineData.getAp_data().getLong(fun.addr1*8);
machineData.getMachineState().us++;
machineData.getAp_data().putLong(machineData.getDsize()+machineData.getC_call_stack_bytes()+machineData.getC_user_stack_bytes()-((machineData.getMachineState().us)*8), val);
machineData.getAp_data().clear();
}
else
{
machineData.getMachineState().us
long val = machineData.getAp_data().getLong(machineData.getDsize()+machineData.getC_call_stack_bytes()+machineData.getC_user_stack_bytes()-(machineData.getMachineState().us*8));
machineData.getAp_data().putLong(fun.addr1*8, val);
machineData.getAp_data().clear();
}
}
}
}
else if( op == OpCode.e_op_code_JMP_SUB )
{
rc = getAddr(true);
if( rc == 0 || disassemble)
{
rc = 1 + 4;
if( disassemble )
{
if( !determine_jumps )
System.out.println("JSR :"+String.format("%8s", fun.addr1).replace(' ', '0'));
}
else
{
if( machineData.getMachineState().cs == ( machineData.getC_call_stack_bytes() / 8 ) )
rc = -1;
else if( machineData.getMachineState().jumps.contains(fun.addr1) )
{
machineData.getMachineState().cs++;
machineData.getAp_data().putLong( machineData.getDsize()+machineData.getC_call_stack_bytes()-(machineData.getMachineState().cs*8), (long)(machineData.getMachineState().pc+rc));
machineData.getAp_data().clear();
machineData.getMachineState().pc = fun.addr1;
}
else
rc = -2;
}
}
}
else if( op == OpCode.e_op_code_RET_SUB )
{
rc = 1;
if( disassemble )
{
if( !determine_jumps )
System.out.println("RET\n");
}
else
{
if( machineData.getMachineState().cs == 0 )
rc = -1;
else
{
long val = machineData.getAp_data().getLong( machineData.getDsize()+machineData.getC_call_stack_bytes()-machineData.getMachineState().cs*8);
machineData.getMachineState().cs
int addr = (int)val;
if( machineData.getMachineState().jumps.contains(addr ) )
machineData.getMachineState().pc = addr;
else
rc = -2;
}
}
}
else if (op==OpCode.e_op_code_SET_IND)
{
rc = getAddrs();
if (rc==0)
{
rc = 1+4+4;
if (disassemble)
{
if(!determine_jumps)
System.out.println("SET @"+
String.format("($%8s)", fun.addr1).replace(' ', '0')+" "+
String.format("$%8s", fun.addr2).replace(' ', '0'));
}
else
{
long addr = machineData.getAp_data().getLong( fun.addr1*8 );
if (!validAddr((int)addr, false))
rc=-1;
else
{
machineData.getMachineState().pc+=rc;
machineData.getAp_data().putLong((int)addr*8, machineData.getAp_data().getLong((int)fun.addr2*8));
machineData.getAp_data().clear();
}
}
}
}
else if (op == OpCode.e_op_code_SET_IDX)
{
int addr1,addr2;
rc = getAddrs();
addr1 = fun.addr1;
addr2 = fun.addr2;
int size = 4 + 4;
if (rc==0 || disassemble)
{
(machineData.getAp_code()).position(size);
rc = getAddr(false);
(machineData.getAp_code()).position((machineData.getAp_code()).position()-size);
if (rc==0 || disassemble)
{
rc=13;
if (disassemble)
{
if (!determine_jumps)
System.out.println("SET @"+
String.format("($%8s+$%8s)", addr1, addr2).replace(' ', '0')+" "+
String.format("$%8s", fun.addr1).replace(' ', '0'));
}
else
{
long addr = addr1+addr2;
if(!validAddr((int)addr, false))
rc=-1;
else
{
machineData.getMachineState().pc+=rc;
machineData.getAp_data().putLong((int)addr*8, machineData.getAp_data().getLong((int)fun.addr1*8));
machineData.getAp_data().clear();
}
}
}
}
}
else if( op == OpCode.e_op_code_JMP_ADR )
{
rc = getAddr(true);
if( rc == 0 || disassemble)
{
rc = 1 + 4;
if( disassemble )
{
if( !determine_jumps )
System.out.println("JMP :"+String.format("%8x",fun.addr1));
}
else if( machineData.getMachineState().jumps.contains( fun.addr1 ) )
machineData.getMachineState().pc = fun.addr1;
else
rc = -2;
}
}
else if( op == OpCode.e_op_code_BZR_DAT || op == OpCode.e_op_code_BNZ_DAT )
{
rc = getAddrOff();
if( rc == 0 || disassemble)
{
rc = 1 + 4 + 1;
if( disassemble )
{
if( !determine_jumps )
{
if( op == OpCode.e_op_code_BZR_DAT )
System.out.print("BZR $");
else
System.out.print("BNZ $");
System.out.println(String.format("%8x",fun.addr1).replace(' ', '0')+", :"+String.format("%8x", machineData.getMachineState().pc+fun.off).replace(' ','0'));
}
}
else
{
long val = machineData.getAp_data().getLong( fun.addr1*8);
if( ( op == OpCode.e_op_code_BZR_DAT && val == 0 )
|| ( op == OpCode.e_op_code_BNZ_DAT && val != 0 ) )
{
if( machineData.getMachineState().jumps.contains( machineData.getMachineState().pc + fun.off ) )
machineData.getMachineState().pc += fun.off;
else
rc = -2;
}
else
machineData.getMachineState().pc += rc;
}
}
}
else if( op == OpCode.e_op_code_BGT_DAT || op == OpCode. e_op_code_BLT_DAT
|| op == OpCode. e_op_code_BGE_DAT || op == OpCode. e_op_code_BLE_DAT
|| op == OpCode. e_op_code_BEQ_DAT || op == OpCode. e_op_code_BNE_DAT )
{
rc = getAddrsOff();
if( rc == 0 || disassemble )
{
rc = 1 + 4 + 4 + 1;
if( disassemble )
{
if( !determine_jumps )
{
if( op == OpCode. e_op_code_BGT_DAT )
System.out.print("BGT $");
else if( op == OpCode. e_op_code_BLT_DAT )
System.out.print("BLT $");
else if( op == OpCode. e_op_code_BGE_DAT )
System.out.print("BGE $");
else if( op == OpCode. e_op_code_BLE_DAT )
System.out.print("BLE $");
else if( op == OpCode. e_op_code_BEQ_DAT )
System.out.print("BEQ $");
else
System.out.print("BNE $");
System.out.println(String.format("%8x",fun.addr1).replace(' ','0')+
" $"+String.format("%8x",fun.addr2).replace(' ','0')+
" :"+String.format("%8x",machineData.getMachineState().pc+fun.off).replace(' ','0'));
}
}
else
{
long val1 = machineData.getAp_data().getLong( fun.addr1*8);
long val2 = machineData.getAp_data().getLong( fun.addr2*8);
if( ( op == OpCode. e_op_code_BGT_DAT && val1 > val2 )
|| ( op == OpCode. e_op_code_BLT_DAT && val1 < val2 )
|| ( op == OpCode. e_op_code_BGE_DAT && val1 >= val2 )
|| ( op == OpCode. e_op_code_BLE_DAT && val1 <= val2 )
|| ( op == OpCode. e_op_code_BEQ_DAT && val1 == val2 )
|| ( op == OpCode. e_op_code_BNE_DAT && val1 != val2 ) )
{
if( machineData.getMachineState().jumps.contains( machineData.getMachineState().pc + fun.off ) )
machineData.getMachineState().pc +=fun.off;
else
rc = -2;
}
else
machineData.getMachineState().pc += rc;
}
}
}
else if( op == OpCode.e_op_code_SLP_DAT )
{
rc = getAddr( true );
if ( rc==0 || disassemble )
{
rc = 1 + 4;
if ( disassemble )
{
if ( !determine_jumps )
System.out.println("SLP @"+String.format("%8x",fun.addr1));
}
else
{
machineData.getMachineState().pc += rc;
int numBlocks = (int)machineData.getAp_data().getLong((int)fun.addr1*8);
if(numBlocks < 0)
numBlocks = 0;
int maxNumBlocks = (int)AT_Constants.getInstance().get_MAX_WAIT_FOR_NUM_OF_BLOCKS(machineData.getCreationBlockHeight());
if(numBlocks > maxNumBlocks)
numBlocks = maxNumBlocks;
machineData.setWaitForNumberOfBlocks(numBlocks);
machineData.getMachineState().stopped = true;
}
}
/*int addr1,addr2;
rc = getAddrs();
addr1 = fun.addr1;
addr2 = fun.addr2;
int size = 4 + 4;
if( rc == 0 || disassemble)
{
(machineData.getAp_code()).position(size);
rc = getAddr( true );
(machineData.getAp_code()).position((machineData.getAp_code()).position()-size);
if( rc == 0 )
{
rc = 1 + size + 4;
if( disassemble )
{
if( !determine_jumps )
System.out.println("SLE @"+String.format("%8x", addr1).replace(' ','0')+
" $"+String.format("%8x", addr2).replace(' ','0')+
" :"+String.format("%8x", fun.addr1).replace(' ','0'));
}
else
{
long val1 = machineData.getAp_data().getLong( addr1*8);
long val2 = machineData.getAp_data().getLong( addr2*8);
machineData.getAp_data().putLong( addr1*8,val1-val2);
machineData.getAp_data().clear();
if( machineData.getAp_data().getLong( addr1*8) <= 0 )
{
if( machineData.getMachineState().jumps.contains( fun.addr1 ) )
machineData.getMachineState().pc = fun.addr1;
else
rc = -2;
}
else
machineData.getMachineState().pc += rc;
}
}
}*/
}
else if( op == OpCode.e_op_code_FIZ_DAT || op == OpCode.e_op_code_STZ_DAT )
{
rc = getAddr(false );
if( rc == 0 || disassemble)
{
rc = 1 + 4;
if( disassemble )
{
if( !determine_jumps )
{
if( op == OpCode.e_op_code_FIZ_DAT )
System.out.print("FIZ @");
else
System.out.print("STZ @");
System.out.println(String.format("%8x",fun.addr1).replace(' ', '0'));
}
}
else
{
if(machineData.getAp_data().getLong( fun.addr1*8) == 0 )
{
if( op == OpCode.e_op_code_STZ_DAT )
{
machineData.getMachineState().pc += rc;
machineData.getMachineState().stopped = true;
machineData.setFreeze( true );
}
else
{
machineData.getMachineState().pc = machineData.getMachineState().pcs;
machineData.getMachineState().finished = true;
machineData.setFreeze( true );
}
}
else
{
rc = 1 + 4;
machineData.getMachineState().pc += rc;
}
}
}
}
else if( op == OpCode.e_op_code_FIN_IMD || op == OpCode.e_op_code_STP_IMD )
{
rc = 1;
if( disassemble )
{
if( !determine_jumps )
{
if( op == OpCode.e_op_code_FIN_IMD )
System.out.println("FIN\n");
else
System.out.println("STP");
}
}
else if( op == OpCode.e_op_code_STP_IMD )
{
machineData.getMachineState().pc += rc;
machineData.getMachineState().stopped = true;
machineData.setFreeze( true );
}
else
{
machineData.getMachineState().pc = machineData.getMachineState().pcs;
machineData.getMachineState().finished = true;
machineData.setFreeze( true );
}
}
else if ( op == OpCode.e_op_code_SLP_IMD )
{
rc = 1;
if( disassemble )
{
if( !determine_jumps )
{
System.out.println("SLP\n");
}
}
else
{
machineData.getMachineState().pc += rc;
machineData.getMachineState().stopped = true;
machineData.setFreeze( true );
}
}
else if( op == OpCode.e_op_code_SET_PCS )
{
rc = 1;
if( disassemble )
{
if( !determine_jumps )
System.out.println("PCS");
}
else
{
machineData.getMachineState().pc += rc;
machineData.getMachineState().pcs = machineData.getMachineState().pc;
}
}
else if( op == OpCode.e_op_code_EXT_FUN )
{
rc = getFun();
if( rc == 0 || disassemble)
{
rc = 1 + 2;
if( disassemble )
{
if( !determine_jumps )
System.out.println("FUN "+fun.fun);
}
else
{
machineData.getMachineState().pc += rc;
AT_API_Controller.func( fun.fun , machineData );
}
}
}
else if( op == OpCode.e_op_code_EXT_FUN_DAT )
{
rc = getFunAddr();
if( rc == 0 )
{
rc = 1 + 2 + 4;
if( disassemble )
{
if( !determine_jumps )
System.out.println( "FUN "+fun.fun+" $"+
String.format( "%8x", fun.addr1 ).replace( ' ','0' ) );
}
else
{
machineData.getMachineState().pc += rc;
long val = (machineData.getAp_data()).getLong( fun.addr1*8 );
AT_API_Controller.func1( fun.fun, val, machineData );
}
}
}
else if( op == OpCode.e_op_code_EXT_FUN_DAT_2 )
{
rc = getFunAddrs();
if( rc == 0 || disassemble)
{
rc = 1 + 2 + 4 + 4;
if( disassemble )
{
if( !determine_jumps )
System.out.println("FUN "+fun.fun+" $"+
String.format("%8x",fun.addr3).replace(' ','0')+
" $"+
String.format("%8x",fun.addr2).replace(' ','0'));
}
else
{
machineData.getMachineState().pc += rc;
long val1 = machineData.getAp_data().getLong( ( fun.addr3 * 8 ) );
long val2 = machineData.getAp_data().getLong( ( fun.addr2 * 8 ) );
AT_API_Controller.func2( fun.fun, val1, val2 ,machineData);
}
}
}
else if( op == OpCode.e_op_code_EXT_FUN_RET )
{
rc = getFunAddr();
if( rc == 0 || disassemble)
{
rc = 1 + 2 + 4;
if( disassemble )
{
if( !determine_jumps )
System.out.println("FUN @"+
String.format("%8x", fun.addr1).replace(' ', '0')+" "+fun.fun);
}
else
{
machineData.getMachineState().pc += rc;
machineData.getAp_data().putLong( fun.addr1*8,AT_API_Controller.func(fun.fun,machineData));
machineData.getAp_data().clear();
}
}
}
else if( op == OpCode.e_op_code_EXT_FUN_RET_DAT || op == OpCode.e_op_code_EXT_FUN_RET_DAT_2 )
{
rc = getFunAddrs();
int size = 2 + 4 + 4;
if( (rc == 0 || disassemble )&& op == OpCode.e_op_code_EXT_FUN_RET_DAT_2 )
{
(machineData.getAp_code()).position(size);
rc = getAddr( false );
(machineData.getAp_code()).position((machineData.getAp_code()).position()-size);
}
if( rc == 0 )
{
rc = 1 + size + (( op == OpCode.e_op_code_EXT_FUN_RET_DAT_2) ? 4 : 0) ;
if( disassemble )
{
if( !determine_jumps )
{
System.out.print("FUN @"+String.format("%8x",fun.addr3).replace(' ','0')+" "+fun.fun+" $"+String.format("%8x", fun.addr2).replace(' ','0'));
if( op == OpCode.e_op_code_EXT_FUN_RET_DAT_2 )
System.out.print(" $"+String.format("%8x", fun.addr1).replace(' ','0'));
System.out.println("");
}
}
else
{
machineData.getMachineState().pc += rc;
long val = machineData.getAp_data().getLong( ( fun.addr2 * 8 ) );
if( op != OpCode.e_op_code_EXT_FUN_RET_DAT_2 )
machineData.getAp_data().putLong( ( fun.addr3 * 8 ),AT_API_Controller.func1( fun.fun, val,machineData));
else
{
long val2 = machineData.getAp_data().getLong( ( fun.addr1 * 8 ) );
machineData.getAp_data().putLong( ( fun.addr3 * 8 ), AT_API_Controller.func2( fun.fun, val, val2,machineData ));
}
machineData.getAp_data().clear();
}
}
}
else if( op == OpCode.e_op_code_ERR_ADR )
{
rc = getAddr(true);
// don't check rc to allow for unsetting handler with -1
rc = 1 + 4;
if( disassemble )
{
if( !determine_jumps )
System.out.println("ERR :"+String.format("%8x",fun.addr1));
}
else
{
if( fun.addr1 == -1 || machineData.getMachineState().jumps.contains( fun.addr1 ))
{
machineData.getMachineState().pc += rc;
machineData.getMachineState().err = fun.addr1;
}
else
rc = -2;
}
}
else
{
if( !disassemble )
rc = -2;
}
if( rc == -1 && disassemble && !determine_jumps )
System.out.println("\n(overflow)");
if( rc == -2 && disassemble && !determine_jumps )
System.out.println("\n(invalid op)");
/*if( rc >= 0 )
++machineData.getMachineState().steps;
*/
return rc;
}
}
|
package org.sqsh.commands;
import static org.sqsh.options.ArgumentRequired.NONE;
import static org.sqsh.options.ArgumentRequired.REQUIRED;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.sqsh.BufferManager;
import org.sqsh.Buffer;
import org.sqsh.CannotSetValueError;
import org.sqsh.Command;
import org.sqsh.DatabaseCommand;
import org.sqsh.RendererManager;
import org.sqsh.SQLRenderer;
import org.sqsh.SQLTools;
import org.sqsh.Session;
import org.sqsh.SqshOptions;
import org.sqsh.options.Argv;
import org.sqsh.options.Option;
/**
* This command is use only by me (Scott) for testing some application
* code that is specific to the company that I work for. This command
* takes the SQL that is about to be executed and wraps it into a
* stored procedure call called ACS_REPOS.TRANSLATE_AND_EXECUTE.
*/
public class Translate
extends Go
implements DatabaseCommand {
private static class Options
extends Go.Options {
@Option(
option='s', longOption="spid", arg=REQUIRED, argName="spid",
description="Sets the sysprocesses spid number of the client")
public int spid = 0;
}
public SqshOptions getOptions() {
return new Options();
}
/**
* Used internally to "login" to the Sybase world.
*
* @param session Jsqsh session handle.
* @return spid The spid assigned to the connection. -1 is returned
* if a spid could not be established.
*/
private int login(Session session) {
Connection conn = session.getSQLContext().getConnection();
CallableStatement stmt = null;
ResultSet results = null;
boolean done = false;
int spid = -1;
try {
stmt = conn.prepareCall("{call acs_repos.acs_login(?)}");
stmt.registerOutParameter(1, java.sql.Types.SMALLINT);
stmt.execute();
while (!done) {
results = stmt.getResultSet();
if (results != null)
{
while (results.next()) {
/* Discard results */
}
}
else {
if (stmt.getUpdateCount() < 0) {
done = true;
}
else {
stmt.getMoreResults();
}
}
}
spid = stmt.getShort(1);
}
catch (SQLException e) {
SQLTools.printException(session.err, e);
}
finally {
if (stmt != null) {
SQLTools.close(stmt);
}
}
return spid;
}
public int execute (Session session, SqshOptions opts)
throws Exception {
BufferManager bufferMan = session.getBufferManager();
SQLRenderer sqlRenderer = session.getSQLRenderer();
Buffer buffer = bufferMan.getCurrent();
String sql = buffer.toString();
StringBuilder call = new StringBuilder();
int spid = ((Options)opts).spid;
/*
* If we weren't force-fed a spid, then see if we have one
* established.
*/
if (spid == 0) {
String str = session.getVariable("acs_spid");
if (str != null) {
spid = Integer.valueOf(str);
}
else {
spid = login(session);
if (spid < 0) {
return 1;
}
session.setVariable("acs_spid", Integer.toString(spid));
}
}
/*
* We need to protect any quotes that are in the original SQL.
*/
int start = 0;
int end = sql.indexOf('\'');
if (end >= 0) {
StringBuilder sb = new StringBuilder();
while (end >= 0) {
sb.append(sql, start, end + 1);
sb.append('\'');
start = end + 1;
end = sql.indexOf('\'', start);
}
if (start < sql.length()) {
sb.append(sql, start, sql.length());
}
sql = sb.toString();
}
call.append("CALL ACS_REPOS.TRANSLATE_AND_EXECUTE(").append(spid);
start = 0;
boolean done = false;
int chunk = 0;
while (!done) {
++chunk;
end = sql.length();
if ((end - start) > 30000) {
end = start + 30000;
}
call.append(", '");
if (start == 0
&& end == sql.length()) {
call.append(sql);
}
else {
call.append(sql, start, end);
}
call.append('\'');
if (end == sql.length()) {
done = true;
}
}
if (chunk > 10) {
session.err.println("SQL is too large for translation\n");
}
call.append(")");
buffer.clear();
buffer.add(call.toString());
return super.execute(session, opts);
}
}
|
package jmetest.renderer;
import com.jme.app.SimpleGame;
import com.jme.bounding.BoundingBox;
import com.jme.image.Texture;
import com.jme.math.Vector3f;
import com.jme.scene.Node;
import com.jme.scene.shape.Box;
import com.jme.scene.state.TextureState;
import com.jme.util.TextureManager;
import com.jme.renderer.Renderer;
import com.jme.scene.state.MaterialState;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.state.AlphaState;
import com.jme.scene.state.ZBufferState;
import com.jme.scene.state.LightState;
import com.jme.light.AmbientLight;
import com.jme.light.DirectionalLight;
import com.jme.input.KeyBindingManager;
import com.jme.input.KeyInput;
import com.jme.scene.shape.Quad;
import com.jme.scene.Spatial;
import com.jme.scene.state.RenderState;
/**
* <code>TestRenderQueue</code>
* @author Joshua Slack
* @version $Id: TestRenderQueue.java,v 1.4 2004-06-18 17:55:09 renanse Exp $
*/
public class TestRenderQueue extends SimpleGame {
private boolean useQueue = false;
protected Node opaques, transps, orthos;
/**
* Entry point for the test,
* @param args
*/
public static void main(String[] args) {
TestRenderQueue app = new TestRenderQueue();
app.setDialogBehaviour(ALWAYS_SHOW_PROPS_DIALOG);
app.start();
}
protected void simpleUpdate() {
if (KeyBindingManager.getKeyBindingManager().isValidCommand("queue", false)) {
if (useQueue) {
display.setTitle("Test Render Queue - off - hit Q to toggle Queue mode");
transps.setRenderQueueMode(Renderer.QUEUE_SKIP);
opaques.setRenderQueueMode(Renderer.QUEUE_SKIP);
orthos.setRenderQueueMode(Renderer.QUEUE_SKIP);
} else {
display.setTitle("Test Render Queue - on - hit Q to toggle Queue mode");
transps.setRenderQueueMode(Renderer.QUEUE_TRANSPARENT);
opaques.setRenderQueueMode(Renderer.QUEUE_OPAQUE);
orthos.setRenderQueueMode(Renderer.QUEUE_ORTHO);
}
useQueue = !useQueue;
}
}
protected void simpleRender() {
display.getRenderer().setOrthoCenter();
display.getRenderer().draw(orthos);
display.getRenderer().unsetOrtho();
display.getRenderer().draw(transps);
display.getRenderer().draw(opaques);
}
protected void simpleInitGame() {
display.setTitle("Test Render Queue - off - hit Q to toggle Queue mode");
KeyBindingManager.getKeyBindingManager().set("queue", KeyInput.KEY_Q);
cam.setLocation(new Vector3f(10, 0, 50));
cam.update();
Vector3f max = new Vector3f(5, 5, 5);
Vector3f min = new Vector3f( -5, -5, -5);
opaques = new Node("Opaques");
transps = new Node("Transps");
orthos = new Node("Orthos");
transps.setRenderQueueMode(Renderer.QUEUE_SKIP);
opaques.setRenderQueueMode(Renderer.QUEUE_SKIP);
orthos.setRenderQueueMode(Renderer.QUEUE_SKIP);
rootNode.attachChild(orthos);
rootNode.attachChild(transps);
rootNode.attachChild(opaques);
Box b1 = new Box("Box", min, max);
b1.setModelBound(new BoundingBox());
b1.updateModelBound();
b1.setLocalTranslation(new Vector3f(0, 0, -15));
opaques.attachChild(b1);
Box b2 = new Box("Box", min, max);
b2.setModelBound(new BoundingBox());
b2.updateModelBound();
b2.setLocalTranslation(new Vector3f(0, 0, -30));
opaques.attachChild(b2);
Box b3 = new Box("Box", min, max);
b3.setModelBound(new BoundingBox());
b3.updateModelBound();
b3.setLocalTranslation(new Vector3f(0, -15, -15));
opaques.attachChild(b3);
TextureState ts = display.getRenderer().getTextureState();
ts.setEnabled(true);
ts.setTexture(
TextureManager.loadTexture(
TestRenderQueue.class.getClassLoader().getResource(
"jmetest/data/images/Monkey.tga"),
Texture.MM_LINEAR,
Texture.FM_LINEAR,
true));
opaques.setRenderState(ts);
LightState ls = display.getRenderer().getLightState();
ls.setEnabled(true);
DirectionalLight dLight = new DirectionalLight();
dLight.setEnabled(true);
dLight.setDiffuse(new ColorRGBA(1,1,1,1));
dLight.setDirection(new Vector3f(-1,-1,-1));
ls.attach(dLight);
DirectionalLight dLight2 = new DirectionalLight();
dLight2.setEnabled(true);
dLight2.setDiffuse(new ColorRGBA(1,1,1,1));
dLight2.setDirection(new Vector3f(1,1,1));
ls.attach(dLight2);
ls.setTwoSidedLighting(false);
Box tb1 = new Box("TBox Blue", min, max);
tb1.setModelBound(new BoundingBox());
tb1.updateModelBound();
tb1.setLocalTranslation(new Vector3f(0, 15, 15));
transps.attachChild(tb1);
MaterialState ms1 = display.getRenderer().getMaterialState();
ms1.setEnabled(true);
ms1.setDiffuse(new ColorRGBA(0,0,1,.75f));
ms1.setShininess(128);
tb1.setRenderState(ls);
tb1.setRenderState(ms1);
tb1.setLightCombineMode(LightState.REPLACE);
Box tb2 = new Box("TBox Green", min, max);
tb2.setModelBound(new BoundingBox());
tb2.updateModelBound();
tb2.setLocalTranslation(new Vector3f(0, 0, 30));
transps.attachChild(tb2);
MaterialState ms2 = display.getRenderer().getMaterialState();
ms2.setEnabled(true);
ms2.setDiffuse(new ColorRGBA(0,1,0,.75f));
ms2.setShininess(128);
tb2.setRenderState(ls);
tb2.setRenderState(ms2);
tb2.setLightCombineMode(LightState.REPLACE);
Box tb3 = new Box("TBox Red", min, max);
tb3.setModelBound(new BoundingBox());
tb3.updateModelBound();
tb3.setLocalTranslation(new Vector3f(0, 0, 15));
transps.attachChild(tb3);
MaterialState ms3 = display.getRenderer().getMaterialState();
ms3.setEnabled(true);
ms3.setDiffuse(new ColorRGBA(1,0,0,.75f));
ms3.setShininess(128);
tb3.setRenderState(ms3);
tb3.setRenderState(ls);
tb3.setLightCombineMode(LightState.REPLACE);
AlphaState as = display.getRenderer().getAlphaState();
as.setEnabled(true);
as.setBlendEnabled(true);
as.setSrcFunction(AlphaState.SB_SRC_ALPHA);
as.setDstFunction(AlphaState.DB_ONE_MINUS_SRC_ALPHA);
transps.setRenderState(as);
Quad q1 = new Quad("Ortho Q1", 40, 40);
q1.setLocalTranslation(new Vector3f(100,100,0));
q1.setZOrder(1);
q1.setSolidColor(ColorRGBA.white);
q1.setLightCombineMode(LightState.REPLACE);
orthos.attachChild(q1);
Quad q2 = new Quad("Ortho Q2", 100, 100);
q2.setLocalTranslation(new Vector3f(60,60,0));
q2.setZOrder(5);
q2.setSolidColor(ColorRGBA.red);
q2.setLightCombineMode(LightState.REPLACE);
orthos.attachChild(q2);
Quad q3 = new Quad("Ortho Q3", 120, 60);
q3.setLocalTranslation(new Vector3f(-20,-150,0));
q3.setZOrder(2);
q3.setSolidColor(ColorRGBA.blue);
q3.setLightCombineMode(LightState.REPLACE);
orthos.attachChild(q3);
ZBufferState zstate = display.getRenderer().getZBufferState();
zstate.setWritable(false);
zstate.setEnabled(false);
orthos.setRenderState(zstate);
orthos.setRenderState(Spatial.defaultStateList[RenderState.RS_LIGHT]);
rootNode.setForceCull(true);
orthos.setForceView(true);
}
}
|
package com.faveset.khttp;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.util.Map;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.nio.channels.Selector;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import com.faveset.log.Log;
import com.faveset.log.NullLog;
public class HttpServer {
private static final String sTag = HttpServer.class.toString();
private Log mLog = new NullLog();
private Map<String, HttpHandler> mHttpHandlerMap = new HashMap<String, HttpHandler>();
private ServerSocketChannel mListenChan;
private SelectionKey mListenKey;
// A SelectorHandler will be attached to each SelectionKey registered
// with the Selector.
private Selector mSelector;
private SelectTaskQueue mSelectTaskQueue;
private SelectorHandler mListenSelectorHandler = new SelectorHandler() {
@Override
public void onReady(SelectionKey key) {
if (key.isValid() && key.isAcceptable()) {
handleAccept(key.channel());
}
}
};
private Set<HttpConnection> mConnectionSet = new HashSet<HttpConnection>();
private HttpConnection.OnCloseCallback mCloseCallback = new HttpConnection.OnCloseCallback() {
@Override
public void onClose(HttpConnection conn) {
handleConnectionClose(conn);
}
};
private volatile boolean mIsDone;
public HttpServer() {}
public void close() throws IOException {
// This also cancels the key.
mListenChan.close();
// Unregister handlers to avoid reference loops.
mListenKey.attach(null);
for (HttpConnection conn : mConnectionSet) {
conn.close();
}
mConnectionSet.clear();
mSelector.close();
}
private void handleAccept(SelectableChannel chanArg) {
ServerSocketChannel chan = (ServerSocketChannel) chanArg;
SocketChannel newChan;
try {
newChan = chan.accept();
} catch (IOException e) {
mLog.e(sTag, "accept failed; shutting down", e);
// We have a serious problem, so just bring down the server.
stop();
return;
}
if (newChan == null) {
// The selection key hint was incorrect, as the channel is not
// ready to accept.
return;
}
HttpConnection conn;
try {
conn = new HttpConnection(mSelector, newChan);
} catch (IOException e) {
mLog.e(sTag, "could not create HttpConnection, closing", e);
try {
newChan.close();
} catch (IOException newChanE) {
mLog.e(sTag, "could not close channel, ignoring", newChanE);
}
return;
}
conn.setOnCloseCallback(mCloseCallback);
conn.setLog(mLog);
// We must update mConnectionSet before starting, since conn.start()
// might issue a sequence of callbacks immediately.
mConnectionSet.add(conn);
conn.start(mHttpHandlerMap);
// NOTE: The connection might close as a result of start(), so we
// must be careful when modifying after this point.
}
private void handleConnectionClose(HttpConnection conn) {
// The HttpServer is at the top of the chain. Thus, we start
// closing for real after cleaning up.
try {
conn.close();
} catch (IOException e) {
mLog.e(sTag, "connection close failed, continuing", e);
// We've tried our best to clean up. It's safe to continue.
}
mConnectionSet.remove(conn);
}
/**
* Starts the HTTP server and begins listening on the given address and
* port. This only returns if stop() is called by another thread.
*/
public void listenAndServe(String listenAddr, int port) throws IllegalArgumentException, IOException {
InetSocketAddress sa = new InetSocketAddress(listenAddr, port);
mListenChan = ServerSocketChannel.open();
mListenChan.configureBlocking(false);
ServerSocket sock = mListenChan.socket();
sock.bind(sa);
mSelector = Selector.open();
mSelectTaskQueue = new SelectTaskQueue(mSelector);
mListenKey = mListenChan.register(mSelector, SelectionKey.OP_ACCEPT, mListenSelectorHandler);
mIsDone = false;
while (true) {
// The return value of select() (number of keys whose
// ready-operation sets were updated) is not the best indicator
// to check for completeness for two reasons:
// 1) A key will not be counted if its ready set does not change.
// (It might have been read ready before the select() and read
// ready after, which would not be counted.)
// 2) It might take an indefinite period of time to finish handling
// connections before we get an empty selection result.
mSelector.select();
if (mIsDone) {
break;
}
// Handle any tasks that must run in the selector thread.
do {
Runnable task = mSelectTaskQueue.poll();
if (task == null) {
break;
}
task.run();
} while (true);
Iterator<SelectionKey> iter = mSelector.selectedKeys().iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
if (!key.isValid()) {
continue;
}
SelectorHandler handler = (SelectorHandler) key.attachment();
handler.onReady(key);
// Remove for the next selection loop.
iter.remove();
}
}
close();
}
public void registerHandler(String url, HttpHandler handler) {
mHttpHandlerMap.put(url, handler);
}
public void setLog(Log log) {
mLog = log;
}
/**
* Threadsafe method for stopping the HttpServer.
*/
public synchronized void stop() {
mIsDone = true;
mSelector.wakeup();
}
public void unregisterHandler(String url) {
mHttpHandlerMap.remove(url);
}
};
|
package cubicchunks;
import net.minecraft.world.Dimension;
import net.minecraft.world.IChunkProvider;
import net.minecraft.world.ISaveHandler;
import net.minecraft.world.WorldClient;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.storage.ChunkLoader;
import net.minecraft.world.chunk.storage.IChunkLoader;
import cuchaz.m3l.api.chunks.ChunkSystem;
public class CubicChunkSystem implements ChunkSystem {
@Override
public IChunkLoader getChunkLoader(ISaveHandler saveHandler, Dimension dimension) {
// TEMP: return an ordinary chunk loader for now
return new ChunkLoader(saveHandler.getSaveFile());
}
@Override
public IChunkProvider getClientChunkProvider(WorldClient world) {
// TODO
return null;
}
@Override
public IChunkProvider getServerChunkProvider(WorldServer world) {
// TODO
return null;
}
}
|
// ModuleDirectory.java
package ed.appserver;
import java.io.*;
import java.util.*;
import ed.js.*;
import ed.js.engine.*;
public class ModuleDirectory extends JSObjectLame implements JSLibrary {
public ModuleDirectory( String root , String name , AppContext context , Scope scope ){
this( new File( Module._base , root ) , name , context , scope );
}
public ModuleDirectory( File root , String name , AppContext context , Scope scope ){
_root = root;
_name = name;
_context = context;
_scope = scope;
if ( ! _root.exists() ){
_root.mkdirs();
if ( ! _root.exists() )
throw new RuntimeException( "modules directory [" + _root + "] does not exist" );
}
}
public synchronized Module getModule( String name ){
Module m = _modules.get( name );
if ( m != null )
return m;
final File moddir = new File( _root , name );
m = new Module( moddir , _name + "." + name , true );
_modules.put( name , m );
return m;
}
public synchronized JSFileLibrary getJSFileLibrary( String name ){
JSFileLibrary lib = _libraries.get( name );
if ( lib != null )
return lib;
Module m = getModule( name );
lib = m.getLibrary( getDesiredVersion( name ) , _context , _scope );
System.err.println( "created JSFileLibrary : " + name );
_libraries.put( name , lib );
return lib;
}
public Object get( Object n ){
return getJSFileLibrary( n.toString() );
}
public String getDesiredVersion( String name ){
if ( _scope != null )
return _getDesiredVersion( _scope , name );
if ( _context != null )
return _getDesiredVersion( _context._scope , name ); // its very important this not call getScope(). that would cause an inf. loop
return null;
}
String _getDesiredVersion( Scope s , String name ){
return AppContext.getVersionForLibrary( s , name );
}
public Object getFromPath( String path , boolean evalToFunction ){
while ( path.startsWith( "/" ) )
path = path.substring(1);
int idx = path.indexOf( "/" );
final String libName;
final String next;
if ( idx > 0 ){
libName = path.substring( 0 , idx );
next = path.substring( idx + 1 );
}
else {
libName = path;
next = null;
}
JSFileLibrary lib = getJSFileLibrary( libName );
if ( next == null )
return lib;
return lib.getFromPath( next , evalToFunction );
}
final String _name;
final File _root;
final AppContext _context;
final Scope _scope;
final Map<String,Module> _modules = new HashMap<String,Module>();
final Map<String,JSFileLibrary> _libraries = new HashMap<String,JSFileLibrary>();
}
|
package arjuan;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.event.ProgressEvent;
import com.amazonaws.event.ProgressEventType;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.glacier.AmazonGlacierClient;
import com.amazonaws.services.glacier.transfer.ArchiveTransferManager;
import com.amazonaws.services.glacier.transfer.UploadResult;
import com.amazonaws.services.glacier.model.JobParameters;
import com.amazonaws.services.glacier.model.InitiateJobRequest;
import com.amazonaws.services.glacier.model.InitiateJobResult;
import com.amazonaws.services.glacier.model.ListJobsRequest;
import com.amazonaws.services.glacier.model.ListJobsResult;
import com.amazonaws.services.glacier.model.GetJobOutputRequest;
import com.amazonaws.services.glacier.model.GetJobOutputResult;
import com.amazonaws.services.glacier.model.GlacierJobDescription;
import java.util.*;
public class ArchiveInventory extends BaseAmazonGlacierClientAware {
private final Log log = LogFactory.getLog(ArchiveInventory.class);
// Ctor
public ArchiveInventory(String region, String account, String vault) {
super (region, account, vault);
}
/**
* Upload an archive in the given dir to an AWS Glacier vault and assign it with given description
*/
public void list() throws IOException {
this.list ("CSV", 15, null, null, null);
}
/**
* retrieve the list of archives in this objects vault
*/
public void list(String format, int interval, String description, String jobId, String fileName) throws IOException {
log.debug("Listing archives in " + format + " format");
if (jobId == null) {
// try to find the latest job of the given format and who's results are still available (AWS keeps results for 24 hours)
GlacierJobDescription potentialJob = retreiveLatestJobResults(format);
if (potentialJob != null) {
jobId = potentialJob.getJobId();
log.info("Found job with Id "+ jobId + " which was successfuly completed on " + potentialJob.getCompletionDate());
} else {
// no job id given and no recent job results are available -> submit a new retrival job and wait for it to complete
jobId = sendInventoryRetrievalJobRequest(format, description, interval);
log.info("A new job request with Id "+ jobId + " is now completed");
}
} else {
// provide some information in the log..
log.info("Looking specifically for the output of job with Id " + jobId);
}
// job is completed - request output and log it line by line
GetJobOutputResult jobOutput = this.awsClient.getJobOutput(new GetJobOutputRequest().withAccountId(this.account).withVaultName(this.vault).withJobId(jobId));
// determine target file name using the given name or use default name if needed
String path = fileName;
if (path == null) {
// caclulate file name suffix out of the JOB content type (either CSV or JSON)
String suffix = jobOutput.getContentType();
if (suffix.equalsIgnoreCase("text/csv")) {
suffix = "csv";
} else if (suffix.equalsIgnoreCase("application/json")) {
suffix = "json";
} else {
suffix = format; // not supposed to get here...
}
// default - informative - file output file name
path = "aws.glacier." + this.region + "." + this.vault + "." + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "." + suffix;
}
// write to file
log.info("Writing job output in a file named " + path);
Files.copy(jobOutput.getBody(), Paths.get(path), StandardCopyOption.REPLACE_EXISTING);
this.awsClient.shutdown();
this.log.info("Done");
}
private GlacierJobDescription retreiveJobResultByJobId(String jobId) {
this.log.info("Looking for specific job by Job Id: " + jobId);
// Prepare a job list request to figure out the status of the job
ListJobsRequest listJobsRequest = new ListJobsRequest().withAccountId(this.account).withVaultName(this.vault).withCompleted("true").withStatuscode("Succeeded");
for (GlacierJobDescription job : this.awsClient.listJobs(listJobsRequest).getJobList()){
// found our job?
if (job.getJobId().equals(jobId)) {
return job;
}
}
// job not found
return null;
}
private GlacierJobDescription retreiveLatestJobResults(String format) {
this.log.info("Looking for recently successfully completed jobs of format: " + format);
GlacierJobDescription latest = null;
Date latestCompletionDate = null;
// set the DateFormat to be able to parse and compare AWS jlacier job completion dates
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
// Traverse a job list that potentially matches the request to list archives in the given format
ListJobsRequest listJobsRequest = new ListJobsRequest().withAccountId(this.account).withVaultName(this.vault).withCompleted("true").withStatuscode("Succeeded");
for (GlacierJobDescription job : this.awsClient.listJobs(listJobsRequest).getJobList()) {
// skip irrelevant job types
if (! job.getAction().equalsIgnoreCase("InventoryRetrieval") ) continue;
// skip irrelevant formats
if (! format.equalsIgnoreCase(job.getInventoryRetrievalParameters().getFormat()) ) continue;
Date currentCompletionDate = null;
try {
currentCompletionDate = dateFormat.parse(job.getCompletionDate());
} catch (Exception e) {
log.warn(e);
// no point in continue checking more jobs given that we have the date format wrong :(
break;
}
// compare against previously found jobs (if any) to pick that latest
if (latestCompletionDate == null || currentCompletionDate.after(latestCompletionDate)) {
latest = job;
latestCompletionDate = currentCompletionDate;
}
}
// job not found
return latest;
}
private String sendInventoryRetrievalJobRequest(String format, String description, int interval) {
log.info("Description: " + description);
log.info("Interval: " + interval);
// craete an inventory retrival request
JobParameters params = new JobParameters().withType("inventory-retrieval").withFormat(format).withDescription(description);
InitiateJobRequest request = new InitiateJobRequest(account, vault, params);
// Initiate job and start polling for its completion
InitiateJobResult initiateJobResult = this.awsClient.initiateJob(request);
String jobId = initiateJobResult.getJobId();
this.log.info("Initiated job 'inventory-retrieval'. jobId=" + jobId);
// wait for the job to complete
GlacierJobDescription jobDescription = retreiveJobResultByJobId(jobId);
while (jobDescription == null || ! jobDescription.isCompleted()) {
// log
this.log.info("Job not completed! Will try again in " + interval + " minutes");
// wait before accessing again (remember: AWS are counting API calls!!)
try {
TimeUnit.MINUTES.sleep(interval);
} catch (InterruptedException ie) {}
// re-check job status
jobDescription = retreiveJobResultByJobId(jobId);
}
return jobId;
}
}
|
package com.jcabi.aether;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.apache.maven.project.MavenProject;
import org.apache.maven.repository.internal.MavenRepositorySystemSession;
import org.sonatype.aether.RepositorySystem;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.collection.CollectRequest;
import org.sonatype.aether.graph.Dependency;
import org.sonatype.aether.graph.DependencyFilter;
import org.sonatype.aether.repository.LocalRepository;
import org.sonatype.aether.repository.RemoteRepository;
import org.sonatype.aether.resolution.ArtifactResult;
import org.sonatype.aether.resolution.DependencyRequest;
import org.sonatype.aether.resolution.DependencyResolutionException;
import org.sonatype.aether.util.filter.DependencyFilterUtils;
/**
* Resolver of dependencies for one artifact.
*
* <p>The class is immutable and thread-safe.
*
* @author Yegor Bugayenko (yegor@jcabi.com)
* @version $Id$
* @since 0.1.6
*/
public final class Aether {
/**
* The project.
*/
private final transient MavenProject project;
/**
* Location of local repo.
*/
private final transient String localRepo;
/**
* Ctor.
* @param prj The project
* @param repo Local repository location
*/
public Aether(final MavenProject prj, final String repo) {
this.project = prj;
this.localRepo = repo;
}
/**
* List of transitive deps of the artifact.
* @param root The artifact to work with
* @param scope The scope to work with ("runtime", "test", etc.)
* @return The list of dependencies
* @todo #134 This "IF NOT NULL" validation is a workaround, since I don't
* know what the actual problem is. Looks like sometimes (for some unknown
* reason) #classpathFilter() returns NULL. When exactly this may happen
* I have no idea. That's why this workaround. Sometime later we should
* do a proper testing and reproduce this defect in a test.
*/
public List<Artifact> resolve(final Artifact root, final String scope) {
final CollectRequest crq = new CollectRequest();
crq.setRoot(new Dependency(root, scope));
for (RemoteRepository repo
: this.project.getRemoteProjectRepositories()) {
crq.addRepository(repo);
}
final RepositorySystem system = new RepositorySystemBuilder().build();
final DependencyFilter filter =
DependencyFilterUtils.classpathFilter(scope);
if (filter != null) {
final MavenRepositorySystemSession session =
new MavenRepositorySystemSession();
final LocalRepository local = new LocalRepository(this.localRepo);
session.setLocalRepositoryManager(
system.newLocalRepositoryManager(local)
);
final List<Artifact> deps = new LinkedList<Artifact>();
Collection<ArtifactResult> results;
try {
results = system.resolveDependencies(
session,
new DependencyRequest(crq, filter)
).getArtifactResults();
} catch (DependencyResolutionException ex) {
throw new IllegalStateException(ex);
}
for (ArtifactResult res : results) {
deps.add(res.getArtifact());
}
}
return deps;
}
}
|
package com.project1;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.db.Connector;
import com.db.User;
/**
* Servlet implementation class DeleteChat
*/
public class DeleteChat extends HttpServlet {
private static final long serialVersionUID = 1L;
public DeleteChat() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uid = request.getParameter("userid");
Session session = null;
Transaction tx = null;
String forward="messageBoard.jsp";
HttpSession session1 = request.getSession(false);
String uid1=null;
try{
uid1=session1.getAttribute("uid").toString();
if(uid1==null){
forward = "http://192.168.12.16:8080/project1/index.jsp";
return;
}
}catch (Exception ex)
{
forward = "http://192.168.12.16:8080/project1/Error.jsp";
return;
}
try
{
Connector conn = new Connector();
session = conn.configureSessionFactory().openSession();
tx = session.beginTransaction();
if(uid.equals(uid1)==false){
forward = "messageBoard.jsp";
return;
}
int uid2;
int chatId;
try{
uid2 = Integer.parseInt(uid1);
chatId = Integer.parseInt(request.getParameter("chatID"));
}catch (Exception ex){
forward = "http://192.168.12.16:8080/project1/Error.jsp";
return;
}
String hsql = "delete from Chat where id = :chatID and user_id = :uid";
Query query = session.createQuery(hsql);
query.setParameter("chatID", chatId);
query.setParameter("uid", uid2);
int res = query.executeUpdate();
}
catch (Exception ex)
{
tx.rollback();
ex.printStackTrace();
}
finally
{
if(session != null && session.isOpen())
{
tx.commit();
session.flush();
session.close();
}
else{
forward="/project1/index.jsp";
}
response.sendRedirect(forward);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package com.qiniu.common;
import java.nio.charset.Charset;
// CHECKSTYLE:OFF
public final class Config {
public static final String VERSION = "7.0.6";
public static final int BLOCK_SIZE = 4 * 1024 * 1024;
public static final Charset UTF_8 = Charset.forName("UTF-8");
/**
* API
*/
public static String API_HOST = "http://api.qiniu.com";
public static String RSF_HOST = "http://rsf.qbox.me";
public static String RS_HOST = "http://rs.qbox.me";
public static String IO_HOST = "http://iovip.qbox.me";
/**
* Zone
*/
public static Zone zone = Zone.zone0();
/**
* , Form
*/
public static int PUT_THRESHOLD = BLOCK_SIZE;
/**
* (10s)
*/
public static int CONNECT_TIMEOUT = 10;
/**
* (30s)
*/
public static int RESPONSE_TIMEOUT = 30;
public static int RETRY_MAX = 5;
private Config() {
}
}
// CHECKSTYLE:ON
|
package com.twu.biblioteca;
public class User {
private String librarynum;
private String password;
private String name;
private String email;
private String phone;
public User(String librarynum, String password, String name, String email, String phone) {
setLibraryNumber(librarynum);
if (this.librarynum == null) {
throw new IllegalArgumentException();
}
this.password = password;
this.name = name;
this.email = email;
this.phone = phone;
}
public String getLibraryNumber() {
return this.librarynum;
}
private boolean setLibraryNumber(String number) {
String[] splitResult = number.split("-");
if (splitResult.length != 2) {
return false;
}
if (splitResult[0].length() != 3) {
return false;
}
if (splitResult[1].length() != 4) {
return false;
}
try {
Integer.parseInt(splitResult[0]);
Integer.parseInt(splitResult[1]);
} catch (Exception e) {
return false;
}
this.librarynum = number;
return true;
}
public String getPassword() {
return this.password;
}
public String getName() {
return this.name;
}
public String getEmail() {
return this.email;
}
public String getPhone() {
return this.phone;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof User)) {
return false;
}
User otherUser = (User) obj;
boolean result = true;
result &= librarynum.equals(otherUser.getLibraryNumber());
result &= password.equals(otherUser.getPassword());
result &= name.equals(otherUser.getName());
result &= email.equals(otherUser.getEmail());
result &= phone.equals(otherUser.getPhone());
return result;
}
}
|
package cz.muni.fi.network;
import cz.muni.fi.datascrapper.DataTools;
import cz.muni.fi.datascrapper.model.Movie;
import cz.muni.fi.datascrapper.model.Person;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
private static List<Person> actors;
private static List<Person> directors;
private static List<Movie> movies;
public static void main(String[] args) throws Exception {
//PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
//System.setOut(out);
// xorTraining();
trainOnMovies(1000, 400, 3, true);
}
private static void trainOnMovies(final int desiredActorCount, final int desiredDirectorsCount, final int actorsInMovie, boolean useDummyNeurons) throws IOException {
// load training data from json
actors = DataTools.getBaseActors();
directors = DataTools.getBaseDirectors();
movies = DataTools.getMoviesWDirectorsFromJson();
// keep only top frequent 'desiredActorCount' actors / 'desiredDirectorsCount' directors
int inputSize = desiredActorCount + desiredDirectorsCount + (useDummyNeurons ? (1 + actorsInMovie) : 0);
removePeopleAboveLimit(desiredActorCount, desiredDirectorsCount);
// remove movies unfit for training (w/o director or 'actorsInMovie' actors)
movies = movies.stream().filter(m -> !m.filterMovie(actorsInMovie, useDummyNeurons)).collect(Collectors.toList());
List<Sample> samples = new ArrayList<>();
Collections.shuffle(movies, new Random(55));
int trainingSize = (int) (movies.size() * 0.9);
System.out.printf("Training on %d movies%n", trainingSize);
int iteratedMovies = 0;
for (Movie movie : movies) {
if (iteratedMovies++ == trainingSize) {
break;
}
double[] outputs = new double[]{movie.getRating() / 5 - 1};
double[] inputs = new double[inputSize];
if (!createInputsForMovie(desiredActorCount, desiredDirectorsCount, actorsInMovie, useDummyNeurons, movie, inputs)) {
continue;
}
double inputSum = Math.round(Arrays.stream(inputs).sum());
if(inputSum != actorsInMovie + 1) {
throw new RuntimeException("Invalid count of set neurons " + inputSum);
}
samples.add(new Sample(inputs, outputs));
}
System.out.println(samples.size());
// Num Inputs, Num Hidden, Num Outputs, Num Learning steps, Show Graph, Output image name
MLP mlp = new MLP(inputSize, 10, 1, 5000, true, "7",
//Learning rate, Use Glorot & Bengio weight init? , Print status frequency, Momentum influence, Frequency of decreasing learning rate, Is dropout on, Is minibatch on, Minibatch size
0.1, false, 30, 0.7, 80, true, true, movies.size() / 500);
mlp.training(samples);
int[] diffs = new int[]{0, 0, 0, 0};
// validation
for (int i = 0; i < movies.size(); i++) {
if (i == iteratedMovies) {
printDiffsTable(diffs);
diffs = new int[]{0, 0, 0, 0};
System.out.println("***");
System.out.println((movies.size() - trainingSize) + "movies not from the training set:");
System.out.println("***");
}
double[] inputs = new double[inputSize];
if(!createInputsForMovie(desiredActorCount, desiredDirectorsCount, actorsInMovie, useDummyNeurons, movies.get(i), inputs)) {
continue;
}
float rating = movies.get(i).getRating();
double predictedRating = (mlp.feedForward(inputs, false)[0] + 1) * 5;
if(i >= trainingSize){
System.out.printf("Movie : %s, rating: %.1f - predicted %.1f%n", movies.get(i).getName(), rating, predictedRating);
}
if (Math.abs(rating - predictedRating) < 0.5) {
++diffs[0];
} else if (Math.abs(rating - predictedRating) < 1) {
++diffs[1];
} else if (Math.abs(rating - predictedRating) < 2) {
++diffs[2];
} else {
++diffs[3];
}
}
printDiffsTable(diffs);
}
private static void removePeopleAboveLimit(int desiredActorCount, int desiredDirectorsCount) {
for (Movie movie : movies) {
for (String actor : movie.getActors()) {
for (Person person : actors) {
if (person.getId().equals(actor)) {
person.count++;
}
}
}
for (Person director : directors) {
if (director.getId().equals(movie.getDirector())) {
director.count++;
}
}
}
Collections.sort(actors, (b, a) -> b.count - a.count);
Collections.sort(directors, (b, a) -> b.count - a.count);
Set<String> removedActors = actors.subList(desiredActorCount, actors.size()).stream().map(a -> a.getId()).collect(Collectors.toSet());
actors = actors.subList(0, desiredActorCount);
Set<String> removedDirectors = actors.subList(desiredDirectorsCount, actors.size()).stream().map(a -> a.getId()).collect(Collectors.toSet());
directors = directors.subList(0, desiredDirectorsCount);
// remove removed actors / directors from movies
for (Movie movie : movies) {
movie.getActors().removeAll(removedActors);
if (removedDirectors.contains(movie.getDirector())) {
movie.setDirector(null);
}
}
}
private static boolean createInputsForMovie(int desiredActorCount, int desiredDirectorsCount, int actorsInMovie, boolean useDummyNeurons, Movie movie, double[] inputs) {
int missingActors = actorsInMovie - movie.getActors().size();
for (String actorId : movie.getActors()) {
int i = actors.indexOf(new Person(actorId));
if (i == -1) {
++missingActors;
} else {
inputs[i] = 1;
}
}
if (useDummyNeurons) {
int peopleNeurons = desiredActorCount + desiredDirectorsCount;
for (int i = peopleNeurons; i < peopleNeurons + missingActors; i++) {
inputs[i] = 1;
}
}
int directorIndex = directors.indexOf(new Person(movie.getDirector()));
if (directorIndex == -1) {
inputs[inputs.length - 1] = 1;
} else {
inputs[desiredActorCount + directorIndex] = 1;
}
if (!useDummyNeurons && (directorIndex == -1 || missingActors > 0)) {
return false;
}
return true;
}
private static void printDiffsTable(int[] diffs) {
int total = Arrays.stream(diffs).sum();
System.out.printf("******************************%n");
System.out.printf("* < 0.5 * %.2f %% *%n", percent(diffs[0], total));
System.out.printf("******************************%n");
System.out.printf("* < 1 * %.2f %% *%n", percent(diffs[1], total));
System.out.printf("******************************%n");
System.out.printf("* < 2 * %.2f %% *%n", percent(diffs[2], total));
System.out.printf("******************************%n");
System.out.printf("* >= 2 * %.2f %% *%n", percent(diffs[3], total));
System.out.printf("******************************%n");
}
private static float percent(int x, int total) {
return x / (float) total * 100f;
}
private static void sinTraining() {
ArrayList<Sample> samples = new ArrayList<>();
for (int i = 0; i < 400; i++) {
double x = new Random(i).nextInt((int) (2 * Math.PI * 1000)) / 1000d;
samples.add(new Sample(new double[]{x / 7}, new double[]{(Math.sin(x) + 1) / 2}));
}
// Num Inputs, Num Hidden, Num Outputs, Num Learning steps, Show Graph, Output image name
MLP mlp = new MLP(1, 2, 1, 1000, true, "2",
//Learning rate, Use Glorot & Bengio weight init? , Print status frequency, Momentum influence, Frequency of decreasing learning rate, Is dropout on, Is minibatch on, Minibatch size
0.15, false, 10, 0.65, 30, true, true, 10);
mlp.training(samples);
for (double x = 0.1; x < Math.PI * 2; x = x + 0.1) {
System.out.printf("%.1f = %.4f%n", x, (Math.sin(x) + 1) / 2);
System.out.printf("Výstup: %.4f%n", mlp.feedForward(new double[]{x / 7}, false)[0]);
System.out.println();
}
}
private static void xorTraining() {
ArrayList<Sample> samples = new ArrayList<>();
samples.add(new Sample(new double[]{1, 1}, new double[]{0}));
samples.add(new Sample(new double[]{1, 0}, new double[]{1}));
samples.add(new Sample(new double[]{0, 1}, new double[]{1}));
samples.add(new Sample(new double[]{0, 0}, new double[]{0}));
samples.add(new Sample(new double[]{1, 1}, new double[]{0}));
samples.add(new Sample(new double[]{1, 0}, new double[]{1}));
samples.add(new Sample(new double[]{0, 1}, new double[]{1}));
samples.add(new Sample(new double[]{0, 0}, new double[]{0}));
samples.add(new Sample(new double[]{1, 1}, new double[]{0}));
samples.add(new Sample(new double[]{1, 0}, new double[]{1}));
samples.add(new Sample(new double[]{0, 1}, new double[]{1}));
samples.add(new Sample(new double[]{0, 0}, new double[]{0}));
// Num Inputs, Num Hidden, Num Outputs, Num Learning steps, Show Graph, Output image name
MLP mlp = new MLP(2, 2, 1, 3000, false, "1",
//Learning rate, Use Glorot & Bengio weight init? , Print status frequency, Momentum influence, Frequency of decreasing learning rate,Is dropout on, Is minibatch on, Minibatch size
0.3, false, 10, 0.5, 30, false, true, 10);
mlp.training(samples);
System.out.println("Vstup: [1,0] Výstup: " + mlp.feedForward(new double[]{1, 0}, true)[0]);
System.out.println("Vstup: [1,1] Výstup: " + mlp.feedForward(new double[]{1, 1}, true)[0]);
System.out.println("Vstup: [0,1] Výstup: " + mlp.feedForward(new double[]{0, 1}, true)[0]);
System.out.println("Vstup: [0,0] Výstup: " + mlp.feedForward(new double[]{0, 0}, true)[0]);
}
}
|
package edu.rit.csh.models;
import java.io.IOException;
import java.io.Serializable;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.GenericGenerator;
import org.json.JSONArray;
import org.json.JSONObject;
import edu.rit.csh.WicketApplication;
import edu.rit.csh.auth.LDAPUser;
@Entity
@Table(name = "BOOKS")
public class Book implements Serializable{
private static final long serialVersionUID = -8012947208250080965L;
private static SessionFactory sessFact;
public static void setSessFact(SessionFactory fact){
sessFact = fact;
}
private Long id;
private String isbn;
private String ownerUID;
private BorrowPeriod borrowPeriod;
private boolean active = true;
public Book(){
}
public Book(String isbn, String uid){
this.setIsbn(isbn);
this.setOwnerUID(uid);
}
/**
* Get the book with the given isbn belonging to the user identified
* by ownerUID. Returns inactive ("deleted") books too, but these
* can be differentiated by the active field.
* @param isbn isbn of the book. must be an exact match.
* @return A book if found, else null.
*/
public static Book getBook(String isbn, String ownerUID){
Session sess = sessFact.openSession();
sess.beginTransaction();
Query qry = sess.createQuery("from Book where isbn = :isbn and ownerUID = :uid");
qry.setParameter("isbn", isbn);
qry.setParameter("uid", ownerUID);
Book b = (Book) qry.uniqueResult();
sess.getTransaction().commit();
sess.close();
return b;
}
/**
* Creates a book.
* @param isbn ISBN code
* @param ownerUID LDAP UID of the user.
*/
public static Book createBook(String isbn, String ownerUID){
Session sess = sessFact.openSession();
sess.beginTransaction();
Book b = new Book(isbn, ownerUID);
sess.save(b);
sess.getTransaction().commit();
sess.close();
return b;
}
/**
* Returns all books returned by the user with UIDnumber ownerUID.
* App must be running.
* @param ownerUID UIDnumber of the user.
* @return list of all books owned (regardless of possession) by the user.
*/
public static List<Book> getOwnedBooks(String ownerUID){
Session sess = sessFact.openSession();
sess.beginTransaction();
Query qry = sess.createQuery("from Book where ownerUID = :uid and active = true");
qry.setParameter("uid", ownerUID);
List<Book> ownedBooks = qry.list();
sess.getTransaction().commit();
sess.close();
return ownedBooks;
}
/**
* Return all books belonging to the user possessorUID or that are
* currently being borrowed by possessorUID.
* @return list of all books possessed by user.
*/
public static List<Book> getPossessedBooks(String possessorUID){
return getPossessedBooks(possessorUID, Calendar.getInstance());
}
/**
* Return all books belonging to the user possessorUID or that are
* being borrowed by possessorUID at time when.
* @return list of all books possessed by user.
*/
public static List<Book> getPossessedBooks(String possessorUID, Calendar when){
Session sess = sessFact.openSession();
sess.beginTransaction();
//List<Book> possessedBooks = getPossessedBooks(sess, when, possessorUID);
Query qry = sess.createQuery("from Book where (ownerUID = :uid or borrowPeriod != null) and active = true");
qry.setParameter("uid", possessorUID);
List<Book> possessedBooks = qry.list();
Iterator<Book> iter = possessedBooks.iterator();
while (iter.hasNext()){
Book b = iter.next();
if (b.getOwnerUID().equals(possessorUID) && b.borrowPeriod == null){
//Book belongs to possessorUID and has no associated BorrowPeriod
continue;
}else if (b.getOwnerUID().equals(possessorUID) && b.borrowPeriod != null){
//if the book has an associated BorrowPeriod we need to verify that
//the book is not currently lent out.
int beginComp = b.borrowPeriod.getBegin().compareTo(when);
int endComp = b.borrowPeriod.getEnd().compareTo(when);
if ((beginComp <= 0) && (endComp >= 0)){
iter.remove();
}
}else if (!b.getOwnerUID().equals(possessorUID) && b.borrowPeriod.getBorrowerUID().equals(possessorUID)){
//if the book does not belong to possessorUID (implying it has a BorrowPeriod)
//then we should exclude it unless it coincides with b.borrowPeriod
int beginComp = b.borrowPeriod.getBegin().compareTo(when);
int endComp = b.borrowPeriod.getEnd().compareTo(when);
if (!(beginComp <= 0) || !(endComp >= 0)){
iter.remove();
}
}else{
//book neither belongs to possessorUID nor has a BorrowPeriod by possessorUID
iter.remove();
}
}
sess.getTransaction().commit();
sess.close();
return possessedBooks;
}
/**
* @param isbn the isbn of the book (doesn't convert between isbn10/13)
* @return all active books that have isbn isbn
*/
public static List<Book> getBooksByIsbn(String isbn){
Session sess = sessFact.openSession();
sess.beginTransaction();
Query qry = sess.createQuery("from Book where isbn = :isbn and active = true");
qry.setParameter("isbn", isbn);
List<Book> books = qry.list();
sess.getTransaction().commit();
sess.close();
return books;
}
/**
* Makes this book inactive so that it won't show up anymore
* in the application.
*/
public void delete(){
Session sess = sessFact.openSession();
sess.beginTransaction();
sess.update(this);
setActive(false);
sess.getTransaction().commit();
sess.close();
}
/**
* borrowerUID borrows a book from begin to end.
*/
public void borrow(String borrowerUID, Calendar begin, Calendar end){
Session sess = sessFact.openSession();
sess.beginTransaction();
sess.update(this);
borrowPeriod = new BorrowPeriod();
borrowPeriod.setBorrowerUID(borrowerUID);
borrowPeriod.setBegin(begin);
borrowPeriod.setEnd(end);
borrowPeriod.setBook(this);
sess.save(borrowPeriod);
sess.getTransaction().commit();
sess.close();
}
public void removeBorrow(){
Session sess = sessFact.openSession();
sess.beginTransaction();
sess.update(this);
if (borrowPeriod != null){
sess.delete(borrowPeriod);
borrowPeriod = null;
sess.save(this);
}
sess.getTransaction().commit();
sess.close();
}
@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy="increment")
public Long getId(){
return id;
}
@SuppressWarnings("unused")
private void setId(Long id){
this.id = id;
}
public String getIsbn() {
return isbn;
}
private void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getOwnerUID() {
return ownerUID;
}
private void setOwnerUID(String ownerUID) {
this.ownerUID = ownerUID;
}
@OneToOne(optional = true)
public BorrowPeriod getBorrowPeriod() {
return borrowPeriod;
}
private void setBorrowPeriod(BorrowPeriod borrowPeriod) {
this.borrowPeriod = borrowPeriod;
}
/**
* Automatically gets the owner using a LDAP connection
* to CSH's LDAP server.
* @return the LDAPUser if successful, else null.
*/
@Transient
public LDAPUser getOwner(){
try {
return WicketApplication.getWicketApplication().getLDAPProxy().getUser(ownerUID);
} catch (LdapException | IOException | CursorException e) {
return null;
}
}
/**
* Set the new owner of this book to newOwner
*/
public void setOwner(LDAPUser newOwner){
ownerUID = newOwner.getUidnumber();
}
/**
* Returns the possessor of the Book on date using a connection to
* CSH's LDAP server.
* @return the possessing LDAPUser if successful, else null
*/
@Transient
public LDAPUser getPossessor(Calendar date){
try{
if (borrowPeriod == null){
return getOwner();
}else if (borrowPeriod.getBegin().compareTo(date) <= 0 &&
borrowPeriod.getEnd().compareTo(date) >= 0){
return WicketApplication.getWicketApplication().getLDAPProxy().getUser(ownerUID);
}else{
return getOwner();
}
} catch (LdapException | IOException | CursorException e) {
return null;
}
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
@Override
public boolean equals(Object o){
if (o instanceof Book){
return isbn.equals(((Book)o).isbn);
}else{
return false;
}
}
public static HashMap<String, String> buildBookModel(JSONObject obj){
HashMap<String, String> model = new HashMap<String, String>();
model.put("title", obj.optString("title"));
model.put("publisher", obj.optString("publisher"));
//description
String description = obj.optString("description");
StringBuilder sb;
if (description.length() > 600){
sb = new StringBuilder(600);
sb.append(description.substring(0, 597));
sb.append("...");
description = sb.toString();
}
model.put("description", description);
JSONObject thumbnails = obj.optJSONObject("imageLinks");
String thumbnailUrl = thumbnails == null ? "" : thumbnails.optString("thumbnail", "");
model.put("thumbnailUrl", thumbnailUrl);
//Construct Authors
sb = new StringBuilder(64);
JSONArray authorsJSON = obj.optJSONArray("authors");
if (authorsJSON != null){
for (int i = 0; i < authorsJSON.length(); i++){
String s = authorsJSON.getString(i);
sb.append(s);
if (i < authorsJSON.length()-1){
sb.append(", ");
}
}
}
model.put("authors", sb.toString());
//get isbn
JSONArray isbns = obj.optJSONArray("industryIdentifiers");
if (isbns != null){
for (int i = 0; i < isbns.length(); i++){
JSONObject isbn = isbns.getJSONObject(i);
if ("ISBN_13".equals(isbn.getString("type"))){
model.put("ISBN_13", isbn.getString("identifier"));
break;
}
}
}
return model;
}
}
|
package graphql.schema;
public interface Coercing {
/**
* Called to convert a result of a DataFetcher to a valid runtime value.
*
* @param input is never null
* @return null if not possible/invalid
*/
Object serialize(Object input);
/**
* Called to resolve a input from a variable.
* Null if not possible.
*
* @param input is never null
* @return null if not possible/invalid
*/
Object parseValue(Object input);
/**
* Called to convert a AST node
* @param input is never null
* @return null if not possible/invalid
*/
Object parseLiteral(Object input);
}
|
package hivemall.common;
import hivemall.common.WeightValue.WeightValueWithCovar;
import hivemall.utils.collections.IMapIterator;
import hivemall.utils.collections.OpenHashMap;
public final class SparseModel implements PredictionModel {
private final OpenHashMap<Object, WeightValue> weights;
public SparseModel() {
this(16384);
}
public SparseModel(int size) {
this.weights = new OpenHashMap<Object, WeightValue>(size);
}
@SuppressWarnings("unchecked")
@Override
public <T extends WeightValue> T get(Object feature) {
return (T) weights.get(feature);
}
@Override
public <T extends WeightValue> void set(Object feature, T value) {
weights.put(feature, value);
}
@Override
public float getWeight(Object feature) {
WeightValue v = weights.get(feature);
return v == null ? 0.f : v.value;
}
@Override
public float getCovariance(Object feature) {
WeightValueWithCovar v = (WeightValueWithCovar) weights.get(feature);
return v == null ? 1.f : v.covariance;
}
@Override
public void setValue(Object feature, float weight) {
weights.put(feature, new WeightValue(weight));
}
@Override
public void setValue(Object feature, float weight, float covar) {
weights.put(feature, new WeightValueWithCovar(weight, covar));
}
@Override
public int size() {
return weights.size();
}
@Override
public boolean contains(Object feature) {
return weights.containsKey(feature);
}
@SuppressWarnings("unchecked")
@Override
public <K, V extends WeightValue> IMapIterator<K, V> entries() {
return (IMapIterator<K, V>) weights.entries();
}
}
|
package hudson.ivy;
import static hudson.Util.fixEmpty;
import static hudson.model.ItemGroupMixIn.loadChildren;
import hudson.CopyOnWrite;
import hudson.Extension;
import hudson.FilePath;
import hudson.Util;
import hudson.ivy.builder.AntIvyBuilderType;
import hudson.ivy.builder.IvyBuilderType;
import hudson.ivy.builder.NAntIvyBuilderType;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.BuildableItemWithBuildWrappers;
import hudson.model.DependencyGraph;
import hudson.model.Descriptor;
import hudson.model.Executor;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Job;
import hudson.model.Queue;
import hudson.model.ResourceActivity;
import hudson.model.SCMedItem;
import hudson.model.Saveable;
import hudson.model.TopLevelItem;
import hudson.model.Descriptor.FormException;
import hudson.model.Queue.Task;
import hudson.model.queue.CauseOfBlockage;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrappers;
import hudson.tasks.Publisher;
import hudson.tasks.Ant.AntInstallation;
import hudson.util.CopyOnWriteMap;
import hudson.util.DescribableList;
import hudson.util.FormValidation;
import hudson.util.Function1;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.servlet.ServletException;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
/**
* Group of {@link IvyModule}s.
*
* <p>
* This corresponds to the group of Ivy module descriptors that constitute a single
* branch of projects.
*
* @author Timothy Bingaman
*/
public final class IvyModuleSet extends AbstractIvyProject<IvyModuleSet,IvyModuleSetBuild> implements TopLevelItem, ItemGroup<IvyModule>, SCMedItem, Saveable, BuildableItemWithBuildWrappers {
/**
* All {@link IvyModule}s, keyed by their {@link IvyModule#getModuleName()} module name}s.
*/
transient /*final*/ Map<ModuleName,IvyModule> modules = new CopyOnWriteMap.Tree<ModuleName,IvyModule>();
/**
* Topologically sorted list of modules. This only includes live modules,
* since archived ones usually don't have consistent history.
*/
@CopyOnWrite
transient List<IvyModule> sortedActiveModules;
private String ivyFilePattern;
private String ivyFileExcludesPattern;
private String targets;
private String ivyBranch;
private String relativePathToDescriptorFromModuleRoot;
private String ivySettingsFile;
private String ivySettingsPropertyFiles;
private IvyBuilderType ivyBuilderType;
/**
* Identifies {@link AntInstallation} to be used.
*/
private String antName;
/**
* ANT_OPTS if not null.
*/
private String antOpts;
/**
* Optional build script path relative to the workspace.
* Used for the Ant '-f' option.
*/
private String buildFile;
/**
* Optional properties to be passed to Ant. Follows {@link Properties} syntax.
*/
private String antProperties;
/**
* If true, the build will be aggregator style, meaning all the modules are
* executed in a single Ant invocation, as in CLI. False otherwise, meaning
* each module is built separately and possibly in parallel.
*/
private boolean aggregatorStyleBuild = true;
/**
* If true, and if aggregatorStyleBuild is false, the build will check the
* changeset before building, and if there are changes, only those modules
* which have changes or those modules which failed or were unstable in the
* previous build will be built directly. Any modules depending on the
* directly built modules will also be built.
*/
private boolean incrementalBuild = false;
/**
* The name of the property used to pass the names of the changed modules
* to the build when both incremental build and aggregated build options are
* selected.
*/
private String changedModulesProperty;
/**
* If true, do not automatically schedule a build when one of the project
* dependencies is built.
*/
private boolean ignoreUpstreamChanges = false;
/**
* If true, allow this project to trigger downstream projects based on
* Ivy dependencies.
*/
private Boolean allowedToTriggerDownstream = true;
/**
* If true properties this build will use parameters specified on the triggering build
*/
private boolean useUpstreamParameters = false;
public boolean isUseUpstreamParameters() {
return useUpstreamParameters;
}
public void setUseUpstreamParameters(boolean useUpstreamParameters) {
this.useUpstreamParameters = useUpstreamParameters;
}
/**
* If true, do not archive artifacts to the master.
*/
private boolean archivingDisabled = false;
/**
* List of active {@link Publisher}s configured for this project.
*/
private DescribableList<Publisher,Descriptor<Publisher>> publishers =
new DescribableList<Publisher,Descriptor<Publisher>>(this);
/**
* List of active {@link BuildWrapper}s configured for this project.
*/
private DescribableList<BuildWrapper,Descriptor<BuildWrapper>> buildWrappers =
new DescribableList<BuildWrapper, Descriptor<BuildWrapper>>(this);
public IvyModuleSet(String name) {
this(Hudson.getInstance(),name);
}
public IvyModuleSet(ItemGroup parent, String name) {
super(parent, name);
}
public String getUrlChildPrefix() {
// seemingly redundant "./" is used to make sure that ':' is not interpreted as the scheme identifier
return ".";
}
@Override
public Hudson getParent() {
return Hudson.getInstance();
}
public Collection<IvyModule> getItems() {
return modules.values();
}
@Exported
public Collection<IvyModule> getModules() {
return getItems();
}
public IvyModule getItem(String name) {
try {
return modules.get(ModuleName.fromString(name));
} catch (IllegalArgumentException iae) {
return null;
}
}
public IvyModule getModule(String name) {
return getItem(name);
}
@Override
protected void updateTransientActions() {
super.updateTransientActions();
for (IvyModule module: modules.values()) {
module.updateTransientActions();
}
if(publishers!=null) // this method can be loaded from within the onLoad method, where this might be null
for (BuildStep step : publishers) {
Collection<? extends Action> a = step.getProjectActions(this);
if(a!=null)
transientActions.addAll(a);
}
if (buildWrappers!=null)
for (BuildWrapper step : buildWrappers) {
Collection<? extends Action> a = step.getProjectActions(this);
if(a!=null)
transientActions.addAll(a);
}
}
@Override
protected void addTransientActionsFromBuild(IvyModuleSetBuild build, Set<Class> added) {
if(build==null) return;
for (Action a : build.getActions())
if(a instanceof IvyAggregatedReport)
if(added.add(a.getClass()))
transientActions.add(((IvyAggregatedReport)a).getProjectAction(this));
List<IvyReporter> list = build.projectActionReporters;
if(list==null) return;
for (IvyReporter step : list) {
if(!added.add(step.getClass())) continue; // already added
Action a = step.getAggregatedProjectAction(this);
if(a!=null)
transientActions.add(a);
}
}
/**
* Called by {@link IvyModule#doDoDelete(StaplerRequest, StaplerResponse)}.
* Real deletion is done by the caller, and this method only adjusts the
* data structure the parent maintains.
*/
/*package*/ void onModuleDeleted(IvyModule module) {
modules.remove(module.getModuleName());
}
/**
* Returns true if there's any disabled module.
*/
public boolean hasDisabledModule() {
for (IvyModule m : modules.values()) {
if(m.isDisabled())
return true;
}
return false;
}
/**
* Possibly empty list of all disabled modules (if disabled==true)
* or all enabeld modules (if disabled==false)
*/
public List<IvyModule> getDisabledModules(boolean disabled) {
if(!disabled && sortedActiveModules!=null)
return sortedActiveModules;
List<IvyModule> r = new ArrayList<IvyModule>();
for (IvyModule m : modules.values()) {
if(m.isDisabled()==disabled)
r.add(m);
}
return r;
}
public boolean isIncrementalBuild() {
return incrementalBuild;
}
public String getChangedModulesProperty() {
return changedModulesProperty;
}
public boolean isAggregatorStyleBuild() {
return aggregatorStyleBuild;
}
public boolean ignoreUpstreamChanges() {
return ignoreUpstreamChanges;
}
public boolean isAllowedToTriggerDownstream() {
return allowedToTriggerDownstream;
}
public void setAllowedToTriggerDownstream(boolean allowedToTriggerDownstream) {
this.allowedToTriggerDownstream = allowedToTriggerDownstream;
}
public boolean isArchivingDisabled() {
return archivingDisabled;
}
public void setIncrementalBuild(boolean incrementalBuild) {
this.incrementalBuild = incrementalBuild;
}
public String getIvyFilePattern() {
return ivyFilePattern;
}
public void setIvyFilePattern(String ivyFilePattern) {
this.ivyFilePattern = ivyFilePattern;
}
public String getIvyFileExcludesPattern() {
return ivyFileExcludesPattern;
}
public void setIvyFileExcludesPattern(String ivyFileExcludesPattern) {
this.ivyFileExcludesPattern = ivyFileExcludesPattern;
}
public String getIvySettingsFile() {
return ivySettingsFile;
}
public void setIvySettingsFile(String ivySettingsFile) {
this.ivySettingsFile = ivySettingsFile;
}
public String getIvySettingsPropertyFiles() {
return ivySettingsPropertyFiles;
}
public void setIvySettingsPropertyFiles(String ivySettingsPropertyFiles) {
this.ivySettingsPropertyFiles = ivySettingsPropertyFiles;
}
public String getIvyBranch() {
return ivyBranch;
}
public void setIvyBranch(String ivyBranch) {
this.ivyBranch = ivyBranch;
}
public IvyBuilderType getIvyBuilderType() {
return ivyBuilderType;
}
public void setAggregatorStyleBuild(boolean aggregatorStyleBuild) {
this.aggregatorStyleBuild = aggregatorStyleBuild;
}
public void setIgnoreUpstremChanges(boolean ignoreUpstremChanges) {
this.ignoreUpstreamChanges = ignoreUpstremChanges;
}
public void setIsArchivingDisabled(boolean archivingDisabled) {
this.archivingDisabled = archivingDisabled;
}
/**
* List of active {@link Publisher}s that should be applied to all module builds.
*/
public DescribableList<Publisher, Descriptor<Publisher>> getModulePublishers() {
return aggregatorStyleBuild ? new DescribableList<Publisher, Descriptor<Publisher>>(this) : publishers;
}
/**
* List of active {@link Publisher}s. Can be empty but never null.
*/
public DescribableList<Publisher, Descriptor<Publisher>> getPublishers() {
return publishers;
}
@Override
public DescribableList<Publisher, Descriptor<Publisher>> getPublishersList() {
return publishers;
}
public DescribableList<BuildWrapper, Descriptor<BuildWrapper>> getBuildWrappersList() {
return buildWrappers;
}
/**
* List of active {@link BuildWrapper}s. Can be empty but never null.
*
* @deprecated as of 1.335
* Use {@link #getBuildWrappersList()} to be consistent with other subtypes of {@link AbstractProject}.
*/
@Deprecated
public DescribableList<BuildWrapper, Descriptor<BuildWrapper>> getBuildWrappers() {
return buildWrappers;
}
@Override
public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
if (ModuleName.isValid(token))
return getModule(token);
return super.getDynamic(token,req,rsp);
}
public File getRootDirFor(IvyModule child) {
return new File(getModulesDir(),child.getModuleName().toFileSystemName());
}
public void onRenamed(IvyModule item, String oldName, String newName) throws IOException {
throw new UnsupportedOperationException();
}
public void onDeleted(IvyModule item) throws IOException {
// noop
}
@Override
public Collection<Job> getAllJobs() {
Set<Job> jobs = new HashSet<Job>(getItems());
jobs.add(this);
return jobs;
}
@Override
protected Class<IvyModuleSetBuild> getBuildClass() {
return IvyModuleSetBuild.class;
}
@Override
protected SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add(new CollectionSearchIndex<IvyModule>() {// for computers
@Override
protected IvyModule get(String key) {
for (IvyModule m : modules.values()) {
if(m.getDisplayName().equals(key))
return m;
}
return null;
}
@Override
protected Collection<IvyModule> all() {
return modules.values();
}
@Override
protected String getName(IvyModule o) {
return o.getName();
}
});
}
@Override
public boolean isFingerprintConfigured() {
return true;
}
@Override
public synchronized void save() throws IOException {
super.save();
if(!isAggregatorStyleBuild())
{
for (IvyModule module : getModules()) {
module.save();
}
}
}
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
modules = Collections.emptyMap(); // needed during load
super.onLoad(parent, name);
modules = loadChildren(this, getModulesDir(),new Function1<ModuleName,IvyModule>() {
public ModuleName call(IvyModule module) {
return module.getModuleName();
}
});
if(publishers==null)
publishers = new DescribableList<Publisher,Descriptor<Publisher>>(this);
publishers.setOwner(this);
if(buildWrappers==null)
buildWrappers = new DescribableList<BuildWrapper, Descriptor<BuildWrapper>>(this);
buildWrappers.setOwner(this);
updateTransientActions();
}
private File getModulesDir() {
return new File(getRootDir(),"modules");
}
/**
* To make it easy to grasp relationship among modules
* and the module set, we'll align the build numbers of
* all the modules.
*
* <p>
* This method is invoked from {@link Executor#run()},
* and because of the mutual exclusion among {@link IvyModuleSetBuild}
* and {@link IvyBuild}, we can safely touch all the modules.
*/
@Override
public synchronized int assignBuildNumber() throws IOException {
// determine the next value
updateNextBuildNumber();
return super.assignBuildNumber();
}
@Override
public void logRotate() throws IOException, InterruptedException {
super.logRotate();
// perform the log rotation of modules
for (IvyModule m : modules.values())
m.logRotate();
}
/**
* The next build of {@link IvyModuleSet} must have
* the build number newer than any of the current module build.
*/
/*package*/ void updateNextBuildNumber() throws IOException {
int next = this.nextBuildNumber;
for (IvyModule m : modules.values())
next = Math.max(next,m.getNextBuildNumber());
if(this.nextBuildNumber!=next) {
this.nextBuildNumber=next;
this.saveNextBuildNumber();
}
}
@Override
protected void buildDependencyGraph(DependencyGraph graph) {
publishers.buildDependencyGraph(this,graph);
buildWrappers.buildDependencyGraph(this,graph);
}
@Override
protected Set<ResourceActivity> getResourceActivities() {
final Set<ResourceActivity> activities = new HashSet<ResourceActivity>();
activities.addAll(super.getResourceActivities());
activities.addAll(Util.filter(publishers,ResourceActivity.class));
activities.addAll(Util.filter(buildWrappers,ResourceActivity.class));
return activities;
}
/**
* Because one of our own modules is currently building.
*/
public static class BecauseOfModuleBuildInProgress extends CauseOfBlockage {
public final IvyModule module;
public BecauseOfModuleBuildInProgress(IvyModule module) {
this.module = module;
}
public String getShortDescription() {
return Messages.IvyModuleSet_ModuleBuildInProgress(module.getName());
}
}
@Override
public CauseOfBlockage getCauseOfBlockage() {
CauseOfBlockage cob = super.getCauseOfBlockage();
if (cob != null) return cob;
for (IvyModule module : modules.values()) {
if (module.isBuilding() || module.isInQueue())
return new BecauseOfModuleBuildInProgress(module);
}
return null;
}
public AbstractProject<?,?> asProject() {
return this;
}
public String getRelativePathToDescriptorFromModuleRoot() {
return relativePathToDescriptorFromModuleRoot;
}
public void setRelativePathToDescriptorFromModuleRoot(String relativePathToDescriptorFromModuleRoot) {
this.relativePathToDescriptorFromModuleRoot = relativePathToDescriptorFromModuleRoot;
}
/**
* Returns the {@link IvyModule}s that are in the queue.
*/
public List<Queue.Item> getQueueItems() {
List<Queue.Item> r = new ArrayList<hudson.model.Queue.Item>();
for( Queue.Item item : Hudson.getInstance().getQueue().getItems() ) {
Task t = item.task;
if((t instanceof IvyModule && ((IvyModule)t).getParent()==this) || t ==this)
r.add(item);
}
return r;
}
// Web methods
@Override
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
super.submit(req,rsp);
JSONObject json = req.getSubmittedForm();
ignoreUpstreamChanges = !json.has("triggerByDependency");
allowedToTriggerDownstream = json.has("allowedToTriggerDownstream");
useUpstreamParameters = json.has("useUpstreamParameters");
ivyFilePattern = Util.fixEmptyAndTrim(json.getString("ivyFilePattern"));
ivyFileExcludesPattern = Util.fixEmptyAndTrim(json.getString("ivyFileExcludesPattern"));
ivySettingsFile = Util.fixEmptyAndTrim(json.getString("ivySettingsFile"));
ivySettingsPropertyFiles = Util.fixEmptyAndTrim(json.getString("ivySettingsPropertyFiles"));
ivyBranch = Util.fixEmptyAndTrim(json.getString("ivyBranch"));
relativePathToDescriptorFromModuleRoot = Util.fixEmptyAndTrim(json.getString("relativePathToDescriptorFromModuleRoot"));
JSONObject ivyBuilderTypeJson = json.getJSONObject("ivyBuilderType");
try {
ivyBuilderType = (IvyBuilderType) req.bindJSON(Class.forName(ivyBuilderTypeJson.getString("stapler-class")), ivyBuilderTypeJson);
} catch (ClassNotFoundException e) {
throw new FormException("Error creating specified builder type.", e, "ivyBuilderType");
}
aggregatorStyleBuild = !req.hasParameter("perModuleBuild");
incrementalBuild = req.hasParameter("incrementalBuild");
if (incrementalBuild)
changedModulesProperty = Util.fixEmptyAndTrim(json.getJSONObject("incrementalBuild").getString("changedModulesProperty"));
publishers.rebuild(req,json,BuildStepDescriptor.filter(Publisher.all(),this.getClass()));
buildWrappers.rebuild(req,json,BuildWrappers.getFor(this));
if(!isAggregatorStyleBuild())
{
for (IvyModule module : getModules()) {
module.getBuildWrappersList().rebuild(req,json,BuildWrappers.getFor(module));
}
}
updateTransientActions(); // to pick up transient actions from builder, publisher, etc.
}
public Class<? extends AbstractProject> getModuleClass() {
return IvyModule.class;
}
/**
* Delete all disabled modules.
*/
public void doDoDeleteAllDisabledModules(StaplerResponse rsp) throws IOException, InterruptedException {
checkPermission(DELETE);
for( IvyModule m : getDisabledModules(true))
m.delete();
rsp.sendRedirect2(".");
}
/**
* Check the location of the ivy descriptor file, alternate settings file, etc - any file.
*/
public FormValidation doCheckFileInWorkspace(@QueryParameter String value) throws IOException, ServletException {
IvyModuleSetBuild lb = getLastBuild();
if (lb!=null) {
FilePath ws = lb.getModuleRoot();
if(ws!=null)
return ws.validateRelativePath(value,true,true);
}
return FormValidation.ok();
}
/**
* Check that the provided file is a relative path. And check that it exists, just in case.
*/
public FormValidation doCheckIvySettingsFile(@QueryParameter String value) throws IOException, ServletException {
String v = fixEmpty(value);
if ((v == null) || (v.length() == 0)) {
// Null values are allowed.
return FormValidation.ok();
}
if ((v.startsWith("/")) || (v.startsWith("\\")) || (v.matches("^\\w\\:\\\\.*"))) {
return FormValidation.error("Ivy settings file must be a relative path.");
}
IvyModuleSetBuild lb = getLastBuild();
if (lb!=null) {
FilePath ws = lb.getWorkspace();
if(ws!=null)
return ws.validateRelativePath(value,true,true);
}
return FormValidation.ok();
}
@SuppressWarnings("unchecked")
public ArrayList<Descriptor<IvyBuilderType>> getBuilderTypeDescriptors() {
ArrayList<Descriptor<IvyBuilderType>> buildTypeDescriptors = new ArrayList<Descriptor<IvyBuilderType>>();
buildTypeDescriptors.add(Hudson.getInstance().getDescriptor(AntIvyBuilderType.class));
if (Hudson.getInstance().getPlugin("nant") != null) {
buildTypeDescriptors.add(Hudson.getInstance().getDescriptor(NAntIvyBuilderType.class));
}
return buildTypeDescriptors;
}
public DescriptorImpl getDescriptor() {
return DESCRIPTOR;
}
@Extension(ordinal=890)
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static final class DescriptorImpl extends AbstractProjectDescriptor {
/**
* Globally-defined ANT_OPTS.
*/
private String globalAntOpts;
public DescriptorImpl() {
super();
load();
}
public String getGlobalAntOpts() {
return globalAntOpts;
}
public void setGlobalAntOpts(String globalAntOpts) {
this.globalAntOpts = globalAntOpts;
save();
}
@Override
public String getDisplayName() {
return Messages.IvyModuleSet_DiplayName();
}
@Override
public TopLevelItem newInstance(String name) {
return new IvyModuleSet(name);
}
public TopLevelItem newInstance(ItemGroup parent, String name) {
return new IvyModuleSet(parent, name);
}
@Override
public boolean configure( StaplerRequest req, JSONObject o ) {
globalAntOpts = Util.fixEmptyAndTrim(o.getString("globalAntOpts"));
save();
return true;
}
}
protected Object readResolve() {
if (ivyBuilderType == null) {
// Convert builder settings to new format
ivyBuilderType = new AntIvyBuilderType(antName, buildFile, targets, antProperties, antOpts);
// Wipe out old builder settings to avoid confusion
antName = null;
buildFile = null;
targets = null;
antProperties = null;
antOpts = null;
}
if (allowedToTriggerDownstream == null) {
allowedToTriggerDownstream = true;
}
return this;
}
}
|
public class MathematicalOperations {
public int binaryPlus(int x,int y){
return x+y;
}
/**
* Performs integer subtraction operation
* @param x The minuend
* @param y The subtrahend
* @return The difference
*/
public int binaryMinus(int x, int y) {
return x-y;
}
/**
* Performs multiplication (times) operation
* @param x multiplicant
* @param y multiplier
* @return multiplication of x and y (x*y)
*/
public int times(int x, int y){ // returns x*y;
return x*y;
}
public float divide (int x, int y){// returns x/y as a float
if(y == 0){
throw new ArithmeticException("divided by 0");
}
return (float)(x)/(float)(y);
}
/**
* Raises x to the power of n
* @param x base
* @param n exponent
* @return exponentiation of x to the nth power (x^n)
*/
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
public float inverseDivide(int x, int y){
//returns y/x
if(x == 0){
throw new ArithmeticException("divided by 0");
}
return (float)(y)/(float)(x);
}
public int remainder(int x, int y) {
if(y == 0) {
throw new ArithmeticException("divided by 0");
}
return x % y;
}
/*
* performs unary plus operation
* @param x is the operand
* @return the value of the x
*/
public int unaryPlus(int x) {
return x;
}
/*
* performs unary minus operation
* @param x is the operand
* @return the unary negation of the x
*/
public int unaryMinus(int x) {
return -x;
}
public boolean negation(boolean x) {
if(x == true){
return false;
}else{
return true;
}
}
/**
* Performs factorial operation
* @param x The number to factorize
* @return The factorial of x
*/
public int factorial(int x){
if(x<0){
throw new ArithmeticException("Undefined factorial");
}else if(x==0 || x==1){
return 1;
}else{
return factorial(x-1)*x;
}
}
/**
* Takes the absolute value of an integer and returns the result
* Added by Mustafa Feyzioglu
*/
public static int absolute(int a) {
if(a<0) a = (a * -1);
return a;
}
}
|
package in.tombo.ponto;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.lang.model.SourceVersion;
public enum KeyStyle {
Flat {
@Override
public void writeMethods(PrintWriter pw, Properties properties) {
for (Object key : properties.keySet()) {
pw.println();
String keyString = key.toString();
MethodType type = MethodType.findMethodType(keyString);
String methodName =
keyString.replace('.', '_').replaceFirst(String.format("_%s\\Z", type.getMethodKey()),
"");
pw.println(commentString(keyString, properties.getProperty(keyString), 1));
pw.print(indent(1));
pw.println(type.toMethodString("public static", escapedMethodName(methodName), keyString));
}
}
},
Hierarchical {
@Override
public void writeMethods(PrintWriter pw, Properties properties) {
Node root = new Node(null, "");
for (Object key : properties.keySet()) {
String keyString = key.toString();
root.addKeyString(keyString);
}
writeNode(pw, root, 1, properties);
}
private void writeNode(PrintWriter pw, Node node, int depth, Properties properties) {
for (Entry<String, MethodType> method : node.getMethods().entrySet()) {
String fullName = node.getFullName();
String keyName = method.getKey();
if (!fullName.isEmpty()) {
keyName = String.format("%s.%s", fullName, method.getKey());
}
if (method.getValue() != MethodType.STRING) {
keyName = String.format("%s.%s", keyName, method.getValue().getMethodKey());
}
pw.println();
pw.println(commentString(keyName, properties.getProperty(keyName), depth));
pw.print(indent(depth));
pw.println(method.getValue().toMethodString("public static", escapedMethodName(method.getKey()), keyName));
}
for (Node child : node.getChilds()) {
pw.println();
pw.print(indent(depth));
pw.println(String.format("public static class %s {", escapedClassName(child.getName())));
writeNode(pw, child, depth + 1, properties);
pw.print(indent(depth));
pw.println("}");
}
}
},
Bean {
@Override
public void validateProperties(List<String> errors, Properties properties) {
Node root = new Node(null, "");
for (Object key : properties.keySet()) {
String keyString = key.toString();
root.addKeyString(keyString);
}
validateNode(errors, root);
}
private void validateNode(List<String> errors, Node node) {
Set<String> parentKeys = new HashSet<>();
for (Entry<String, MethodType> method : node.getMethods().entrySet()) {
parentKeys.add(method.getKey());
}
for (Node child : node.getChilds()) {
if (parentKeys.contains(child.getName())) {
errors.add(String.format("If using Bean Style, can not assign a value to the parent key [%s].", child.getFullName()));
}
validateNode(errors, child);
}
}
@Override
public void writeMethods(PrintWriter pw, Properties properties) {
Node root = new Node(null, "");
for (Object key : properties.keySet()) {
String keyString = key.toString();
root.addKeyString(keyString);
}
writeNode(pw, root, 1, properties);
}
private void writeNode(PrintWriter pw, Node node, int depth, Properties properties) {
for (Entry<String, MethodType> method : node.getMethods().entrySet()) {
String fullName = node.getFullName();
String keyName = method.getKey();
if (!fullName.isEmpty()) {
keyName = String.format("%s.%s", fullName, method.getKey());
}
if (method.getValue() != MethodType.STRING) {
keyName = String.format("%s.%s", keyName, method.getValue().getMethodKey());
}
pw.println();
pw.println(commentString(keyName, properties.getProperty(keyName), depth));
pw.print(indent(depth));
pw.println(method.getValue().toMethodString("public", beanGetterName(method.getKey(), method.getValue()), keyName));
}
for (Node child : node.getChilds()) {
String childName = child.getName();
pw.println();
pw.print(indent(depth));
pw.println(String.format("public %s %s() { return new %s(); }", escapedClassName(childName), beanGetterName(childName), escapedClassName(childName)));
pw.println();
pw.print(indent(depth));
pw.println(String.format("public static class %s {", escapedClassName(childName)));
writeNode(pw, child, depth + 1, properties);
pw.print(indent(depth));
pw.println("}");
}
}
};
public void validateProperties(List<String> errors, Properties properties) {}
public static final String commentTemplate = ""
public static String commentString(String key, String value, int depth) {
return String.format(commentTemplate.replaceAll("
}
public abstract void writeMethods(PrintWriter pw, Properties properties);
/**
* @param methodName
* @return
*/
private static String escapedMethodName(String methodName) {
return escapedName(methodName);
}
/**
* @param className
* @return
*/
private static String escapedClassName(String className) {
return escapedName(className);
}
private static String escapedName(String name) {
if (!SourceVersion.isName(name)) {
return "_" + name;
}
return name;
}
private static final Pattern upperCamelConvertionPattern = Pattern.compile("\\A.[a-z].*");
private static final Pattern snakeToCamelPattern = Pattern.compile("_([a-zA-Z])");
/**
* @param methodName
* @return
*/
private static String beanGetterName(String propertyName) {
return beanGetterName(propertyName, null);
}
/**
* @param methodName
* @param methodType
* @return
*/
private static String beanGetterName(String propertyName, MethodType methodType) {
if (upperCamelConvertionPattern.matcher(propertyName).matches()) {
propertyName = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
}
Matcher m;
while ((m = snakeToCamelPattern.matcher(propertyName)).find()) {
String group = m.group(1);
propertyName = propertyName.replace("_" + group, group.toUpperCase());
}
String prefix = methodType == MethodType.BOOLEAN ? "is" : "get";
return prefix + propertyName;
}
private static String indent(int depth) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < depth; i++) {
buf.append(" ");
}
return buf.toString();
}
}
|
package beaform.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import beaform.entities.Formula;
import beaform.entities.FormulaTag;
import beaform.entities.Ingredient;
/**
* This class handles all DB access for formulas.
*
* @author Steven Post
*
*/
public final class FormulaDAO {
private static final Logger LOG = LoggerFactory.getLogger(FormulaDAO.class);
/** Query to search for a formula by tag */
private static final String FORMULA_BY_TAG = "MATCH (t:FormulaTag { name:{name} })<-[r]-(f:Formula) RETURN f";
private FormulaDAO() {
// private constructor, because this is a utility class.
}
public static List<Ingredient> getIngredients(final Formula formula) {
final EntityManager entityManager = GraphDbHandler.getInstance().getEntityManager();
entityManager.getTransaction().begin();
final Formula retrievedFormula = entityManager.find(Formula.class, formula.getName());
final List<Ingredient> retList = retrievedFormula.getIngredients();
entityManager.getTransaction().commit();
return retList;
}
public static void updateExisting(final String name,
final String description,
final String totalAmount,
final List<Ingredient> ingredients,
final List<FormulaTag> tags) {
final EntityManager entityManager = GraphDbHandler.getInstance().getEntityManager();
entityManager.getTransaction().begin();
final Formula formula = entityManager.find(Formula.class, name);
setFormulaProperties(formula, description, totalAmount);
clearFormulaRelations(formula);
addTags(tags, formula);
addIngredientsToFormula(formula, ingredients);
entityManager.getTransaction().commit();
entityManager.detach(formula);
}
private static void addIngredientsToFormula(final Formula formula, final List<Ingredient> ingredients) {
for (final Ingredient ingredient : ingredients) {
// We should only be holding existing Formulas at this point
formula.addIngredient(ingredient.getFormula(), ingredient.getAmount());
}
}
public static void addFormula(final String name,
final String description,
final String totalAmount,
final List<Ingredient> ingredients,
final List<FormulaTag> tags) {
final EntityManager entityManager = GraphDbHandler.getInstance().getEntityManager();
entityManager.getTransaction().begin();
final Formula formula = new Formula(name, description, totalAmount);
addTags(tags, formula);
addIngredientsToFormula(formula, ingredients);
entityManager.persist(formula);
entityManager.getTransaction().commit();
entityManager.detach(formula);
}
private static void setFormulaProperties(final Formula formula, final String description, final String totalAmount) {
formula.setDescription(description);
formula.setTotalAmount(totalAmount);
}
/**
* This method adds tags to a formula.
* It assumes a running transaction.
*
* @param tags A list of tags
* @param entityManager an open entity manager
* @param formula the formula to add the tags to
* @throws NotSupportedException If the calling thread is already
* associated with a transaction,
* and nested transactions are not supported.
* @throws SystemException If the transaction service fails in an unexpected way.
*/
private static void addTags(final List<FormulaTag> tags, final Formula formula) {
for (final FormulaTag tag : tags) {
addTagToFormula(formula, tag);
}
}
private static void addTagToFormula(final Formula formula, final FormulaTag tag) {
// See if the tag exist in the DB, if so, use it.
FormulaTag tagToAdd;
try {
tagToAdd = FormulaTagDAO.findByObject(tag);
}
catch (NoResultException e1) {
if (LOG.isDebugEnabled()) {
LOG.debug("No tag with name " + tag.getName() + " found: " + e1.getMessage(), e1);
}
tagToAdd = tag;
}
formula.addTag(tagToAdd);
}
/**
* This method finds a formula in the DB based on a name.
* It assumes a transaction is already in progress.
*
* @param name the name of the formula to look for
* @return the found {@link Formula} or null if none was found.
*/
public static Formula findFormulaByName(final String name) {
final EntityManager entityManager = GraphDbHandler.getInstance().getEntityManager();
entityManager.getTransaction().begin();
final Formula result = entityManager.find(Formula.class, name);
if (LOG.isDebugEnabled()) {
LOG.debug("Found: " + result);
}
entityManager.getTransaction().commit();
entityManager.detach(result);
return result;
}
public static List<Formula> findFormulasByTag(final String tagName) {
final EntityManager entityManager = GraphDbHandler.getInstance().getEntityManager();
entityManager.getTransaction().begin();
final List<Formula> result = findByTag(tagName, entityManager);
if (LOG.isDebugEnabled()) {
LOG.debug("Found: " + result);
}
entityManager.getTransaction().commit();
for (final Formula formula : result) {
entityManager.detach(formula);
}
return result;
}
private static List<Formula> findByTag(final String tagName, final EntityManager entityManager) {
final Query query = entityManager.createNativeQuery(FORMULA_BY_TAG, Formula.class);
query.setParameter("name", tagName);
return query.getResultList();
}
private static void clearFormulaRelations(final Formula formula) {
formula.deleteAllIngredients();
formula.deleteAllTags();
}
}
|
package com.datastax.probe;
import java.util.Arrays;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.probe.job.ProbeJob;
public class App {
private static final Logger LOG = LoggerFactory.getLogger(App.class);
@SuppressWarnings("static-access")
private static Options getCLiOption() {
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("help").withDescription("Display help information").create("h"));
options.addOption(OptionBuilder.withLongOpt("interval")
.withDescription("The interval in seconds between running probe jobs.\nIf not specified or < 1, the probe will be run once only.").hasArg().withArgName("INTERVAL")
.create("i"));
options.addOption(OptionBuilder.withLongOpt("yaml")
.withDescription("The path to the cassandra.yaml to obtain the contact points (via the seeds) and ports Cassandra is listening on").hasArg().withArgName("YAML")
.create("y"));
options.addOption(OptionBuilder.withLongOpt("username").withDescription("The username to connect to Cassandra").hasArg().withArgName("USERNAME").create("u"));
options.addOption(OptionBuilder.withLongOpt("password").withDescription("The password to connect to Cassandra").hasArg().withArgName("PASSWORD").create("p"));
options.addOption(OptionBuilder
.withLongOpt("cqlshrc")
.withDescription(
"The path to the CQLSHRC containing security credentails for Cassandra. If this is specified the security credentials will be read from this file and NOT the username/password arguments")
.hasArg().withArgName("CQLSHRC").create("c"));
options.addOption(OptionBuilder.withLongOpt("ping").withDescription("Execute ping/isReachable probe to Cassandra host").create("pi"));
options.addOption(OptionBuilder.withLongOpt("storage").withDescription("Probe the storage/gossip port").create("st"));
options.addOption(OptionBuilder.withLongOpt("native").withDescription("Probe the native port").create("na"));
options.addOption(OptionBuilder.withLongOpt("thrift").withDescription("Probe the thrift port").create("th"));
options.addOption(OptionBuilder.withLongOpt("test_cql")
.withDescription("Test CQL query to run against cluster").hasArg().withArgName("TEST CQL QUERY")
.create("cql"));
options.addOption(OptionBuilder.withLongOpt("consistency")
.withDescription("The consistency level to use for the test CQL statement").hasArg().withArgName("CONSISTENCY LEVEL")
.create("con"));
options.addOption(OptionBuilder.withLongOpt("tracing").withDescription("Enable query tracing as part of the test query. WARNING - enabling tracing persists data to the system_traces keyspace in the cluster being probed.").create("tr"));
return options;
}
private static void printHelp() {
HelpFormatter help = new HelpFormatter();
help.setWidth(HelpFormatter.DEFAULT_WIDTH + 100);
help.printHelp("java -jar cassandra-probe-exec.jar", App.getCLiOption());
}
public static void main(String[] args) {
if (args.length == 0 || Arrays.asList(args).contains("--help") || Arrays.asList(args).contains("-help") || Arrays.asList(args).contains("help")) {
App.printHelp();
System.exit(0);
}
CommandLineParser parser = new BasicParser();
CommandLine cmd = null;
try {
cmd = parser.parse(App.getCLiOption(), args);
} catch (ParseException e) {
String msg = "Problem encountered parsing command line arguments : " + e.getMessage();
LOG.error(msg);
System.err.println(msg);
App.printHelp();
System.exit(1);
}
int interval = Integer.parseInt(cmd.getOptionValue("interval", "-1"));
LOG.info("interval: " + interval);
String yaml = cmd.getOptionValue("yaml");
LOG.info("yaml: " + yaml);
String cqlshrc = cmd.getOptionValue("cqlshrc");
String userName = cmd.getOptionValue("username");
String password = cmd.getOptionValue("password");
boolean pingProbe = true;
boolean storageProbe = true;
boolean thriftProbe = true;
boolean nativeProbe = true;
if (cmd.hasOption("storage") || cmd.hasOption("thrift") || cmd.hasOption("native") || cmd.hasOption("ping")) {
storageProbe = cmd.hasOption("storage");
thriftProbe = cmd.hasOption("thrift");
nativeProbe = cmd.hasOption("native");
pingProbe = cmd.hasOption("ping");
}
if (StringUtils.isNotBlank(cqlshrc)) {
LOG.info("cqlshrc path provided as '" + cqlshrc + "'");
userName = null;
password = null;
} else if (StringUtils.isNotBlank(userName)) {
if (StringUtils.isBlank(password)) {
String msg = "Cassandra username is provided, but no password has been specified";
LOG.error(msg);
System.err.println(msg);
App.printHelp();
System.exit(1);
}
LOG.info("Username/password authentication is provided");
} else {
LOG.info("No cqlshrc path or user credentials provided. Cassandra will be connected to without any authentication");
}
String testCql = cmd.getOptionValue("test_cql");
String con = cmd.getOptionValue("consistency");
boolean tracingEnabled = cmd.hasOption("tracing");
ConsistencyLevel consistency = null;
LOG.debug("Test CQL query '"+testCql+"' and consistency level of '"+con+"'");
if (StringUtils.isNotBlank(testCql)) {
if (StringUtils.isBlank(con)) {
String msg = "Consistency level must be specified if test cql query is provided";
LOG.error(msg);
System.err.println(msg);
App.printHelp();
System.exit(1);
}
LOG.info("Test CQL query '"+testCql+"' will be executed at Consistency level of '"+con+"' with tracing enabled "+tracingEnabled);
consistency = ConsistencyLevel.valueOf(con.toUpperCase().trim());
if (consistency == null) {
String msg = "Unable to recognise inputted consistency '"+con+"'";
LOG.error(msg);
System.err.println(msg);
App.printHelp();
System.exit(1);
}
} else {
LOG.info("No Test CQL query required");
}
try {
if (interval < 1) {
LOG.info("Running probe once only");
Prober app = null;
if (cqlshrc != null) {
app = new Prober(yaml, cqlshrc, nativeProbe, thriftProbe, storageProbe, pingProbe, testCql, consistency, tracingEnabled);
} else if (userName != null) {
app = new Prober(yaml, userName, password, nativeProbe, thriftProbe, storageProbe, pingProbe, testCql, consistency, tracingEnabled);
} else {
app = new Prober(yaml, nativeProbe, thriftProbe, storageProbe, pingProbe, testCql, consistency, tracingEnabled);
}
app.probe();
System.exit(0);
} else {
LOG.info("Running probe continuously with an interval of " + interval + " seconds between probes");
final App app = new App();
app.startJob(interval, yaml, cqlshrc, userName, password, nativeProbe, thriftProbe, storageProbe, pingProbe, testCql, consistency, tracingEnabled);
}
} catch (Exception e) {
String msg = "Problem encountered starting job: " + e.getMessage();
LOG.error(msg, e);
e.printStackTrace(System.err);
System.exit(1);
}
}
public void startJob(final int intervalInSeconds, final String yamlPath, final String cqlshrcPath, final String userName, final String password,
final boolean nativeProbe, final boolean thriftProbe, final boolean storageProbe, final boolean pingProbe, final String testCql,
final ConsistencyLevel consistency, final boolean tracingEnabled) throws SchedulerException {
final JobDataMap args = new JobDataMap();
args.put("cqlshrcPath", cqlshrcPath);
args.put("yamlPath", yamlPath);
args.put("username", userName);
args.put("password", password);
args.put("nativeProbe", nativeProbe);
args.put("thriftProbe", thriftProbe);
args.put("storageProbe", storageProbe);
args.put("pingProbe", pingProbe);
args.put("testCql", testCql);
args.put("consistency", consistency);
args.put("tracingEnabled", tracingEnabled);
JobDetail job = JobBuilder.newJob(ProbeJob.class).withIdentity("ProbeJob", "cassandra-probe").usingJobData(args).build();
Trigger trigger = TriggerBuilder.newTrigger().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(intervalInSeconds).repeatForever()).build();
SchedulerFactory schFactory = new StdSchedulerFactory();
Scheduler sch = schFactory.getScheduler();
sch.start();
sch.scheduleJob(job, trigger);
}
}
|
package com.imcode.imcms.db;
import com.imcode.imcms.persistence.components.SqlResourcePathResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.util.List;
public final class DB {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final JdbcTemplate jdbcTemplate;
public DB(DataSource ds) {
jdbcTemplate = new JdbcTemplate(ds);
}
public List<String> tables() {
return jdbcTemplate.query("SHOW TABLES", (resultSet, rowNum) -> resultSet.getString(1));
}
public boolean isNew() {
return tables().isEmpty();
}
public Version getVersion() {
String versionStr = jdbcTemplate.queryForObject("SELECT concat(major, '.', minor) FROM database_version", String.class);
return Version.parse(versionStr);
}
private synchronized void updateVersion(Version newVersion) {
final Version currentVersion = getVersion();
logger.info("Updating database version from {} to {}.", currentVersion, newVersion);
jdbcTemplate.update("UPDATE database_version SET major=?, minor=?", newVersion.getMajor(), newVersion.getMinor());
}
private Version update(Schema schema) {
Version dbVersion = getVersion();
Version requiredVersion = schema.getVersion();
switch (dbVersion.compareTo(requiredVersion)) {
case 0:
logger.info("Database is up-to-date.");
return dbVersion;
case 1:
String errorMsg = String.format(
"Unexpected database version. Database version %s is greater that required version %s",
requiredVersion, requiredVersion);
logger.error(errorMsg);
throw new IllegalStateException(errorMsg);
default:
logger.info("Database have to be updated. Required version: {}, database version: {}", requiredVersion, dbVersion);
List<Diff> diffs = schema.diffsChainFrom(dbVersion);
if (diffs.isEmpty()) {
final String errorMessage = String.format("No diff is available for version %s", dbVersion);
logger.error(errorMessage);
throw new IllegalStateException(errorMessage);
}
logger.info("The following diff will be applied: {}.", diffs);
diffs.forEach(diff -> {
runScripts(diff.getScripts(), schema.getScriptsDir());
updateVersion(diff.getTo());
});
Version updatedDbVersion = getVersion();
logger.info("Database has been updated. Database version is {}.", updatedDbVersion);
return updatedDbVersion;
}
}
public synchronized Version prepare(Schema schema) {
logger.info("Preparing database.");
if (isNew()) {
logger.info("Database is empty and need to be initialized.");
logger.info("The following init will be applied: {}", schema.getInit());
runScripts(schema.getInit().getScripts(), schema.getScriptsDir());
updateVersion(schema.getInit().getVersion());
logger.info("Database has been initialized.");
}
return update(schema);
}
private synchronized void runScripts(List<String> scripts, URI scriptsDirURI) {
jdbcTemplate.execute((ConnectionCallback<Void>) connection -> {
try (SqlResourcePathResolver pathResolver = new SqlResourcePathResolver(scriptsDirURI)) {
Path scriptsDirPath = pathResolver.resolveSqlResourcePath();
runScripts(scripts, scriptsDirPath, connection);
} catch (IOException e) {
throw new RuntimeSqlException(e);
}
return null;
});
}
private void runScripts(List<String> scripts, Path scriptsDirPath, Connection connection) throws IOException {
IBatisPatchedScriptRunner scriptRunner = new IBatisPatchedScriptRunner(connection);
scriptRunner.setAutoCommit(false);
scriptRunner.setStopOnError(true);
for (String script : scripts) {
logger.debug("Running script {}.", script);
final Path scriptPath = scriptsDirPath.resolve(script);
final InputStream scriptInputStream = Files.newInputStream(scriptPath);
try (Reader reader = new InputStreamReader(scriptInputStream, StandardCharsets.UTF_8)) {
scriptRunner.runScript(reader);
}
}
}
}
|
package mtr.render;
import minecraftmappings.Utilities;
import minecraftmappings.UtilitiesClient;
import mtr.MTRClient;
import mtr.block.BlockSignalLightBase;
import mtr.block.BlockSignalSemaphoreBase;
import mtr.config.Config;
import mtr.data.*;
import mtr.gui.ClientCache;
import mtr.gui.ClientData;
import mtr.gui.IDrawing;
import mtr.item.ItemNodeModifierBase;
import mtr.model.TrainClientRegistry;
import mtr.path.PathData;
import net.minecraft.block.Block;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.render.*;
import net.minecraft.client.render.entity.model.EntityModel;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.Entity;
import net.minecraft.entity.vehicle.MinecartEntity;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.DyeColor;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.Vec3f;
import net.minecraft.world.LightType;
import net.minecraft.world.World;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class RenderTrains implements IGui {
public static int maxTrainRenderDistance;
private static float gameTick = 0;
private static float lastPlayedTrainSoundsTick = 0;
private static int prevPlatformCount;
private static int prevSidingCount;
public static final int TICKS_PER_SPEED_SOUND = 4;
private static final Set<String> AVAILABLE_TEXTURES = new HashSet<>();
private static final Set<String> UNAVAILABLE_TEXTURES = new HashSet<>();
private static final int DETAIL_RADIUS = 32;
private static final int DETAIL_RADIUS_SQUARED = DETAIL_RADIUS * DETAIL_RADIUS;
private static final int MAX_RADIUS_REPLAY_MOD = 64 * 16;
private static final int TICKS_PER_SECOND = 20;
private static final EntityModel<MinecartEntity> MODEL_MINECART = UtilitiesClient.getMinecartModel();
public static void render(World world, MatrixStack matrices, VertexConsumerProvider vertexConsumers, Camera camera) {
final MinecraftClient client = MinecraftClient.getInstance();
final ClientPlayerEntity player = client.player;
if (player == null) {
return;
}
final int renderDistanceChunks = client.options.viewDistance;
final float lastFrameDuration = MTRClient.isReplayMod ? 20F / 60 : client.getLastFrameDuration();
gameTick += lastFrameDuration;
final boolean useTTSAnnouncements = Config.useTTSAnnouncements();
if (Config.useDynamicFPS()) {
if (lastFrameDuration > 0.5) {
maxTrainRenderDistance = Math.max(maxTrainRenderDistance - (maxTrainRenderDistance - DETAIL_RADIUS) / 2, DETAIL_RADIUS);
} else if (lastFrameDuration < 0.4) {
maxTrainRenderDistance = Math.min(maxTrainRenderDistance + 1, renderDistanceChunks * 8);
}
} else {
maxTrainRenderDistance = renderDistanceChunks * 8;
}
final Vec3d cameraPos = camera.getPos();
final float cameraYaw = camera.getYaw();
final Vec3d cameraOffset = client.gameRenderer.getCamera().isThirdPerson() ? player.getCameraPosVec(client.getTickDelta()).subtract(cameraPos) : Vec3d.ZERO;
final boolean secondF5 = Math.abs(Utilities.getYaw(player) - client.gameRenderer.getCamera().getYaw()) > 90;
ClientData.TRAINS.forEach(train -> train.simulateTrain(world, client.isPaused() ? 0 : lastFrameDuration, (x, y, z, yaw, pitch, trainId, baseTrainType, isEnd1Head, isEnd2Head, head1IsFront, doorLeftValue, doorRightValue, opening, lightsOn, isTranslucent, playerOffset) -> renderWithLight(world, x, y, z, cameraPos.add(cameraOffset), playerOffset != null, (light, posAverage) -> {
final TrainClientRegistry.TrainProperties trainProperties = TrainClientRegistry.getTrainProperties(trainId, baseTrainType);
if (trainProperties.model == null && isTranslucent) {
return;
}
matrices.push();
if (playerOffset == null) {
matrices.translate(x - cameraPos.x, y - cameraPos.y, z - cameraPos.z);
} else {
matrices.translate(cameraOffset.x, cameraOffset.y, cameraOffset.z);
matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(Utilities.getYaw(player) - cameraYaw + (secondF5 ? 180 : 0)));
matrices.translate(x - playerOffset.x, y - playerOffset.y, z - playerOffset.z);
}
matrices.multiply(Vec3f.POSITIVE_Y.getRadialQuaternion((float) Math.PI + yaw));
matrices.multiply(Vec3f.POSITIVE_X.getRadialQuaternion((float) Math.PI + pitch));
if (trainProperties.model == null || trainProperties.textureId == null) {
matrices.translate(0, 0.5, 0);
matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(90));
final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(MODEL_MINECART.getLayer(new Identifier("textures/entity/minecart.png")));
MODEL_MINECART.setAngles(null, 0, 0, -0.1F, 0, 0);
MODEL_MINECART.render(matrices, vertexConsumer, light, OverlayTexture.DEFAULT_UV, 1, 1, 1, 1);
} else {
trainProperties.model.render(matrices, vertexConsumers, resolveTexture(trainProperties, textureId -> textureId + ".png"), light, doorLeftValue, doorRightValue, opening, isEnd1Head, isEnd2Head, head1IsFront, lightsOn, isTranslucent, MTRClient.isReplayMod || posAverage.getSquaredDistance(new BlockPos(cameraPos)) <= DETAIL_RADIUS_SQUARED);
}
matrices.pop();
}), (prevPos1, prevPos2, prevPos3, prevPos4, thisPos1, thisPos2, thisPos3, thisPos4, x, y, z, yaw, trainId, baseTrainType, lightsOn, playerOffset) -> renderWithLight(world, x, y, z, cameraPos.add(cameraOffset), playerOffset != null, (light, posAverage) -> {
final TrainClientRegistry.TrainProperties trainProperties = TrainClientRegistry.getTrainProperties(trainId, baseTrainType);
if (trainProperties.textureId == null) {
return;
}
matrices.push();
if (playerOffset == null) {
matrices.translate(-cameraPos.x, -cameraPos.y, -cameraPos.z);
} else {
matrices.translate(cameraOffset.x, cameraOffset.y, cameraOffset.z);
matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(Utilities.getYaw(player) - cameraYaw + (secondF5 ? 180 : 0)));
matrices.translate(-playerOffset.x, -playerOffset.y, -playerOffset.z);
}
final VertexConsumer vertexConsumerExterior = vertexConsumers.getBuffer(MoreRenderLayers.getExterior(getConnectorTextureString(trainProperties, "exterior")));
drawTexture(matrices, vertexConsumerExterior, thisPos2, prevPos3, prevPos4, thisPos1, light);
drawTexture(matrices, vertexConsumerExterior, prevPos2, thisPos3, thisPos4, prevPos1, light);
drawTexture(matrices, vertexConsumerExterior, prevPos3, thisPos2, thisPos3, prevPos2, light);
drawTexture(matrices, vertexConsumerExterior, prevPos1, thisPos4, thisPos1, prevPos4, light);
final int lightOnLevel = lightsOn ? MAX_LIGHT_INTERIOR : light;
final VertexConsumer vertexConsumerSide = vertexConsumers.getBuffer(MoreRenderLayers.getInterior(getConnectorTextureString(trainProperties, "side")));
drawTexture(matrices, vertexConsumerSide, thisPos3, prevPos2, prevPos1, thisPos4, lightOnLevel);
drawTexture(matrices, vertexConsumerSide, prevPos3, thisPos2, thisPos1, prevPos4, lightOnLevel);
drawTexture(matrices, vertexConsumers.getBuffer(MoreRenderLayers.getInterior(getConnectorTextureString(trainProperties, "roof"))), prevPos2, thisPos3, thisPos2, prevPos3, lightOnLevel);
drawTexture(matrices, vertexConsumers.getBuffer(MoreRenderLayers.getInterior(getConnectorTextureString(trainProperties, "floor"))), prevPos4, thisPos1, thisPos4, prevPos1, lightOnLevel);
matrices.pop();
}), (speed, stopIndex, routeIds) -> {
if (!(speed <= 5 && RailwayData.useRoutesAndStationsFromIndex(stopIndex, routeIds, ClientData.DATA_CACHE, (thisRoute, nextRoute, thisStation, nextStation, lastStation) -> {
final Text text;
switch ((int) ((System.currentTimeMillis() / 1000) % 3)) {
default:
text = getStationText(thisStation, "this");
break;
case 1:
if (nextStation == null) {
text = getStationText(thisStation, "this");
} else {
text = getStationText(nextStation, "next");
}
break;
case 2:
text = getStationText(lastStation, "last");
break;
}
player.sendMessage(text, true);
}))) {
player.sendMessage(new TranslatableText("gui.mtr.train_speed", Math.round(speed * 10) / 10F, Math.round(speed * 36) / 10F), true);
}
}, (stopIndex, routeIds) -> {
final boolean showAnnouncementMessages = Config.showAnnouncementMessages();
if (showAnnouncementMessages || useTTSAnnouncements) {
RailwayData.useRoutesAndStationsFromIndex(stopIndex, routeIds, ClientData.DATA_CACHE, (thisRoute, nextRoute, thisStation, nextStation, lastStation) -> {
final List<String> messages = new ArrayList<>();
final String thisRouteSplit = thisRoute.name.split("\\|\\|")[0];
final String nextRouteSplit = nextRoute == null ? null : nextRoute.name.split("\\|\\|")[0];
if (nextStation != null) {
final boolean isLightRailRoute = thisRoute.isLightRailRoute;
messages.add(IGui.insertTranslation(isLightRailRoute ? "gui.mtr.next_station_light_rail_announcement_cjk" : "gui.mtr.next_station_announcement_cjk", isLightRailRoute ? "gui.mtr.next_station_light_rail_announcement" : "gui.mtr.next_station_announcement", 1, nextStation.name));
final Map<Integer, ClientCache.ColorNamePair> routesInStation = ClientData.DATA_CACHE.stationIdToRoutes.get(nextStation.id);
if (routesInStation != null) {
final List<String> interchangeRoutes = routesInStation.values().stream().filter(interchangeRoute -> {
final String routeName = interchangeRoute.name.split("\\|\\|")[0];
return !routeName.equals(thisRouteSplit) && (nextRoute == null || !routeName.equals(nextRouteSplit));
}).map(interchangeRoute -> interchangeRoute.name).collect(Collectors.toList());
final String mergedStations = IGui.mergeStations(interchangeRoutes, ", ");
if (!mergedStations.isEmpty()) {
messages.add(IGui.insertTranslation("gui.mtr.interchange_announcement_cjk", "gui.mtr.interchange_announcement", 1, mergedStations));
}
}
if (lastStation != null && nextStation.id == lastStation.id && nextRoute != null && !nextRoute.platformIds.isEmpty() && !nextRouteSplit.equals(thisRouteSplit)) {
final Station nextFinalStation = ClientData.DATA_CACHE.platformIdToStation.get(nextRoute.platformIds.get(nextRoute.platformIds.size() - 1));
if (nextFinalStation != null) {
if (nextRoute.isLightRailRoute) {
messages.add(IGui.insertTranslation("gui.mtr.next_route_light_rail_announcement_cjk", "gui.mtr.next_route_light_rail_announcement", nextRoute.lightRailRouteNumber, 1, nextFinalStation.name.split("\\|\\|")[0]));
} else {
messages.add(IGui.insertTranslation("gui.mtr.next_route_announcement_cjk", "gui.mtr.next_route_announcement", 2, nextRouteSplit, nextFinalStation.name.split("\\|\\|")[0]));
}
}
}
}
IDrawing.narrateOrAnnounce(IGui.mergeStations(messages, " "));
});
}
}, (stopIndex, routeIds) -> {
if (useTTSAnnouncements) {
RailwayData.useRoutesAndStationsFromIndex(stopIndex, routeIds, ClientData.DATA_CACHE, (thisRoute, nextRoute, thisStation, nextStation, lastStation) -> {
if (thisRoute.isLightRailRoute && lastStation != null) {
IDrawing.narrateOrAnnounce(IGui.insertTranslation("gui.mtr.light_rail_route_announcement_cjk", "gui.mtr.light_rail_route_announcement", thisRoute.lightRailRouteNumber, 1, lastStation.name));
}
});
}
}));
if (!Config.hideTranslucentParts()) {
ClientData.TRAINS.forEach(TrainClient::renderTranslucent);
}
matrices.translate(-cameraPos.x, 0.0625 + SMALL_OFFSET - cameraPos.y, -cameraPos.z);
final boolean renderColors = Utilities.isHolding(player, item -> item instanceof ItemNodeModifierBase || Block.getBlockFromItem(item) instanceof BlockSignalLightBase || Block.getBlockFromItem(item) instanceof BlockSignalSemaphoreBase);
final int maxRailDistance = renderDistanceChunks * 16;
ClientData.RAILS.forEach((startPos, railMap) -> railMap.forEach((endPos, rail) -> {
if (!RailwayData.isBetween(player.getX(), startPos.getX(), endPos.getX(), maxRailDistance) || !RailwayData.isBetween(player.getZ(), startPos.getZ(), endPos.getZ(), maxRailDistance)) {
return;
}
rail.render((x1, z1, x2, z2, x3, z3, x4, z4, y1, y2) -> {
final BlockPos pos2 = new BlockPos(x1, y1, z1);
if (shouldNotRender(pos2, maxRailDistance, null)) {
return;
}
final int light2 = LightmapTextureManager.pack(world.getLightLevel(LightType.BLOCK, pos2), world.getLightLevel(LightType.SKY, pos2));
if (rail.railType == RailType.NONE) {
if (renderColors) {
final VertexConsumer vertexConsumerArrow = vertexConsumers.getBuffer(MoreRenderLayers.getExterior(new Identifier("mtr:textures/block/one_way_rail_arrow.png")));
IDrawing.drawTexture(matrices, vertexConsumerArrow, (float) x1, (float) y1, (float) z1, (float) x2, (float) y1 + SMALL_OFFSET, (float) z2, (float) x3, (float) y2, (float) z3, (float) x4, (float) y2 + SMALL_OFFSET, (float) z4, 0, 0.25F, 1, 0.75F, Direction.UP, -1, light2);
IDrawing.drawTexture(matrices, vertexConsumerArrow, (float) x2, (float) y1 + SMALL_OFFSET, (float) z2, (float) x1, (float) y1, (float) z1, (float) x4, (float) y2 + SMALL_OFFSET, (float) z4, (float) x3, (float) y2, (float) z3, 0, 0.25F, 1, 0.75F, Direction.UP, -1, light2);
}
} else {
final float textureOffset = (((int) (x1 + z1)) % 4) * 0.25F;
final int color = renderColors || !Config.hideSpecialRailColors() && rail.railType.hasSavedRail ? rail.railType.color : -1;
final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(MoreRenderLayers.getExterior(new Identifier("textures/block/rail.png")));
IDrawing.drawTexture(matrices, vertexConsumer, (float) x1, (float) y1, (float) z1, (float) x2, (float) y1 + SMALL_OFFSET, (float) z2, (float) x3, (float) y2, (float) z3, (float) x4, (float) y2 + SMALL_OFFSET, (float) z4, 0, 0.1875F + textureOffset, 1, 0.3125F + textureOffset, Direction.UP, color, light2);
IDrawing.drawTexture(matrices, vertexConsumer, (float) x4, (float) y2 + SMALL_OFFSET, (float) z4, (float) x3, (float) y2, (float) z3, (float) x2, (float) y1 + SMALL_OFFSET, (float) z2, (float) x1, (float) y1, (float) z1, 0, 0.1875F + textureOffset, 1, 0.3125F + textureOffset, Direction.UP, color, light2);
}
}, -1, 1);
if (renderColors) {
final List<SignalBlocks.SignalBlock> signalBlocks = ClientData.SIGNAL_BLOCKS.getSignalBlocksAtTrack(PathData.getRailProduct(startPos, endPos));
final float width = 1F / DyeColor.values().length;
for (int i = 0; i < signalBlocks.size(); i++) {
final SignalBlocks.SignalBlock signalBlock = signalBlocks.get(i);
final boolean shouldGlow = signalBlock.isOccupied() && (((int) Math.floor(getGameTicks())) % TICKS_PER_SECOND) < TICKS_PER_SECOND / 2;
final VertexConsumer vertexConsumer = shouldGlow ? vertexConsumers.getBuffer(MoreRenderLayers.getLight(new Identifier("mtr:textures/block/white.png"), false)) : vertexConsumers.getBuffer(MoreRenderLayers.getExterior(new Identifier("textures/block/white_wool.png")));
final float u1 = width * i + 1 - width * signalBlocks.size() / 2;
final float u2 = u1 + width;
final int color = ARGB_BLACK + signalBlock.color.getMapColor().color;
rail.render((x1, z1, x2, z2, x3, z3, x4, z4, y1, y2) -> {
final BlockPos pos2 = new BlockPos(x1, y1, z1);
if (shouldNotRender(pos2, maxRailDistance, null)) {
return;
}
final int light2 = shouldGlow ? MAX_LIGHT_GLOWING : LightmapTextureManager.pack(world.getLightLevel(LightType.BLOCK, pos2), world.getLightLevel(LightType.SKY, pos2));
IDrawing.drawTexture(matrices, vertexConsumer, (float) x1, (float) y1, (float) z1, (float) x2, (float) y1 + SMALL_OFFSET, (float) z2, (float) x3, (float) y2, (float) z3, (float) x4, (float) y2 + SMALL_OFFSET, (float) z4, u1, 0, u2, 1, Direction.UP, color, light2);
IDrawing.drawTexture(matrices, vertexConsumer, (float) x4, (float) y2 + SMALL_OFFSET, (float) z4, (float) x3, (float) y2, (float) z3, (float) x2, (float) y1 + SMALL_OFFSET, (float) z2, (float) x1, (float) y1, (float) z1, u1, 0, u2, 1, Direction.UP, color, light2);
IDrawing.drawTexture(matrices, vertexConsumer, (float) x1, (float) y1, (float) z1, (float) x2, (float) y1 + SMALL_OFFSET / 2, (float) z2, (float) x3, (float) y2, (float) z3, (float) x4, (float) y2 + SMALL_OFFSET / 2, (float) z4, 0, 0, 1, 1, Direction.UP, color, light2);
IDrawing.drawTexture(matrices, vertexConsumer, (float) x4, (float) y2 + SMALL_OFFSET / 2, (float) z4, (float) x3, (float) y2, (float) z3, (float) x2, (float) y1 + SMALL_OFFSET / 2, (float) z2, (float) x1, (float) y1, (float) z1, 0, 0, 1, 1, Direction.UP, color, light2);
}, u1 - 1, u2 - 1);
}
}
}));
if (prevPlatformCount != ClientData.PLATFORMS.size() || prevSidingCount != ClientData.SIDINGS.size()) {
ClientData.DATA_CACHE.sync();
}
prevPlatformCount = ClientData.PLATFORMS.size();
prevSidingCount = ClientData.SIDINGS.size();
ClientData.DATA_CACHE.clearDataIfNeeded();
}
public static float getGameTicks() {
return gameTick;
}
public static boolean canPlaySound() {
if (gameTick - lastPlayedTrainSoundsTick >= TICKS_PER_SPEED_SOUND) {
lastPlayedTrainSoundsTick = gameTick;
}
return gameTick == lastPlayedTrainSoundsTick && !MinecraftClient.getInstance().isPaused();
}
public static boolean shouldNotRender(BlockPos pos, int maxDistance, Direction facing) {
final Entity camera = MinecraftClient.getInstance().cameraEntity;
return shouldNotRender(camera, pos, maxDistance, facing);
}
public static void clearTextureAvailability() {
AVAILABLE_TEXTURES.clear();
UNAVAILABLE_TEXTURES.clear();
}
private static boolean shouldNotRender(Entity camera, BlockPos pos, int maxDistance, Direction facing) {
final boolean playerFacingAway;
if (facing == null) {
playerFacingAway = false;
} else {
if (facing.getAxis() == Direction.Axis.X) {
final double playerXOffset = camera.getX() - pos.getX() - 0.5;
playerFacingAway = Math.signum(playerXOffset) == facing.getOffsetX() && Math.abs(playerXOffset) >= 0.5;
} else {
final double playerZOffset = camera.getZ() - pos.getZ() - 0.5;
playerFacingAway = Math.signum(playerZOffset) == facing.getOffsetZ() && Math.abs(playerZOffset) >= 0.5;
}
}
return camera == null || playerFacingAway || camera.getBlockPos().getManhattanDistance(pos) > (MTRClient.isReplayMod ? MAX_RADIUS_REPLAY_MOD : maxDistance);
}
private static void renderWithLight(World world, double x, double y, double z, Vec3d cameraPos, boolean offsetRender, RenderCallback renderCallback) {
final BlockPos posAverage = offsetRender ? new BlockPos(cameraPos).add(x, y, z) : new BlockPos(x, y, z);
if (!shouldNotRender(posAverage, MinecraftClient.getInstance().options.viewDistance * 8, null)) {
renderCallback.renderCallback(LightmapTextureManager.pack(world.getLightLevel(LightType.BLOCK, posAverage), world.getLightLevel(LightType.SKY, posAverage)), posAverage);
}
}
private static Text getStationText(Station station, String textKey) {
if (station != null) {
return Text.of(IGui.formatStationName(IGui.insertTranslation("gui.mtr." + textKey + "_station_cjk", "gui.mtr." + textKey + "_station", 1, IGui.textOrUntitled(station.name))));
} else {
return new LiteralText("");
}
}
private static void drawTexture(MatrixStack matrices, VertexConsumer vertexConsumer, Vec3d pos1, Vec3d pos2, Vec3d pos3, Vec3d pos4, int light) {
IDrawing.drawTexture(matrices, vertexConsumer, (float) pos1.x, (float) pos1.y, (float) pos1.z, (float) pos2.x, (float) pos2.y, (float) pos2.z, (float) pos3.x, (float) pos3.y, (float) pos3.z, (float) pos4.x, (float) pos4.y, (float) pos4.z, 0, 0, 1, 1, Direction.UP, -1, light);
}
private static Identifier resolveTexture(TrainClientRegistry.TrainProperties trainProperties, Function<String, String> formatter) {
final String textureString = formatter.apply(trainProperties.textureId);
final Identifier id = new Identifier(textureString);
final boolean available;
if (!AVAILABLE_TEXTURES.contains(textureString) && !UNAVAILABLE_TEXTURES.contains(textureString)) {
available = MinecraftClient.getInstance().getResourceManager().containsResource(id);
(available ? AVAILABLE_TEXTURES : UNAVAILABLE_TEXTURES).add(textureString);
if (!available) {
System.out.println("Texture " + textureString + " not found, using default");
}
} else {
available = AVAILABLE_TEXTURES.contains(textureString);
}
return available ? id : new Identifier(formatter.apply(TrainClientRegistry.getTrainProperties(trainProperties.baseTrainType.toString(), trainProperties.baseTrainType).textureId));
}
private static Identifier getConnectorTextureString(TrainClientRegistry.TrainProperties trainProperties, String connectorPart) {
return resolveTexture(trainProperties, textureId -> textureId + "_connector_" + connectorPart + ".png");
}
@FunctionalInterface
private interface RenderCallback {
void renderCallback(int light, BlockPos posAverage);
}
}
|
package com.patreon;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.github.jasminb.jsonapi.DeserializationFeature;
import com.github.jasminb.jsonapi.JSONAPIDocument;
import com.github.jasminb.jsonapi.ResourceConverter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.patreon.resources.campaign.PatreonCampaign;
import com.patreon.resources.campaign.PatreonCampaignResponse;
import com.patreon.resources.pledge.Pledge;
import com.patreon.resources.pledge.PledgeResponse;
import com.patreon.resources.user.PatreonUser;
import org.jsoup.Jsoup;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class PatreonAPI {
private final String accessToken;
public static final Gson gson = new GsonBuilder().serializeNulls().enableComplexMapKeySerialization().create();
private ResourceConverter converter;
public PatreonAPI(String accessToken) {
this.accessToken = accessToken;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
this.converter = new ResourceConverter(
objectMapper,
PatreonUser.class,
PatreonCampaign.class,
Pledge.class
);
this.converter.enableDeserializationOption(DeserializationFeature.ALLOW_UNKNOWN_INCLUSIONS);
}
/**
* Get the user object of the creator
*
* @return JSONAPIDocument<PatreonUser> containing all data pertaining to the current user
* @throws IOException Thrown when the GET request failed
*/
public JSONAPIDocument<PatreonUser> fetchUser() throws IOException {
return converter.readDocument(
getDataStream("current_user"),
PatreonUser.class
);
}
/**
* Get a list of campaigns the current creator is running - also contains other related data like Goals
* Note: The first campaign data object is located at index 0 in the data list
*
* @return JSONAPIDocument<List<PatreonCampaign>> containing the above-mentioned data
* @throws IOException Thrown when the GET request failed
*/
public JSONAPIDocument<List<PatreonCampaign>> fetchCampaigns() throws IOException {
return converter.readDocumentCollection(
getDataStream("current_user/campaigns?include=rewards,creator,goals"),
PatreonCampaign.class
);
}
/**
* Retrieve pledges for the specified campaign
*
* @param campaignId id for campaign to retrieve
* @param pageSize how many pledges to return
* @param pageCursor ignore, put null.
* @return JSONAPIDocument<List<Pledge>> containing pledges & associated data
* @throws IOException Thrown when the GET request failed
*/
public JSONAPIDocument<List<Pledge>> fetchPageOfPledges(String campaignId, int pageSize, String pageCursor) throws IOException {
String url = "campaigns/" + campaignId + "/pledges?page%5Bcount%5D=" + pageSize;
if (pageCursor != null) url += "&page%5Bcursor%5D=" + pageCursor;
return converter.readDocumentCollection(
getDataStream(url),
Pledge.class
);
}
private String getJson(String suffix) throws IOException {
return Jsoup.connect("https://api.patreon.com/oauth2/api/" + suffix)
.ignoreContentType(true).header("Authorization", "Bearer " + accessToken).get().body().text();
}
private InputStream getDataStream(String suffix) {
try {
String prefix = "https://api.patreon.com/oauth2/api/";
URL url = new URL(prefix.concat(suffix));
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Authorization", "Bearer ".concat(this.accessToken));
return connection.getInputStream();
} catch (IOException e) {
System.out.println(e.getMessage());
}
return null;
}
public static <E> E toObject(String str, Class<E> clazz) {
return gson.fromJson(str, clazz);
}
}
|
package net.imagej.ops;
/**
* An {@link HybridOp} is a {@link ComputerOp} which is able to create the
* output object itself. Hence, the "out" parameter is marked optional (i.e.,
* "required = false") and may be omitted, in which case it will be created
* based on the given "in" parameter.
*
* @author Christian Dietz (University of Konstanz)
*/
public interface HybridOp<I, O> extends ComputerOp<I, O>, FunctionOp<I, O> {
/**
* Compute the output of a function, given some input.
*
* @param input
* of the {@link HybridOp}
*
* @return output
*/
@Override
O compute(I input);
/**
* @return create an output object of type O, given some input. The output
* can then be used to call compute(I input, O output), which will
* fill the output with the result.
*/
O createOutput(I input);
@Override
HybridOp<I, O> getIndependentInstance();
}
|
package nuclibook.models;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import nuclibook.server.Renderable;
import java.util.HashMap;
/**
* Model to represent a tracer.
*/
@DatabaseTable(tableName = "tracers")
public class Tracer implements Renderable {
@DatabaseField(generatedId = true)
private Integer id;
@DatabaseField(width = 64)
private String name;
@DatabaseField(columnName = "order_time")
private int orderTime;
@DatabaseField(defaultValue = "true")
private Boolean enabled;
/**
* Gets the ID of the tracer.
*
* @return the ID of the tracer.
*/
public Integer getId() {
return id;
}
/**
* Sets the ID of the tracer.
*
* @param id the ID of the tracer.
*/
public void setId(Integer id) {
this.id = id;
}
/**
* Gets the name of the tracer.
*
* @return the name of the tracer.
*/
public String getName() {
return name;
}
/**
* Sets the name of the tracer.
*
* @param name the name of the tracer.
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the lead order time of the tracer.
*
* @return the lead order time of the tracer.
*/
public int getOrderTime() {
return orderTime;
}
/**
* Sets the lead order time of the tracer.
*
* @param orderTime the lead order time of the tracer.
*/
public void setOrderTime(int orderTime) {
this.orderTime = orderTime;
}
/**
* Gets whether it's enabled.
*
* @return whether it's enabled.
*/
public Boolean getEnabled() {
return enabled;
}
/**
* Sets whether it's enabled.
*
* @param enabled whether it's enabled.
*/
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
@Override
public HashMap<String, String> getHashMap() {
return new HashMap<String, String>() {{
put("id", getId().toString());
put("tracer-id", getId().toString());
put("name", getName());
put("tracer-name", getName());
put("order-time", ((Integer) getOrderTime()).toString());
}};
}
}
|
package core.index;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class LockManager {
// locks for posting list
ReadWriteLock[] postsLocks;
// any operation to the version set needs to occupy this lock
ReadWriteLock versionLock;
public static LockManager instance = new LockManager();
boolean bootstrap = false;
private LockManager() {
postsLocks = new ReadWriteLock[1024];
versionLock = new ReentrantReadWriteLock();
for (int i = 0; i < 1024; i++) {
postsLocks[i] = new ReentrantReadWriteLock();
}
}
public void setBootStrap() {
bootstrap ^= bootstrap;
}
public void postReadLock(int keyword) {
postsLocks[keyword % postsLocks.length].readLock().lock();
}
public void postReadUnLock(int keyword) {
postsLocks[keyword % postsLocks.length].readLock().unlock();
}
public void postWriteLock(int keyword) {
postsLocks[keyword % postsLocks.length].writeLock().lock();
}
public void postWriteUnLock(int keyword) {
postsLocks[keyword % postsLocks.length].writeLock().unlock();
}
public void versionReadLock() {
versionLock.readLock().lock();
}
public void versionReadUnLock() {
versionLock.readLock().unlock();
}
public void versionWriteLock() {
versionLock.writeLock().lock();
}
public void versionWriteUnLock() {
versionLock.writeLock().unlock();
}
}
|
package org.charlie.chess;
import org.charlie.chess.directions.Black;
import org.charlie.chess.directions.NeighboringSquareDirection;
import org.charlie.chess.directions.White;
import org.charlie.chess.moves.ChessMove;
import org.charlie.chess.moves.Moves;
import org.charlie.chess.pieces.*;
import org.charlie.chess.players.Player;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Board {
private final Moves moves;
private Piece[][] board;
private boolean hasWinner;
private GameResult gameResult;
private Map<Player, Set<Piece>> pieces = new HashMap<>();
public Board(Piece[][] board, Moves moves) {
this.board = board;
this.moves = moves;
}
public Board copy() {
Piece[][] pieces = new Piece[board.length][];
for (int i = 0; i < board.length; i++) {
Piece[] aMatrix = board[i];
int aLength = aMatrix.length;
pieces[i] = new Piece[aLength];
System.arraycopy(aMatrix, 0, pieces[i], 0, aLength);
}
return new Board(pieces, moves.copy());
}
public boolean hasNoWinner() {
return !hasWinner;
}
public void setUpBoard(Player white, Player black) {
pieces.clear();
Set<Piece> whitePieces = new HashSet<>();
Set<Piece> blackPieces = new HashSet<>();
assert (board.length == 8);
assert (board[0].length == 8);
King whiteKing = new King(white, black, new Square(0, 4));
whitePieces.add(whiteKing);
King blackKing = new King(black, white, new Square(7, 4));
board[0][4] = whiteKing;
board[7][4] = blackKing;
board[0][0] = new Rook(white, new Square(0, 0), whiteKing, blackKing);
board[0][1] = new Knight(white, new Square(0, 1), whiteKing, blackKing);
board[0][2] = new Bishop(white, new Square(0, 2), whiteKing, blackKing);
board[0][3] = new Queen(white, new Square(0, 3), whiteKing, blackKing);
board[0][5] = new Bishop(white, new Square(0, 5), whiteKing, blackKing);
board[0][6] = new Knight(white, new Square(0, 6), whiteKing, blackKing);
board[0][7] = new Rook(white, new Square(0, 7), whiteKing, blackKing);
Piece[] whitePanwRow = board[1];
for (int i = 0; i < whitePanwRow.length; i++) {
whitePanwRow[i] = new Pawn(white, new Square(1, i), new White(), whiteKing, blackKing);
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 8; j++) {
whitePieces.add(board[i][j]);
}
}
board[7][0] = new Rook(black, new Square(7, 0), blackKing, whiteKing);
board[7][1] = new Knight(black, new Square(7, 1), blackKing, whiteKing);
board[7][2] = new Bishop(black, new Square(7, 2), blackKing, whiteKing);
board[7][3] = new Queen(black, new Square(7, 3), blackKing, whiteKing);
board[7][5] = new Bishop(black, new Square(7, 5), blackKing, whiteKing);
board[7][6] = new Knight(black, new Square(7, 6), blackKing, whiteKing);
board[7][7] = new Rook(black, new Square(7, 7), blackKing, whiteKing);
Piece[] blackPawnRow = board[6];
for (int i = 0; i < blackPawnRow.length; i++) {
blackPawnRow[i] = new Pawn(black, new Square(1, i), new Black(), blackKing, whiteKing);
}
for (int i = 6; i < 8; i++) {
for (int j = 0; j < 8; j++) {
whitePieces.add(board[i][j]);
}
}
pieces.put(white, whitePieces);
pieces.put(black, blackPieces);
}
public void move(Player movingPlayer) {
final ChessMove chessMove = movingPlayer.selectMove(copy());
chessMove.move(this);
moves.addLastMove(chessMove);
}
public ChessMove getLastMove() {
return moves.getLastMove();
}
public Piece getPieceAt(Square square) {
if (isLocationOnBoard(square)) {
return board[square.getX()][square.getY()];
}
return null;
}
public void setNullAt(Square square) {
board[square.getX()][square.getY()] = null;
}
public void setPieceAt(Square square, Piece piece) {
board[square.getX()][square.getY()] = piece;
}
public GameResult getResults() {
return gameResult;
}
public void setHasWinner(Player winner, Player loser) {
this.gameResult = new GameResult(winner, loser, moves);
this.hasWinner = true;
}
public boolean isPieceAt(Square square) {
return isLocationOnBoard(square) && getPieceAt(square) != null;
}
public boolean isOpponentsPieceAt(Square square, Player owner) {
return isPieceAt(square) && !getPieceAt(square).isOwnedBy(owner);
}
public boolean myPieceIsAt(Square square, Player owner) {
return isPieceAt(square) && getPieceAt(square).isOwnedBy(owner);
}
private boolean isLocationOnBoard(Square square) {
return square.getY() >= 0 && square.getY() <= 7 && square.getX() >= 0 && square.getX() <= 7;
}
public Square getEmptySquareOrEnemySquareOrOriginalSquare(Square src, NeighboringSquareDirection neighboringSquareDirection, Player owner) {
switch (neighboringSquareDirection) {
case Left: {
Square leftMostSquare = new Square(src.getX(), 0);
int distance = Math.abs(src.getY() - leftMostSquare.getY());
for (int i = 1; i < distance; i++) {
Square nextSquare = new Square(src.getX(), src.getY() - i);
if (isOpponentsPieceAt(nextSquare, owner)) {
return nextSquare;
}
if (myPieceIsAt(nextSquare, owner)) {
return new Square(nextSquare.getX(), nextSquare.getY() + 1);
}
}
return leftMostSquare;
}
case Right: {
Square rightMostSquare = new Square(src.getX(), 7);
int distance = Math.abs(src.getY() - rightMostSquare.getY());
for (int i = 1; i < distance; i++) {
Square nextSquare = new Square(src.getX(), src.getY() + i);
if (isOpponentsPieceAt(nextSquare, owner)) {
return nextSquare;
}
if (myPieceIsAt(nextSquare, owner)) {
return new Square(nextSquare.getX(), nextSquare.getY() - 1);
}
}
return rightMostSquare;
}
case Forward: {
Square topMostSquare = new Square(0, src.getY());
int distance = Math.abs(src.getX() - topMostSquare.getX());
for (int i = 0; i < distance; i++) {
Square nextSquare = new Square(src.getX() - i, src.getY());
if (isOpponentsPieceAt(nextSquare, owner)) {
return nextSquare;
}
if (myPieceIsAt(nextSquare, owner)) {
return new Square(nextSquare.getX() + 1, src.getY());
}
}
return topMostSquare;
}
case Backward: {
Square bottomMostSquare = new Square(7, src.getY());
int distance = Math.abs(src.getX() - bottomMostSquare.getX());
for (int i = 0; i < distance; i++) {
Square nextSquare = new Square(src.getX() + 1, src.getY());
if (isOpponentsPieceAt(nextSquare, owner)) {
return nextSquare;
}
if (myPieceIsAt(nextSquare, owner)) {
return new Square(nextSquare.getX() - 1, src.getY());
}
}
return bottomMostSquare;
}
case ForwardLeft: {
int xDist = Math.abs(src.getX() - 0);
int yDist = Math.abs(src.getY() - 0);
int distance = Math.min(xDist, yDist);
Square furthest = new Square(src.getX() - distance, src.getY() - distance);
for (int i = 0; i < distance; i++) {
Square nextSquare = new Square(src.getX() - i, src.getY() - i);
if (isOpponentsPieceAt(nextSquare, owner)) {
return nextSquare;
}
if (myPieceIsAt(nextSquare, owner)) {
return new Square(nextSquare.getX() + 1, nextSquare.getY() + 1);
}
}
return furthest;
}
case ForwardRight: {
int xDist = Math.abs(src.getX() - 0);
int yDist = Math.abs(src.getY() - 7);
int distance = Math.min(xDist, yDist);
Square furthest = new Square(src.getX() - distance, src.getY() + distance);
for (int i = 0; i < distance; i++) {
Square nextSquare = new Square(src.getX() - i, src.getY() + i);
if (isOpponentsPieceAt(nextSquare, owner)) {
return nextSquare;
}
if (myPieceIsAt(nextSquare, owner)) {
return new Square(nextSquare.getX() + 1, nextSquare.getY() - 1);
}
}
return furthest;
}
case BackwardRight: {
int xDist = Math.abs(src.getX() - 7);
int yDist = Math.abs(src.getY() - 7);
int distance = Math.min(xDist, yDist);
Square furthest = new Square(src.getX() + distance, src.getY() + distance);
for (int i = 0; i < distance; i++) {
Square nextSquare = new Square(src.getX() + i, src.getY() + i);
if (isOpponentsPieceAt(nextSquare, owner)) {
return nextSquare;
}
if (myPieceIsAt(nextSquare, owner)) {
return new Square(nextSquare.getX() - 1, nextSquare.getY() - 1);
}
}
return furthest;
}
case BackwardLeft: {
int xDist = Math.abs(src.getX() - 7);
int yDist = Math.abs(src.getY() - 0);
int distance = Math.min(xDist, yDist);
Square furthest = new Square(src.getX() + distance, src.getY() - distance);
for (int i = 0; i < distance; i++) {
Square nextSquare = new Square(src.getX() + i, src.getY() - i);
if (isOpponentsPieceAt(nextSquare, owner)) {
return nextSquare;
}
if (myPieceIsAt(nextSquare, owner)) {
return new Square(nextSquare.getX() - 1, nextSquare.getY() + 1);
}
}
return furthest;
}
case NotNeighbor: {
throw new UnsupportedOperationException("Do not call this method withn NotNeighbor");
}
}
throw new UnsupportedOperationException("Should not get here");
}
public King getOpponentKingAt(Square location, Player owner) {
if (isOpponentKingAt(location, owner)) {
return (King) getPieceAt(location);
}
return null;
}
public boolean isOpponentKingAt(Square location, Player owner) {
return isOpponentsPieceAt(location, owner) && getPieceAt(location).isKing();
}
public PossibleMoves getPossibleMovesFor(Player owner) {
Set<Piece> ownerPieces = pieces.get(owner);
PossibleMoves normalChessMoves = new PossibleMoves();
for (Piece piece : ownerPieces) {
normalChessMoves.addMoves(piece.getPossibleMoves(copy()));
}
return normalChessMoves;
}
public boolean isPieceBetween(Square src, Square dest) {
Set<Square> squares = src.locationsBetween(dest);
boolean isBetween = false;
for (Square square : squares) {
isBetween = isPieceAt(square);
if (isBetween) {
break;
}
}
return isLocationOnBoard(src) && isLocationOnBoard(dest) && isBetween;
}
public void markAsTaken(Piece piece, Player owner) {
Set<Piece> pieceSet = pieces.get(owner);
pieceSet.remove(piece);
}
}
|
package de.fau.osr.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.*;
import de.fau.osr.bl.RequirementsTraceabilityMatrix;
import de.fau.osr.bl.RequirementsTraceabilityMatrixByImpact;
import de.fau.osr.core.vcs.base.CommitFile;
import de.fau.osr.gui.GuiViewElementHandler.ButtonState;
import de.fau.osr.gui.util.SpiceTraceabilityProgressBar;
/*
* View part of the MVC. This Class is responsible for the setting up the UI and interacting with the
* Elements. Whenever the texts or functionality of UI-Elements are changed, this class must be called.
*/
public class GuiView{
public static class HighlightedLine{
String line;
boolean highlighted;
public HighlightedLine(String line, boolean hightlighted){
this.line = line;
this.highlighted = hightlighted;
}
}
private class HighlightedLine_Renderer implements ListCellRenderer<HighlightedLine>{
protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
@Override
public Component getListCellRendererComponent(
JList<? extends HighlightedLine> list, HighlightedLine value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(value.highlighted){
renderer.setForeground(Color.RED);
}
renderer.setText(value.line);
return renderer;
}
}
/**
* Displays each CommitFile by file name, cell highlighting and impact percentage
*/
private class CommitFile_ImpactRenderer implements ListCellRenderer<CommitFile> {
protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
@Override
public Component getListCellRendererComponent(
JList<? extends CommitFile> list, CommitFile value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
switch(value.commitState){
case MODIFIED:
renderer.setBackground(Color.YELLOW);
break;
case ADDED:
renderer.setBackground(Color.GREEN);
break;
case DELETED:
renderer.setBackground(Color.RED);
break;
default:
renderer.setBackground(Color.WHITE);
break;
}
renderer.setText(String.format("%s - %f", value.newPath, value.impact));
return renderer;
}
}
/**
* Displays each CommitFile by just file name.
*/
private class CommitFile_SimpleFilenameRenderer implements ListCellRenderer<CommitFile> {
protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
@Override
public Component getListCellRendererComponent(
JList<? extends CommitFile> list, CommitFile value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
renderer.setText(value.newPath.getPath());
return renderer;
}
}
//The UI-Elements themselves are handled by the Element Handler.
private GuiViewElementHandler elementHandler;
GuiView(GuiController guiController) {
elementHandler = new GuiViewElementHandler(guiController);
}
/*
* Setting up the initial Dialog to choose the Repository.
* @return File to the chosen directory. Keep in mind, that the file is not checked yet.
* @throws IOException whenever the user cancels the Dialog.
* (This can not be solved)
*/
File Repo_OpeningDialog() throws IOException{
JFileChooser chooser = new JFileChooser("..");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileHidingEnabled(false);
int returnValue = chooser.showDialog(null,"Auswahl des Repository");
if (returnValue == JFileChooser.APPROVE_OPTION) {
return chooser.getSelectedFile();
}else {
throw new IOException("Fehler bei er Repository Auswahl");
}
}
/*
* Opening the initial Dialog to choose a Pattern for searching for requirements in commit messages
* or external sources.
* @return String containing the directly the user input. Not yet checked whether it's a proper pattern
*/
String Pattern_OpeningDialog(String currentPattern) {
String msg = "Gebe \"Requirement-Pattern\" als RegExp ein.\n" +
"Mehrere \"Requirement-Pattern\" müssen gemäß der RegExp-Syntax\n" +
"mit | (Pipe) getrennt eingegeben werden.";
return JOptionPane.showInputDialog(msg, currentPattern);
}
/*
* Method to open a option dialog for configuration where user can select which
* configuration needs to be modified
* @return integer containing the option selected for configuration (TODO int to be converted to
* a proper enum)
*/
int Configure_OptionDialog(){
Object[] options = { "Change Repository", "Change Requirement Pattern"};
return JOptionPane.showOptionDialog(null, "Choose to Configure", "SpiceTraceability Configuration", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
}
/*
* Creating the UI. Frame + Elements
*/
void showView() {
elementHandler.setVisible(true);
}
/*
* Showing an Dialog to the User. Marked as Error dialog.
* @parameter message to be presented to the user
*/
void showErrorDialog(String message) {
JOptionPane.showMessageDialog(null, message, "Fehler", JOptionPane.ERROR_MESSAGE);
}
/*
* Showing a dialog to the user. Marked as Information dialog
* @parameter message to be presented to the user
*/
void showInformationDialog(String message) {
JOptionPane.showMessageDialog(null, message, "Information", JOptionPane.INFORMATION_MESSAGE);
}
/*
* Clearing all scrollpanes. Containing the Code_ScrollPane. And clearing all Textfields.
* Deactivating Linkage_Button
* Color is set to the initial white.
*/
void clearAll(){
clearRequirements();
clearCommits();
clearFiles();
clearCode();
clearImpactPercentage();
elementHandler.getCommit_textField().setText("");
elementHandler.getRequirementID_textField().setText("");
switchLinkage_Button(ButtonState.Deactivate);
}
void clearImpactPercentage() {
JPanel panelimpact = new JPanel(new GridLayout());
panelimpact.setBackground(Color.WHITE);
elementHandler.getImpactPercentage_scrollPane().setViewportView(panelimpact);
}
void clearFiles() {
JPanel panelfiles = new JPanel(new GridLayout());
panelfiles.setBackground(Color.WHITE);
elementHandler.getFiles_scrollPane().setViewportView(panelfiles);
// elementHandler.getReqIdsByLines_scrollPane().setViewportView(panelfiles);
}
void clearRequirements() {
JPanel panelrequirement = new JPanel(new GridLayout());
panelrequirement.setBackground(Color.WHITE);
elementHandler.getRequirementID_scrollPane().setViewportView(panelrequirement);
}
void clearCommits() {
JPanel panelcommit = new JPanel(new GridLayout());
panelcommit.setBackground(Color.WHITE);
elementHandler.getCommit_scrollPane().setViewportView(panelcommit);
}
void clearCode() {
JPanel panel = new JPanel(new GridLayout());
panel.setBackground(Color.WHITE);
elementHandler.getCode_scrollPane().setViewportView(panel);
panel = new JPanel(new GridLayout());
// panel.setBackground(UIManager.getColor("Panel.background"));
panel.setBackground(UIManager.getColor(Color.WHITE));
elementHandler.getRequirements2Lines_scrollPane().setViewportView(panel);
}
/*
* Showing all Elements of the JList parameter in the RequirementsID_Scrollpane
* @parameter requirements_JList containing the Elements to be displayed
*/
void showRequirements(JList<String> requirements_JList) {
JPanel panel = new JPanel(new GridLayout());
panel.add(requirements_JList);
elementHandler.getRequirementID_scrollPane().setViewportView(panel);
}
/*
* Showing all Elements of the JList parameter in the Commit_Scrollpane
* @parameter commitMessage_JList containing the Elements to be displayed
*/
void showCommits(JList<String> commitMessages_JList) {
JPanel panel = new JPanel(new GridLayout());
panel.add(commitMessages_JList);
elementHandler.getCommit_scrollPane().setViewportView(panel);
}
/*
* Showing all Elements of the JList parameter in the Files_Scrollpane
* WITH rendering.
* @parameter commitFile_JList containing the Elements to be displayed
*/
void showFiles(JList<CommitFile> commitFileName_JList) {
showFilesByGivenRenderer(commitFileName_JList, new CommitFile_ImpactRenderer());
}
/*
* Showing all Elements of the JList parameter in the Files_Scrollpane
* WITHOUT rendering.
* @parameter commitFile_JList containing the Elements to be displayed
*/
void showFilesWithoutRendering(JList<CommitFile> commitFileName_JList) {
showFilesByGivenRenderer(commitFileName_JList, new CommitFile_SimpleFilenameRenderer());
}
/**
* Will be called by public Methods *showFiles()* and *showFilesNoRendering*
* @author Taleh Didover
*/
private void showFilesByGivenRenderer(JList<CommitFile> commitFileName_JList, ListCellRenderer<CommitFile> renderer) {
JPanel panel = new JPanel(new GridLayout());
commitFileName_JList.setCellRenderer(renderer);
panel.add(commitFileName_JList);
elementHandler.getFiles_scrollPane().setViewportView(panel);
}
/*
* Showing the parameter String in the Code_Scrollpane.
* Until now. There is no further processing of the data. This will probably change
* with Req-11
* @parameter changeData String to be presented
*/
void showCode(JList<HighlightedLine> code_JList) {
JPanel panel = new JPanel(new GridLayout());
HighlightedLine_Renderer renderer = new HighlightedLine_Renderer();
code_JList.setCellRenderer(renderer);
panel.add(code_JList);
elementHandler.getCode_scrollPane().setViewportView(panel);
}
/**
* Show requirement ids for each code line.
* @author Taleh Didover
*/
void showRequirementIdsByLines(JList<String> requirements2Lines_JList) {
JPanel panel = new JPanel(new GridLayout());
panel.add(requirements2Lines_JList);
elementHandler.getRequirements2Lines_scrollPane().setViewportView(panel);
}
/*
* Adding a Mouselistener to the passed component
*/
void addMouseListener(JComponent component, MouseListener actListener){
component.addMouseListener(actListener);
}
void showLinkageRequirement(String requirementID) {
elementHandler.getRequirementID_textField().setText(requirementID);
}
void showLinkageCommit(String commit) {
elementHandler.getCommit_textField().setText(commit);
}
void switchLinkage_Button(ButtonState buttonState){
elementHandler.switchLinkageButton(buttonState);
}
/**
* shows the traceability matrix window with filled in data
* @param requirementsTraceabilityMatrix
*/
void showTraceabilityMatrix(RequirementsTraceabilityMatrix requirementsTraceabilityMatrix){
try {
TraceabilityMatrixViewHandler trMatrix = new TraceabilityMatrixViewHandler();
trMatrix.setRequirementsTraceabilityMatrix(requirementsTraceabilityMatrix);
trMatrix.initTable();
trMatrix.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
trMatrix.setVisible(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* shows the traceability matrix (by impact) window with filled in data
* @param requirementsTraceabilityMatrixByImpact the matrix which contains the info for traceability
*/
void showTraceabilityMatrixByImpact(RequirementsTraceabilityMatrixByImpact requirementsTraceabilityMatrixByImpact){
TraceabilityMatrixByImpactViewHandler trMatrixByImpact = new TraceabilityMatrixByImpactViewHandler();
trMatrixByImpact.setRequirementsTraceabilityMatrix(requirementsTraceabilityMatrixByImpact);
trMatrixByImpact.initTable();
trMatrixByImpact.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
trMatrixByImpact.setVisible(true);
}
/*
* method to show progress bar for the processing of traceability matrix by impact values
*/
void showTraceabilityMatrixByImpactProgressBar(){
final SpiceTraceabilityProgressBar progressBar = new SpiceTraceabilityProgressBar();
progressBar.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
progressBar.setProgressBarContent("Generating Traceability Matrix (by Impact)");
progressBar.setVisible(true);
class showTraceabilityMatrixByImpactProgressBarThread implements Runnable{
@Override
public void run() {
Boolean completion = false;
while(RequirementsTraceabilityMatrixByImpact.processProgress<=100){
progressBar.setProgressBarValue(RequirementsTraceabilityMatrixByImpact.processProgress);
try {
Thread.sleep(100);
if(completion)
break;
if(RequirementsTraceabilityMatrixByImpact.processProgress == 100){
completion = true;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
progressBar.dispatchEvent(new WindowEvent(progressBar, WindowEvent.WINDOW_CLOSING));
}
}
Thread tr = new Thread(new showTraceabilityMatrixByImpactProgressBarThread());
tr.start();
}
}
|
package org.lantern;
import static org.littleshoot.util.FiveTuple.Protocol.*;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;
import javax.net.ssl.SSLEngine;
import org.lantern.proxy.BaseChainedProxy;
import org.lantern.state.Peer;
import org.lantern.state.Peer.Type;
import org.littleshoot.proxy.TransportProtocol;
import org.littleshoot.util.FiveTuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class ProxyHolder extends BaseChainedProxy
implements Comparable<ProxyHolder> {
private static final Logger LOG = LoggerFactory
.getLogger(ProxyHolder.class);
private final ProxyTracker proxyTracker;
private final PeerFactory peerFactory;
private final LanternTrustStore lanternTrustStore;
private final URI jid;
private final FiveTuple fiveTuple;
private final boolean natTraversed;
/**
* <p>
* Once connecting to this proxy fails, this tracks the first time that
* connecting started failing. Once a connection is successful, this is set
* to 0.
* </p>
*
* <p>
* We start this at 1 on the assumption that the proxy is disconnected until
* proven otherwise.
* </p>
*/
private final AtomicLong timeOfOldestConsecFailure = new AtomicLong(1);
/**
* Tracks the time of the most recent failure since connecting to this proxy
* started failing.
*/
private final AtomicLong timeOfNewestConsecFailure = new AtomicLong(1);
private final Type type;
private volatile Peer peer;
public ProxyHolder(final ProxyTracker proxyTracker,
final PeerFactory peerFactory,
final LanternTrustStore lanternTrustStore,
final URI jid, final FiveTuple tuple,
final Type type, final boolean natTraversed,
final String lanternAuthToken) {
super(lanternAuthToken);
this.proxyTracker = proxyTracker;
this.peerFactory = peerFactory;
this.lanternTrustStore = lanternTrustStore;
this.jid = jid;
this.fiveTuple = tuple;
this.type = type;
this.natTraversed = natTraversed;
}
public FiveTuple getFiveTuple() {
return fiveTuple;
}
/**
* Get the {@link Peer} for this ProxyHolder, lazily looking it up from our
* {@link PeerFactory}.
*
* @return
*/
public Peer getPeer() {
if (peer == null) {
peer = peerFactory.peerForJid(jid);
}
return peer;
}
@Override
synchronized public String toString() {
Date oldestConsecFailure = null;
Date newestConsecFailure = null;
Date retryTime = null;
if (timeOfNewestConsecFailure.get() > 0) {
oldestConsecFailure = new Date(timeOfOldestConsecFailure.get());
newestConsecFailure = new Date(timeOfNewestConsecFailure.get());
retryTime = new Date(getRetryTime());
}
return "ProxyHolder [jid=" + jid + ", fiveTuple=" + fiveTuple
+ ", timeOfOldestConsecFailure=" + oldestConsecFailure
+ ", timeOfNewestConsecFailure=" + newestConsecFailure
+ ", retryTime=" + retryTime
+ ", type=" + type + "] connected? " + isConnected();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((fiveTuple == null) ? 0 : fiveTuple.hashCode());
result = prime * result + ((jid == null) ? 0 : jid.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProxyHolder other = (ProxyHolder) obj;
if (fiveTuple == null) {
if (other.fiveTuple != null)
return false;
} else if (!fiveTuple.equals(other.fiveTuple))
return false;
if (jid == null) {
if (other.jid != null)
return false;
} else if (!jid.equals(other.jid))
return false;
return true;
}
synchronized private void failuresStarted() {
long now = System.currentTimeMillis();
timeOfOldestConsecFailure.set(now);
timeOfNewestConsecFailure.set(now);
}
private void failuresContinued() {
timeOfNewestConsecFailure.set(System.currentTimeMillis());
}
synchronized public void markConnected() {
timeOfOldestConsecFailure.set(0l);
timeOfNewestConsecFailure.set(0l);
}
synchronized public void resetRetryInterval() {
timeOfNewestConsecFailure.set(timeOfOldestConsecFailure.get());
}
/**
* If this is a new proxy and our first attempt to connect fails, it is
* permitted to try falling back to connecting to the same peer via a NAT
* traversal.
*
* @return
*/
public boolean attemptNatTraversalIfConnectionFailed() {
return !isNatTraversed() &&
timeOfOldestConsecFailure.get() == 1l &&
timeOfNewestConsecFailure.get() == 1l;
}
synchronized public void failedToConnect() {
if (isConnected()) {
LOG.debug("Setting proxy as disconnected: {}", fiveTuple);
failuresStarted();
} else {
failuresContinued();
}
}
@Override
public int compareTo(ProxyHolder o) {
return (int) (getRetryTime() - o.getRetryTime());
}
synchronized public long getRetryTime() {
long timeDead = timeOfNewestConsecFailure.get()
- timeOfOldestConsecFailure.get();
if (timeDead <= 0) {
// First time retrying, 100 milliseconds
return timeOfNewestConsecFailure.get() + 5000;
} else {
// Back off exponentially up to a maximum of 5 seconds and at least
// 100 milliseconds
long waitTime = Math.max(timeDead, 100);
waitTime = Math.min(waitTime, 5000);
return timeOfNewestConsecFailure.get() + waitTime;
}
}
public URI getJid() {
return jid;
}
public Type getType() {
return type;
}
public boolean isConnected() {
return timeOfOldestConsecFailure.get() <= 0;
}
public boolean needsConnectionTest() {
return timeOfNewestConsecFailure.get() > 0;
}
/**
*
* @return
*/
public boolean isNatTraversed() {
return natTraversed;
}
/**
* We use the remote address of the {@link FiveTuple} as our chained proxy
* address.
*/
@Override
public InetSocketAddress getChainedProxyAddress() {
return fiveTuple.getRemote();
}
/**
* If the we are nat traversed, we use the local address of the
* {@link FiveTuple} as our local address from which to connect to the
* chained proxy, otherwise we leave this null to let the connection proceed
* from whatever available port.
*/
@Override
public InetSocketAddress getLocalAddress() {
return natTraversed ? fiveTuple.getLocal() : null;
}
/**
* For UDP connections, we tell the proxy to use
* {@link TransportProtocol#UDT}, otherwise we tell it to use
* {@link TransportProtocol#TCP}.
*/
@Override
public TransportProtocol getTransportProtocol() {
return UDP == fiveTuple.getProtocol() ? TransportProtocol.UDT
: TransportProtocol.TCP;
}
/**
* All our connections to chained proxies require encryption.
*/
@Override
public boolean requiresEncryption() {
return true;
}
@Override
public SSLEngine newSslEngine() {
return lanternTrustStore.newSSLEngine();
}
@Override
public void connectionSucceeded() {
markConnected();
Peer peer = getPeer();
if (peer != null) {
peer.connected();
}
}
@Override
public void connectionFailed(Throwable cause) {
String message = cause != null ? cause.getMessage() : null;
LOG.debug("Got connectionFailed from LittleProxy: {}", message);
if (cause instanceof ConnectException) {
LOG.info("Could not connect to proxy at ip: " +
this.fiveTuple.getRemote(), cause);
proxyTracker.onCouldNotConnect(this);
} else {
LOG.debug("Ignoring non-ConnectException");
}
}
@Override
public void disconnected() {
Peer peer = getPeer();
if (peer != null) {
peer.disconnected();
}
}
}
|
package org.lantern;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import org.apache.commons.lang.StringUtils;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.lastbamboo.common.p2p.P2PConstants;
import org.lastbamboo.jni.JLibTorrent;
import org.littleshoot.commom.xmpp.XmppP2PClient;
import org.littleshoot.commom.xmpp.XmppUtils;
import org.littleshoot.p2p.P2P;
import org.littleshoot.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handles logging in to the XMPP server and processing trusted users through
* the roster.
*/
public class XmppHandler implements ProxyStatusListener, ProxyProvider {
private static final String LANTERN_JID = "lantern-controller@appspot.com";
private static final Logger LOG =
LoggerFactory.getLogger(XmppHandler.class);
private final String email;
private final String pwd;
private final Set<ProxyHolder> proxySet =
new HashSet<ProxyHolder>();
private final Queue<ProxyHolder> proxies =
new ConcurrentLinkedQueue<ProxyHolder>();
private final Set<URI> peerProxySet = new HashSet<URI>();
private final Queue<URI> peerProxies =
new ConcurrentLinkedQueue<URI>();
private final Set<URI> anonymousProxySet = new HashSet<URI>();
private final Queue<URI> anonymousProxies =
new ConcurrentLinkedQueue<URI>();
private final Set<ProxyHolder> laeProxySet =
new HashSet<ProxyHolder>();
private final Queue<ProxyHolder> laeProxies =
new ConcurrentLinkedQueue<ProxyHolder>();
private final XmppP2PClient client;
private boolean displayedUpdateMessage = false;
private static final String ID;
private static final String UNCENSORED_ID = "-lan-";
private static final String CENSORED_ID = "-lac-";
static {
LOG.info("Waiting for internet connection...");
LanternUtils.waitForInternet();
LOG.info("Got internet...");
if (CensoredUtils.isCensored()) {
ID = CENSORED_ID;
} else {
ID = UNCENSORED_ID;
}
SmackConfiguration.setPacketReplyTimeout(30 * 1000);
}
private final int sslProxyRandomPort;
private final Timer updateTimer = new Timer(true);
private Chat hubChat;
private final SystemTray tray;
private volatile long lastInfoMessageScheduled = 0L;
private final MessageListener typedListener = new MessageListener() {
@Override
public void processMessage(final Chat ch, final Message msg) {
final String part = msg.getFrom();//ch.getParticipant();
LOG.info("Got chat participant: {} with message:\n {}", part,
msg.toXML());
if (part.startsWith(LANTERN_JID)) {
LOG.info("Lantern controlling agent response");
final String body = msg.getBody();
LOG.info("Body: {}", body);
final Object obj = JSONValue.parse(body);
final JSONObject json = (JSONObject) obj;
final JSONArray servers =
(JSONArray) json.get(LanternConstants.SERVERS);
final Long delay =
(Long) json.get(LanternConstants.UPDATE_TIME);
if (delay != null) {
final long now = System.currentTimeMillis();
final long elapsed = now - lastInfoMessageScheduled;
if (elapsed < 10000) {
LOG.info("Ignoring duplicate info request scheduling- "+
"scheduled request {} milliseconds ago.", elapsed);
return;
}
lastInfoMessageScheduled = now;
updateTimer.schedule(new TimerTask() {
@Override
public void run() {
sendInfoRequest();
}
}, delay);
LOG.info("Scheduled next info request in {} milliseconds",
delay);
}
if (servers == null) {
LOG.info("XMPP: "+XmppUtils.toString(msg));
} else {
final Iterator<String> iter = servers.iterator();
while (iter.hasNext()) {
final String server = iter.next();
addProxy(server);
}
if (!servers.isEmpty() && ! Configurator.configured()) {
Configurator.configure();
tray.activate();
}
}
// This is really a JSONObject, but that itself is a map.
final Map<String, String> update =
(Map<String, String>) json.get(LanternConstants.UPDATE_KEY);
LOG.info("Already displayed update? {}", displayedUpdateMessage);
if (update != null && !displayedUpdateMessage) {
LOG.info("About to show update...");
displayedUpdateMessage = true;
LanternHub.display().asyncExec (new Runnable () {
@Override
public void run () {
LanternHub.systemTray().addUpdate(update);
//final LanternBrowser lb = new LanternBrowser(true);
//lb.showUpdate(update);
}
});
}
}
final Integer type =
(Integer) msg.getProperty(P2PConstants.MESSAGE_TYPE);
if (type != null) {
LOG.info("Not processing typed message");
//processTypedMessage(msg, type, ch);
}
}
};
/**
* Creates a new XMPP handler.
*
* @param keyStoreManager The class for managing certificates.
* @param sslProxyRandomPort The port of the HTTP proxy that other peers
* will relay to.
* @param plainTextProxyRandomPort The port of the HTTP proxy running
* only locally and accepting plain-text sockets.
*/
public XmppHandler(final int sslProxyRandomPort,
final int plainTextProxyRandomPort, final SystemTray tray) {
this.sslProxyRandomPort = sslProxyRandomPort;
this.tray = tray;
this.email = LanternUtils.getStringProperty("google.user");
this.pwd = LanternUtils.getStringProperty("google.pwd");
if (StringUtils.isBlank(this.email)) {
LOG.error("No user name");
throw new IllegalStateException("No user name");
}
if (StringUtils.isBlank(this.pwd)) {
LOG.error("No password.");
throw new IllegalStateException("No password");
}
try {
final String libName = System.mapLibraryName("jnltorrent");
final JLibTorrent libTorrent =
new JLibTorrent(Arrays.asList(new File (new File(".."),
libName), new File (libName), new File ("lib", libName)), true);
//final SocketFactory socketFactory = newTlsSocketFactory();
//final ServerSocketFactory serverSocketFactory =
// newTlsServerSocketFactory();
final InetSocketAddress plainTextProxyRelayAddress =
new InetSocketAddress("127.0.0.1", plainTextProxyRandomPort);
this.client = P2P.newXmppP2PHttpClient("shoot", libTorrent,
libTorrent, new InetSocketAddress(this.sslProxyRandomPort),
SocketFactory.getDefault(), ServerSocketFactory.getDefault(),
plainTextProxyRelayAddress, false);
// This is a global, backup listener added to the client. We might
// get notifications of messages twice in some cases, but that's
// better than the alternative of sometimes not being notified
// at all.
LOG.info("Adding message listener...");
this.client.addMessageListener(typedListener);
this.client.login(this.email, this.pwd, ID);
final XMPPConnection connection = this.client.getXmppConnection();
LOG.info("Connection ID: {}", connection.getConnectionID());
// Here we handle allowing the server to subscribe to our presence.
connection.addPacketListener(new PacketListener() {
@Override
public void processPacket(final Packet pack) {
//log.info("Got packet: {}", pack);
LOG.info("Responding to subscribtion request from {} and to {}",
pack.getFrom(), pack.getTo());
final Presence packet =
new Presence(Presence.Type.subscribed);
packet.setTo(pack.getFrom());
packet.setFrom(pack.getTo());
connection.sendPacket(packet);
}
}, new PacketFilter() {
@Override
public boolean accept(final Packet packet) {
//log.info("Filtering incoming packet:\n{}", packet.toXML());
if(packet instanceof Presence) {
final Presence pres = (Presence) packet;
if(pres.getType().equals(Presence.Type.subscribe)) {
LOG.info("Got subscribe packet!!");
final String from = pres.getFrom();
if (from.startsWith("lantern-controller@") &&
from.endsWith("lantern-controller.appspotchat.com")) {
LOG.info("Got lantern subscription request!!");
return true;
} else {
LOG.info("Ignoring subscription request from: {}",
from);
}
}
} else {
LOG.info("Filtered out packet: ", packet.toXML());
//XmppUtils.printMessage(packet);
}
return false;
}
});
updatePresence();
final ChatManager chatManager = connection.getChatManager();
this.hubChat =
chatManager.createChat(LANTERN_JID, typedListener);
sendInfoRequest();
configureRoster();
} catch (final IOException e) {
final String msg = "Could not log in!!";
LOG.warn(msg, e);
throw new Error(msg, e);
} catch (final XMPPException e) {
final String msg = "Could not configure roster!!";
LOG.warn(msg, e);
throw new Error(msg, e);
}
}
private void updatePresence() {
// This is for Google Talk compatibility. Surprising, all we need to
// do is grab our Google Talk shared status, signifying support for
// their protocol, and then we don't interfere with GChat visibility.
final Packet status = LanternUtils.getSharedStatus(
this.client.getXmppConnection());
LOG.info("Status:\n{}", status.toXML());
final XMPPConnection conn = this.client.getXmppConnection();
LOG.info("Sending presence available");
conn.sendPacket(new Presence(Presence.Type.available));
final Presence forHub = new Presence(Presence.Type.available);
forHub.setTo(LANTERN_JID);
conn.sendPacket(forHub);
}
private void configureRoster() throws XMPPException {
final XMPPConnection xmpp = this.client.getXmppConnection();
final Roster roster = xmpp.getRoster();
// Make sure we look for Lantern packets.
final RosterEntry lantern = roster.getEntry(LANTERN_JID);
if (lantern == null) {
LOG.info("Creating roster entry for Lantern...");
roster.createEntry(LANTERN_JID, "Lantern", null);
}
roster.setSubscriptionMode(Roster.SubscriptionMode.manual);
roster.addRosterListener(new RosterListener() {
@Override
public void entriesDeleted(final Collection<String> addresses) {
LOG.info("Entries deleted");
}
@Override
public void entriesUpdated(final Collection<String> addresses) {
LOG.info("Entries updated: {}", addresses);
}
@Override
public void presenceChanged(final Presence presence) {
//log.info("Processing presence changed: {}", presence);
processPresence(presence);
}
@Override
public void entriesAdded(final Collection<String> addresses) {
LOG.info("Entries added: "+addresses);
}
});
// Now we add all the existing entries to get people who are already
// online.
final Collection<RosterEntry> entries = roster.getEntries();
for (final RosterEntry entry : entries) {
final Iterator<Presence> presences =
roster.getPresences(entry.getUser());
while (presences.hasNext()) {
final Presence p = presences.next();
processPresence(p);
}
}
LOG.info("Finished adding listeners");
}
private void processPresence(final Presence p) {
final String from = p.getFrom();
LOG.info("Got presence: {}", p.toXML());
if (isLanternHub(from)) {
LOG.info("Got Lantern hub presence");
}
else if (isLanternJid(from)) {
addOrRemovePeer(p, from);
}
}
private void sendInfoRequest() {
// Send an "info" message to gather proxy data.
final Message msg = new Message();
final JSONObject json = new JSONObject();
final StatsTracker statsTracker = LanternHub.statsTracker();
json.put(LanternConstants.COUNTRY_CODE, CensoredUtils.countryCode());
//json.put(LanternConstants.USER_NAME, this.user);
//json.put(LanternConstants.PASSWORD, this.pwd);
json.put(LanternConstants.BYTES_PROXIED,
statsTracker.getBytesProxied());
json.put(LanternConstants.DIRECT_BYTES,
statsTracker.getDirectBytes());
json.put(LanternConstants.REQUESTS_PROXIED,
statsTracker.getProxiedRequests());
json.put(LanternConstants.DIRECT_REQUESTS,
statsTracker.getDirectRequests());
json.put(LanternConstants.WHITELIST_ADDITIONS,
LanternUtils.toJsonArray(Whitelist.getAdditions()));
json.put(LanternConstants.WHITELIST_REMOVALS,
LanternUtils.toJsonArray(Whitelist.getRemovals()));
json.put(LanternConstants.VERSION_KEY, LanternConstants.VERSION);
final String str = json.toJSONString();
LOG.info("Reporting data: {}", str);
msg.setBody(str);
try {
LOG.info("Sending info message to Lantern Hub");
this.hubChat.sendMessage(msg);
Whitelist.whitelistReported();
statsTracker.clear();
} catch (final XMPPException e) {
LOG.error("Could not send INFO message", e);
}
}
private void addOrRemovePeer(final Presence p, final String from) {
LOG.info("Processing peer: {}", from);
final URI uri;
try {
uri = new URI(from);
} catch (final URISyntaxException e) {
LOG.error("Could not create URI from: {}", from);
return;
}
final TrustedContactsManager tcm =
LanternHub.getTrustedContactsManager();
final boolean trusted = tcm.isJidTrusted(from);
if (p.isAvailable()) {
LOG.info("Adding from to peer JIDs: {}", from);
if (trusted) {
addTrustedProxy(uri);
} else {
addAnonymousProxy(uri);
}
}
else {
LOG.info("Removing JID for peer '"+from+"' with presence: {}", p);
removePeer(uri);
}
}
private boolean isLanternHub(final String from) {
return from.startsWith("lantern-controller@") &&
from.contains("lantern-controller.appspot");
}
private void sendErrorMessage(final InetSocketAddress isa,
final String message) {
final Message msg = new Message();
msg.setProperty(P2PConstants.MESSAGE_TYPE,
XmppMessageConstants.ERROR_TYPE);
final String errorMessage = "Error: "+message+" with host: "+isa;
msg.setProperty(XmppMessageConstants.MESSAGE, errorMessage);
try {
this.hubChat.sendMessage(msg);
} catch (final XMPPException e) {
LOG.error("Error sending message", e);
}
}
/*
private void processTypedMessage(final Message msg, final Integer type,
final Chat chat) {
final String from = chat.getParticipant();
final URI uri;
try {
uri = new URI(from);
} catch (final URISyntaxException e) {
log.error("Could not create URI from: {}", from);
return;
}
log.info("Processing typed message from {}", from);
if (!this.peerProxySet.contains(uri)) {
log.warn("Ignoring message from untrusted peer: {}", from);
log.warn("Peer not in: {}", this.peerProxySet);
return;
}
switch (type) {
case (XmppMessageConstants.INFO_REQUEST_TYPE):
log.info("Handling INFO request from {}", from);
processInfoData(msg, chat);
sendInfoResponse(chat);
break;
case (XmppMessageConstants.INFO_RESPONSE_TYPE):
log.info("Handling INFO response from {}", from);
processInfoData(msg, chat);
break;
default:
log.warn("Did not understand type: "+type);
break;
}
}
*/
private void processInfoData(final Message msg) {
LOG.info("Processing INFO data from request or response.");
final String proxyString =
(String) msg.getProperty(XmppMessageConstants.PROXIES);
if (StringUtils.isNotBlank(proxyString)) {
LOG.info("Got proxies: {}", proxyString);
final Scanner scan = new Scanner(proxyString);
while (scan.hasNext()) {
final String cur = scan.next();
addProxy(cur);
}
}
//final String mac =
// (String) msg.getProperty(P2PConstants.MAC);
final String base64Cert =
(String) msg.getProperty(P2PConstants.CERT);
LOG.info("Base 64 cert: {}", base64Cert);
final String secret =
(String) msg.getProperty(P2PConstants.SECRET_KEY);
LOG.info("Secret key: {}", secret);
if (StringUtils.isNotBlank(secret)) {
final URI uri;
try {
uri = new URI(msg.getFrom());
} catch (final URISyntaxException e) {
LOG.error("Could not create URI from: {}",
msg.getFrom());
return;
}
synchronized (peerProxySet) {
if (!peerProxySet.contains(uri)) {
peerProxies.add(uri);
peerProxySet.add(uri);
}
}
}
/*
if (StringUtils.isNotBlank(base64Cert)) {
log.info("Got certificate:\n"+
new String(Base64.decodeBase64(base64Cert)));
// First we need to add this certificate to the trusted
// certificates on the proxy. Then we can add it to our list of
// peers.
final URI uri;
try {
uri = new URI(chat.getParticipant());
} catch (final URISyntaxException e) {
log.error("Could not create URI from: {}",
chat.getParticipant());
return;
}
try {
// Add the peer if we're able to add the cert.
this.keyStoreManager.addBase64Cert(mac, base64Cert);
synchronized (peerProxySet) {
if (!peerProxySet.contains(uri)) {
peerProxies.add(uri);
peerProxySet.add(uri);
}
}
} catch (final IOException e) {
log.error("Could not add cert??", e);
}
}
*/
}
private void addProxy(final String cur) {
LOG.info("Considering proxy: {}", cur);
final String jid = this.client.getXmppConnection().getUser().trim();
final String emailId = LanternUtils.jidToUser(jid);
LOG.info("We are: {}", jid);
LOG.info("Service name: {}",
this.client.getXmppConnection().getServiceName());
if (jid.equals(cur.trim())) {
LOG.info("Not adding ourselves as a proxy!!");
return;
}
if (cur.contains("appspot")) {
addLaeProxy(cur);
} else if (cur.startsWith(emailId+"/")) {
try {
addTrustedProxy(new URI(cur));
} catch (final URISyntaxException e) {
LOG.error("Error with proxy URI", e);
}
} else if (cur.contains("@")) {
try {
addAnonymousProxy(new URI(cur));
} catch (final URISyntaxException e) {
LOG.error("Error with proxy URI", e);
}
} else {
addGeneralProxy(cur);
}
}
private void addTrustedProxy(final URI cur) {
LOG.info("Considering trusted peer proxy: {}", cur);
addPeerProxy(cur, this.peerProxySet, this.peerProxies);
}
private void addAnonymousProxy(final URI cur) {
LOG.info("Considering anonymous proxy");
addPeerProxy(cur, this.anonymousProxySet, this.anonymousProxies);
}
private void addPeerProxy(final URI cur, final Set<URI> peerSet,
final Queue<URI> peerQueue) {
LOG.info("Considering peer proxy");
synchronized (peerSet) {
if (!peerSet.contains(cur)) {
LOG.info("Actually adding peer proxy: {}", cur);
peerSet.add(cur);
peerQueue.add(cur);
} else {
LOG.info("We already know about the peer proxy");
}
}
}
private void addLaeProxy(final String cur) {
LOG.info("Adding LAE proxy");
addProxyWithChecks(this.laeProxySet, this.laeProxies,
new ProxyHolder(cur, new InetSocketAddress(cur, 443)));
}
private void addGeneralProxy(final String cur) {
final String hostname =
StringUtils.substringBefore(cur, ":");
final int port =
Integer.parseInt(StringUtils.substringAfter(cur, ":"));
final InetSocketAddress isa =
new InetSocketAddress(hostname, port);
addProxyWithChecks(proxySet, proxies, new ProxyHolder(hostname, isa));
}
private void addProxyWithChecks(final Set<ProxyHolder> set,
final Queue<ProxyHolder> queue, final ProxyHolder ph) {
if (set.contains(ph)) {
LOG.info("We already know about proxy "+ph+" in {}", set);
return;
}
final Socket sock = new Socket();
try {
sock.connect(ph.isa, 60*1000);
synchronized (set) {
if (!set.contains(ph)) {
set.add(ph);
queue.add(ph);
LOG.info("Queue is now: {}", queue);
}
}
} catch (final IOException e) {
LOG.error("Could not connect to: {}", ph);
sendErrorMessage(ph.isa, e.getMessage());
onCouldNotConnect(ph.isa);
} finally {
try {
sock.close();
} catch (final IOException e) {
LOG.info("Exception closing", e);
}
}
}
private final Map<String, String> secretKeys =
new ConcurrentHashMap<String, String>();
private String getSecretKey(final String jid) {
synchronized (secretKeys) {
if (secretKeys.containsKey(jid)) {
return secretKeys.get(jid);
}
final String key = CommonUtils.generateBase64Key();
secretKeys.put(jid, key);
return key;
}
}
protected boolean isLanternJid(final String from) {
// Here's the format we're looking for: "-la-"
if (from.contains("/"+UNCENSORED_ID)) {
LOG.info("Returning Lantern TRUE for from: {}", from);
return true;
}
return false;
}
@Override
public void onCouldNotConnect(final InetSocketAddress proxyAddress) {
// This can happen in several scenarios. First, it can happen if you've
// actually disconnected from the internet. Second, it can happen if
// the proxy is blocked. Third, it can happen when the proxy is simply
// down for some reason.
LOG.info("COULD NOT CONNECT TO STANDARD PROXY!! Proxy address: {}",
proxyAddress);
// For now we assume this is because we've lost our connection.
//onCouldNotConnect(new ProxyHolder(proxyAddress.getHostName(), proxyAddress),
// this.proxySet, this.proxies);
}
@Override
public void onCouldNotConnectToLae(final InetSocketAddress proxyAddress) {
LOG.info("COULD NOT CONNECT TO LAE PROXY!! Proxy address: {}",
proxyAddress);
// For now we assume this is because we've lost our connection.
//onCouldNotConnect(new ProxyHolder(proxyAddress.getHostName(), proxyAddress),
// this.laeProxySet, this.laeProxies);
}
private void onCouldNotConnect(final ProxyHolder proxyAddress,
final Set<ProxyHolder> set, final Queue<ProxyHolder> queue){
LOG.info("COULD NOT CONNECT!! Proxy address: {}", proxyAddress);
synchronized (this.proxySet) {
set.remove(proxyAddress);
queue.remove(proxyAddress);
}
}
@Override
public void onCouldNotConnectToPeer(final URI peerUri) {
removePeer(peerUri);
}
@Override
public void onError(final URI peerUri) {
removePeer(peerUri);
}
private void removePeer(final URI uri) {
// We always remove from both since their trusted status could have
// changed
removePeerUri(uri);
removeAnonymousPeerUri(uri);
}
private void removePeerUri(final URI peerUri) {
LOG.info("Removing peer with URI: {}", peerUri);
remove(peerUri, this.peerProxySet, this.peerProxies);
}
private void removeAnonymousPeerUri(final URI peerUri) {
LOG.info("Removing anonymous peer with URI: {}", peerUri);
remove(peerUri, this.anonymousProxySet, this.anonymousProxies);
}
private void remove(final URI peerUri, final Set<URI> set,
final Queue<URI> queue) {
LOG.info("Removing peer with URI: {}", peerUri);
synchronized (set) {
set.remove(peerUri);
queue.remove(peerUri);
}
}
@Override
public InetSocketAddress getLaeProxy() {
return getProxy(this.laeProxies);
}
@Override
public InetSocketAddress getProxy() {
return getProxy(this.proxies);
}
@Override
public URI getAnonymousProxy() {
LOG.info("Getting anonymous proxy");
return getProxyUri(this.anonymousProxies);
}
@Override
public URI getPeerProxy() {
LOG.info("Getting peer proxy");
final URI proxy = getProxyUri(this.peerProxies);
if (proxy == null) {
LOG.info("Peer proxies {} and anonymous proxies {}",
this.peerProxies, this.anonymousProxies);
}
return proxy;
}
private URI getProxyUri(final Queue<URI> queue) {
if (queue.isEmpty()) {
LOG.info("No proxy URIs");
return null;
}
final URI proxy = queue.remove();
queue.add(proxy);
LOG.info("FIFO queue is now: {}", queue);
return proxy;
}
private InetSocketAddress getProxy(final Queue<ProxyHolder> queue) {
if (queue.isEmpty()) {
LOG.info("No proxy addresses");
return null;
}
final ProxyHolder proxy = queue.remove();
queue.add(proxy);
LOG.info("FIFO queue is now: {}", queue);
return proxy.isa;
}
public XmppP2PClient getP2PClient() {
return client;
}
private static final class ProxyHolder {
private final String id;
private final InetSocketAddress isa;
private ProxyHolder(final String id, final InetSocketAddress isa) {
this.id = id;
this.isa = isa;
}
@Override
public String toString() {
return "ProxyHolder [isa=" + isa + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((isa == null) ? 0 : isa.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProxyHolder other = (ProxyHolder) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (isa == null) {
if (other.isa != null)
return false;
} else if (!isa.equals(other.isa))
return false;
return true;
}
}
}
|
package org.neo4j.webadmin;
import java.net.URI;
import java.net.URISyntaxException;
import org.neo4j.helpers.Args;
import org.neo4j.rest.WebServer;
import org.neo4j.rest.domain.DatabaseLocator;
/**
* Main entry point for the neo4j stand-alone REST system with web
* administration. This code based on Main class for the REST neo4j
* distribution.
*
* @author Jacob Hansson <jacob@voltvoodoo.com>
*
*/
public class Main
{
public static int restPort;
public static int adminPort;
public static void main( String[] strArgs ) throws Exception
{
Args args = new Args( strArgs );
// 1. ARGUMENT HANDLING
System.setProperty( "org.neo4j.graphdb.location", args.get( "dbPath",
"neo4j-rest-db" ) );
System.setProperty( "org.neo4j.webadmin.developmentmode", args.get(
"development", "false" ) );
restPort = args.getNumber( "restPort", WebServer.DEFAULT_PORT ).intValue();
adminPort = args.getNumber( "adminPort", AdminServer.DEFAULT_PORT ).intValue();
String webRoot = args.get( "webRoot", AdminServer.DEFAULT_WEBROOT );
// We need this to close the graph db backend
final String restBaseUri = WebServer.getLocalhostBaseUri( restPort );
// 2. START SERVERS
WebServer.INSTANCE.startServer( restPort );
AdminServer.INSTANCE.startServer( adminPort, webRoot );
System.out.println( String.format( "Running REST at [%s]", restBaseUri ) );
System.out.println( String.format( "Running admin interface at [%s]",
AdminServer.getLocalhostBaseUri( adminPort ) ) );
System.out.println( "\nPress Ctrl-C to kill the server" );
// 3. AWAIT THE GRIM REAPER
Runtime.getRuntime().addShutdownHook( new Thread()
{
@Override
public void run()
{
try
{
// Kill the REST-server
System.out.println( "\nShutting down the REST server.." );
WebServer.INSTANCE.stopServer();
DatabaseLocator.shutdownGraphDatabase( new URI( restBaseUri ) );
// Kill the admin-server
System.out.println( "Shutting down the admin server.." );
AdminServer.INSTANCE.stopServer();
System.out.println( "Shutdown complete." );
}
catch ( URISyntaxException e )
{
throw new RuntimeException( e );
}
}
} );
}
}
|
package org.weakref.s3fs;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Iterator;
import java.util.List;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.transform;
import static java.lang.String.format;
public class S3Path
implements Path
{
public static final String PATH_SEPARATOR = "/";
private final String bucket;
private final boolean directory; // files that end in "/" are considered directories in s3
private final List<String> parts;
/**
* Root component for the given bucket
*/
public S3Path(String bucket)
{
this.bucket = bucket;
this.parts = ImmutableList.of();
this.directory = true;
}
/**
* Build an S3Path from path segments. '/' are stripped from each segment.
*
* If the last part ends in '/', the path is considered directory
*/
public S3Path(String bucket, String... parts)
{
this(bucket,
ImmutableList.copyOf(parts),
parts.length == 0 || (parts.length > 0 && parts[parts.length - 1].endsWith("/"))
);
}
private S3Path(String bucket, Iterable<String> parts, boolean isDirectory)
{
if (bucket != null) {
bucket = bucket.replace("/", "");
}
this.bucket = bucket;
this.directory = isDirectory;
this.parts = ImmutableList.copyOf(transform(parts, strip("/")));
}
/**
* path must be a string of the form "/{bucket}", "/{bucket}/{key}" or just "{key}"
*
* redundant '/' are stripped
*/
public static S3Path forPath(String path)
{
List<String> parts = ImmutableList.copyOf(Splitter.on(PATH_SEPARATOR).omitEmptyStrings().split(path));
String bucket = null;
List<String> pathParts = parts;
if (path.startsWith(PATH_SEPARATOR)) { // absolute path
Preconditions.checkArgument(parts.size() >= 1, "path must start with bucket name");
bucket = parts.get(0);
if (!parts.isEmpty()) {
pathParts = parts.subList(1, parts.size());
}
}
return new S3Path(bucket, pathParts, path.endsWith("/") || pathParts.isEmpty());
}
public String getBucket()
{
return bucket;
}
public String getKey()
{
if (parts.isEmpty()) {
return "";
}
ImmutableList.Builder<String> builder = ImmutableList.<String>builder().addAll(parts);
if (isDirectory()) {
builder.add(""); // to get a trailing '/'
}
return Joiner.on(PATH_SEPARATOR).join(builder.build());
}
@Override
public FileSystem getFileSystem()
{
throw new UnsupportedOperationException(); // TODO
}
@Override
public boolean isAbsolute()
{
return bucket != null;
}
public boolean isDirectory()
{
return directory;
}
@Override
public Path getRoot()
{
if (isAbsolute()) {
return new S3Path(bucket, ImmutableList.<String>of(), true);
}
return null;
}
@Override
public Path getFileName()
{
if (!parts.isEmpty()) {
return new S3Path(null, parts.subList(parts.size() - 1, parts.size()), directory);
}
return null;
}
@Override
public Path getParent()
{
if (parts.isEmpty()) {
return null;
}
return new S3Path(bucket, parts.subList(0, parts.size() - 1), true);
}
@Override
public int getNameCount()
{
return parts.size();
}
@Override
public Path getName(int index)
{
boolean isDirectory = (index < parts.size() - 1) || directory;
return new S3Path(null, parts.subList(index, index + 1), isDirectory);
}
@Override
public Path subpath(int beginIndex, int endIndex)
{
boolean isDirectory = (endIndex <= parts.size() - 1) || directory;
return new S3Path(null, parts.subList(beginIndex, endIndex), isDirectory);
}
@Override
public boolean startsWith(Path other)
{
throw new UnsupportedOperationException();
}
@Override
public boolean startsWith(String other)
{
throw new UnsupportedOperationException();
}
@Override
public boolean endsWith(Path other)
{
throw new UnsupportedOperationException();
}
@Override
public boolean endsWith(String other)
{
throw new UnsupportedOperationException();
}
@Override
public Path normalize()
{
return this;
}
@Override
public Path resolve(Path other)
{
Preconditions.checkArgument(other instanceof S3Path, "other must be an instance of %s", S3Path.class.getName());
S3Path s3Path = (S3Path) other;
if (s3Path.isAbsolute()) {
return s3Path;
}
if (s3Path.parts.isEmpty()) { // other is relative and empty
return this;
}
return new S3Path(bucket, concat(parts, s3Path.parts), s3Path.directory);
}
@Override
public Path resolve(String other)
{
return resolve(forPath(other));
}
@Override
public Path resolveSibling(Path other)
{
Preconditions.checkArgument(other instanceof S3Path, "other must be an instance of %s", S3Path.class.getName());
S3Path s3Path = (S3Path) other;
Path parent = getParent();
if (parent == null || s3Path.isAbsolute()) {
return s3Path;
}
if (s3Path.parts.isEmpty()) { // other is relative and empty
return parent;
}
return new S3Path(bucket, concat(parts.subList(0, parts.size() - 1), s3Path.parts), s3Path.directory);
}
@Override
public Path resolveSibling(String other)
{
return resolveSibling(forPath(other));
}
@Override
public Path relativize(Path other)
{
Preconditions.checkArgument(other instanceof S3Path, "other must be an instance of %s", S3Path.class.getName());
S3Path s3Path = (S3Path) other;
if (this.equals(other)) {
return S3Path.forPath("");
}
Preconditions.checkArgument(isAbsolute(), "Path is already relative: %s", this);
Preconditions.checkArgument(s3Path.isAbsolute(), "Cannot relativize against a relative path: %s", s3Path);
Preconditions.checkArgument(bucket.equals(s3Path.getBucket()), "Cannot relativize paths with different buckets: '%s', '%s'", this, other);
// TODO
throw new UnsupportedOperationException();
}
@Override
public URI toUri()
{
return URI.create("s3://" + bucket + Joiner.on(PATH_SEPARATOR).join(parts));
}
@Override
public Path toAbsolutePath()
{
if (isAbsolute()) {
return this;
}
throw new IllegalStateException(format("Relative path cannot be made absolute: %s", this));
}
@Override
public Path toRealPath(LinkOption... options)
throws IOException
{
throw new UnsupportedOperationException();
}
@Override
public File toFile()
{
throw new UnsupportedOperationException();
}
@Override
public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers)
throws IOException
{
throw new UnsupportedOperationException();
}
@Override
public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events)
throws IOException
{
throw new UnsupportedOperationException();
}
@Override
public Iterator<Path> iterator()
{
ImmutableList.Builder<Path> builder = ImmutableList.builder();
for (Iterator<String> iterator = parts.iterator(); iterator.hasNext(); ) {
String part = iterator.next();
boolean isDirectory = iterator.hasNext() || directory;
builder.add(new S3Path(null, ImmutableList.of(part), isDirectory));
}
return builder.build().iterator();
}
@Override
public int compareTo(Path other)
{
return toString().compareTo(other.toString());
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
if (isAbsolute()) {
builder.append(PATH_SEPARATOR);
builder.append(bucket);
builder.append(PATH_SEPARATOR);
}
builder.append(Joiner.on(PATH_SEPARATOR).join(parts));
if (directory && !parts.isEmpty()) {
builder.append(PATH_SEPARATOR);
}
return builder.toString();
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
S3Path paths = (S3Path) o;
if (directory != paths.directory) {
return false;
}
if (bucket != null ? !bucket.equals(paths.bucket) : paths.bucket != null) {
return false;
}
if (!parts.equals(paths.parts)) {
return false;
}
return true;
}
@Override
public int hashCode()
{
int result = bucket != null ? bucket.hashCode() : 0;
result = 31 * result + (directory ? 1 : 0);
result = 31 * result + parts.hashCode();
return result;
}
private static Function<String, String> strip(final String str)
{
return new Function<String, String>()
{
public String apply(String input)
{
return input.replace(str, "");
}
};
}
}
|
package plugincore;
import ActiveMQ.*;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.commons.configuration.SubnodeConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import netdiscovery.DiscoveryClientIPv6;
import netdiscovery.DiscoveryEngine;
//import shared.Clogger;
import shared.MsgEvent;
import shared.MsgEventType;
import shared.RandomString;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
public class PluginEngine {
public static boolean clientDiscoveryActive = false;
public static boolean clientDiscoveryActiveIPv6 = false;
public static boolean DiscoveryActive = false;
public static boolean ActiveBrokerManagerActive = false;
public static boolean ActiveDestManagerActive = false;
public static boolean ConsumerThreadActive = false;
public static boolean ConsumerThreadRegionActive = false;
public static boolean restartOnShutdown = false;
public static Thread discoveryEngineThread;
public static Thread activeBrokerManagerThread;
public static Thread consumerRegionThread;
public static Thread consumerAgentThread;
public static WatchDog watchDogProcess;
public static ActiveProducer ap;
public static String brokerAddress;
public static boolean isBroker = false;
public static boolean isIPv6 = false;
public static boolean isActive = false;
public static int responds = 0;
public static String region;
public static String agent;
public static String plugin;
public static String agentpath;
public static ConcurrentHashMap<String,BrokeredAgent> brokeredAgents;
public static ConcurrentLinkedQueue<MsgEvent> incomingCanidateBrokers;
public static ConcurrentLinkedQueue<MsgEvent> outgoingMessages;
//public static DiscoveryClientIPv4 dc;
public static DiscoveryClientIPv6 dcv6;
//public static Clogger logger;
private static final Logger logger = LoggerFactory.getLogger(PluginEngine.class);
public String getName() {
return "Name";
}
public String getVersion() {
return "Version";
}
public void msgIn(MsgEvent command) {
}
public static void shutdown()
{
try
{
logger.info("Shutting down");
if(watchDogProcess != null)
{
watchDogProcess.timer.cancel();
watchDogProcess = null;
}
logger.debug("WatchDog has stopped");
DiscoveryActive = false;
if(discoveryEngineThread != null)
{
logger.trace("Discovery Engine shutting down");
DiscoveryEngine.shutdown();
discoveryEngineThread.join();
isActive = false;
logger.debug("Discover Engine has shutdown");
}
ConsumerThreadRegionActive = false;
if(consumerRegionThread != null)
{
logger.trace("Region Consumer shutting down");
consumerRegionThread.join();
//logger.debug("Region Consumer has shutdown");
}
ConsumerThreadActive = false;
if(consumerAgentThread != null)
{
logger.trace("Agent Consumer shutting down");
consumerAgentThread.join();
//logger.debug("Agent Consumer has shutdown");
}
ActiveBrokerManagerActive = false;
if(activeBrokerManagerThread != null)
{
logger.trace("Active Broker Manager shutting down");
activeBrokerManagerThread.join();
//logger.debug("Active Broker Manager has shutdown");
}
if (ap != null) {
logger.trace("Producer shutting down");
ap.shutdown();
//logger.debug("Producer has shutdown");
}
if(broker != null)
{
logger.trace("Broker shutting down");
broker.stopBroker();
//logger.debug("Broker has shutdown");
}
if(restartOnShutdown)
{
commInit(); //reinit everything
restartOnShutdown = false;
}
}
catch(Exception ex)
{
logger.error("shutdown {}", ex.getMessage());
}
}
public boolean initialize(ConcurrentLinkedQueue<MsgEvent> msgOutQueue, ConcurrentLinkedQueue<MsgEvent> msgInQueue, SubnodeConfiguration configObj, String region, String agent, String plugin) {
//logger = new Clogger(msgOutQueue, region, agent, plugin);
return true;
}
public static ActiveBroker broker;
public static void main(String[] args) throws Exception
{
if(args.length == 1)
{
Thread.sleep(Integer.parseInt(args[0])*1000);
}
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
try {
shutdown();
} catch(Exception ex) {
logger.error("Run {}", ex.getMessage());
}
}
}, "Shutdown-thread"));
logger.debug("Generating Agent identity");
RandomString rs = new RandomString(4);
agent = "agent-" + rs.nextString();
/*//disabled ipv4 discovery
//Start IPv4 network discovery engine
Thread de = new Thread(new DiscoveryEngine());
de.start();
while(!DiscoveryActive)
{
//System.out.println("Wating on Discovery Server to start...");
Thread.sleep(1000);
}
System.out.println("IPv4 DiscoveryEngine Started..");
*/
commInit(); //initial init
logger.info("Agent [{}] running...", agentpath);
System.out.print("Name of Agent to message [q to quit]: ");
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
while (!input.toLowerCase().equals("q")) {
if (input.length() == 0) {
List<String> rAgents = reachableAgents();
if (rAgents.isEmpty()) {
logger.info("No agents found... " + responds);
} else {
logger.info("Sending message to {} agents", rAgents.size());
for(String str : rAgents) {
logger.info("\t" + str);
}
logger.info("Found {} agents", rAgents.size());
}
} else {
if(input.toLowerCase().equals("all")) {
List<String> rAgents = reachableAgents();
if(rAgents.isEmpty()) {
logger.info("No agents found...");
} else {
logger.info("Sending message to {} agents", rAgents.size());
for(String agent : rAgents) {
logger.info("\t" + agent);
sendMessage(MsgEventType.INFO, agent, "ping");
}
logger.info("Found {} agents", rAgents.size());
}
} else {
sendMessage(MsgEventType.INFO, input, "ping");
}
}
System.out.print("Name of Agent to message [q to quit]: ");
input = scanner.nextLine();
}
shutdown();
}
public static void commInit()
{
logger.info("Initializing services");
PluginEngine.isActive = true;
try
{
brokeredAgents = new ConcurrentHashMap<>();
incomingCanidateBrokers = new ConcurrentLinkedQueue<>();
outgoingMessages = new ConcurrentLinkedQueue<>();
brokerAddress = null;
isIPv6 = isIPv6();
dcv6 = new DiscoveryClientIPv6();
//dc = new DiscoveryClientIPv4();
logger.debug("Broker Search...");
dcv6.getDiscoveryMap(2000);
//logger.info("Broker search IPv4:");
//dc.getDiscoveryMap(2000);
if(incomingCanidateBrokers.isEmpty())
{
//generate regional ident
RandomString rs = new RandomString(4);
region = "region-" + rs.nextString();
agentpath = region + "_" + agent;
//Start controller services
//discovery engine
discoveryEngineThread = new Thread(new DiscoveryEngine());
discoveryEngineThread.start();
while(!DiscoveryActive)
{
Thread.sleep(1000);
}
//logger.debug("IPv6 DiscoveryEngine Started..");
//logger.debug("Starting ActiveBroker");
broker = new ActiveBroker(agentpath);
//broker manager
activeBrokerManagerThread = new Thread(new ActiveBrokerManager());
activeBrokerManagerThread.start();
/*synchronized (activeBrokerManagerThread) {
activeBrokerManagerThread.wait();
}*/
while(!ActiveBrokerManagerActive)
{
Thread.sleep(1000);
}
//logger.debug("ActiveBrokerManager Started..");
if(isIPv6) { //set broker address for consumers and producers
brokerAddress = "[::1]";
} else {
brokerAddress = "localhost";
}
//consumer region
consumerRegionThread = new Thread(new ActiveRegionConsumer(region, "tcp://" + brokerAddress + ":32010"));
consumerRegionThread.start();
while(!ConsumerThreadRegionActive)
{
Thread.sleep(1000);
}
//logger.debug("Region ConsumerThread Started..");
isBroker = true;
} else {
//determine least loaded broker
//need to use additional metrics to determine best fit broker
String cbrokerAddress = null;
String cRegion = null;
int brokerCount = -1;
for (MsgEvent bm : incomingCanidateBrokers) {
logger.debug("commInit {}", bm.getParams());
int tmpBrokerCount = Integer.parseInt(bm.getParam("agent_count"));
if(brokerCount < tmpBrokerCount) {
//logger.debug("commInit {}", bm.getParam("dst_ip"));
cbrokerAddress = bm.getParam("dst_ip");
cRegion = bm.getParam("src_region");
}
}
if (cbrokerAddress != null) {
InetAddress remoteAddress = InetAddress.getByName(cbrokerAddress);
if(remoteAddress instanceof Inet6Address) {
cbrokerAddress = "[" + cbrokerAddress + "]";
}
brokerAddress = cbrokerAddress;
region = cRegion;
agentpath = region + "_" + agent;
}
isBroker = false;
}
//consumer agent
consumerAgentThread = new Thread(new ActiveAgentConsumer(agentpath,"tcp://" + brokerAddress + ":32010"));
consumerAgentThread.start();
while(!ConsumerThreadActive)
{
Thread.sleep(1000);
}
//logger.debug("Agent ConsumerThread Started..");
ap = new ActiveProducer("tcp://" + brokerAddress + ":32010");
//logger.debug("Producer Started..");
watchDogProcess = new WatchDog();
//logger.debug("Watchdog Started");
} catch(Exception e) {
e.printStackTrace();
logger.error("commInit " + e.getMessage());
}
}
public static boolean sendMessage(MsgEventType type, String targetAgent, String msg) {
if (isReachableAgent(targetAgent)) {
logger.debug("Sending message to Agent [{}]", targetAgent);
String[] str = targetAgent.split("_");
MsgEvent sme = new MsgEvent(type, region, agent, plugin, msg);
sme.setParam("src_region", region);
sme.setParam("src_agent", agent);
sme.setParam("dst_region", str[0]);
if(str.length == 2) {
sme.setParam("dst_agent", str[1]); //send to region if agent does not exist
}
ap.sendMessage(sme);
return true;
} else {
logger.error("Attempted to send message to unreachable agent [{}]", targetAgent);
return false;
}
}
public static boolean isLocal(String checkAddress) {
boolean isLocal = false;
if(checkAddress.contains("%")) {
String[] checkScope = checkAddress.split("%");
checkAddress = checkScope[0];
}
List<String> localAddressList = localAddresses();
for(String localAddress : localAddressList) {
if(localAddress.contains(checkAddress)) {
isLocal = true;
}
}
return isLocal;
}
public static List<String> localAddresses() {
List<String> localAddressList = new ArrayList<>();
try {
Enumeration<NetworkInterface> inter = NetworkInterface.getNetworkInterfaces();
while (inter.hasMoreElements()) {
NetworkInterface networkInter = inter.nextElement();
for (InterfaceAddress interfaceAddress : networkInter.getInterfaceAddresses()) {
String localAddress = interfaceAddress.getAddress().getHostAddress();
if(localAddress.contains("%")) {
String[] localScope = localAddress.split("%");
localAddress = localScope[0];
}
if(!localAddressList.contains(localAddress)) {
localAddressList.add(localAddress);
}
}
}
} catch(Exception ex) {
logger.error("localAddresses Error: {}", ex.getMessage());
}
return localAddressList;
}
public static boolean isIPv6() {
boolean isIPv6 = false;
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.getDisplayName().startsWith("veth") || networkInterface.isLoopback() || !networkInterface.isUp() || !networkInterface.supportsMulticast() || networkInterface.isPointToPoint() || networkInterface.isVirtual()) {
continue; // Don't want to broadcast to the loopback interface
}
if(networkInterface.supportsMulticast()) {
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
if ((interfaceAddress.getAddress() instanceof Inet6Address)) {
isIPv6 = true;
}
}
}
}
} catch(Exception ex) {
logger.error("isIPv6 Error: {}", ex.getMessage());
}
return isIPv6;
}
public static List<String> reachableAgents() {
List<String> rAgents = null;
try {
rAgents = new ArrayList<>();
if(isBroker) {
ActiveMQDestination[] er = ActiveBroker.broker.getBroker().getDestinations();
for(ActiveMQDestination des : er) {
if(des.isQueue()) {
rAgents.add(des.getPhysicalName());
}
}
} else {
rAgents.add(region); //just return regional controller
}
} catch(Exception ex) {
logger.error("isReachableAgent Error: {}", ex.getMessage());
}
return rAgents;
}
public static boolean isReachableAgent(String remoteAgentPath) {
boolean isReachableAgent = false;
if(isBroker) {
try {
ActiveMQDestination[] er = ActiveBroker.broker.getBroker().getDestinations();
for(ActiveMQDestination des : er) {
if(des.isQueue()) {
String testPath = des.getPhysicalName();
if(testPath.equals(remoteAgentPath)) {
isReachableAgent = true;
}
}
}
} catch(Exception ex) {
logger.error("isReachableAgent Error: {}", ex.getMessage());
}
} else {
isReachableAgent = true; //send all messages to regional controller if not broker
}
return isReachableAgent;
}
}
|
package ixa.kaflib;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.IOException;
import org.jdom2.JDOMException;
public class KAFDocument {
public class FileDesc {
String author;
String title;
String creationtime;
String filename;
String filetype;
Integer pages;
private FileDesc() {}
}
public class Public {
String publicId;
String uri;
private Public(String publicId) {
this.publicId = publicId;
}
}
public class LinguisticProcessor {
String name;
String timestamp;
String version;
private LinguisticProcessor(String name, String timestamp, String version) {
this.name = name;
this.timestamp = timestamp;
this.version = version;
}
}
/** Language identifier */
private String lang;
/** KAF version */
private String version;
/** Linguistic processors */
private Map<String, List<LinguisticProcessor>> lps;
private FileDesc fileDesc;
private Public _public;
/** Identifier manager */
private IdManager idManager;
/** Keeps all the annotations of the document */
private AnnotationContainer annotationContainer;
/** Creates an empty KAFDocument element */
public KAFDocument(String lang, String version) {
this.lang = lang;
this.version = version;
lps = new LinkedHashMap<String, List<LinguisticProcessor>>();
idManager = new IdManager();
annotationContainer = new AnnotationContainer();
}
/** Creates a new KAFDocument and loads the contents of the file passed as argument
* @param file an existing KAF file to be loaded into the library.
*/
public static KAFDocument createFromFile(File file) throws IOException {
KAFDocument kaf = null;
try {
kaf = ReadWriteManager.load(file);
} catch(JDOMException e) {
e.printStackTrace();
}
return kaf;
}
/** Creates a new KAFDocument loading the content read from the reader given on argument.
* @param stream Reader to read KAF content.
*/
public static KAFDocument createFromStream(Reader stream) throws IOException {
KAFDocument kaf = null;
try {
kaf = ReadWriteManager.load(stream);
} catch(JDOMException e) {
e.printStackTrace();
}
return kaf;
}
/** Sets the language of the processed document */
public void setLang(String lang) {
this.lang = lang;
}
/** Returns the language of the processed document */
public String getLang() {
return lang;
}
/** Sets the KAF version */
public void setVersion(String version) {
this.version = version;
}
/** Returns the KAF version */
public String getVersion() {
return version;
}
/** Adds a linguistic processor to the document header. The timestamp is added implicitly. */
public LinguisticProcessor addLinguisticProcessor(String layer, String name, String version) {
String timestamp = this.getTimestamp();
LinguisticProcessor lp = new LinguisticProcessor(name, timestamp, version);
List<LinguisticProcessor> layerLps = lps.get(layer);
if (layerLps == null) {
layerLps = new ArrayList<LinguisticProcessor>();
lps.put(layer, layerLps);
}
layerLps.add(lp);
return lp;
}
/** Adds a linguistic processor to the document header */
public LinguisticProcessor addLinguisticProcessor(String layer, String name, String timestamp, String version) {
LinguisticProcessor lp = new LinguisticProcessor(name, timestamp, version);
List<LinguisticProcessor> layerLps = lps.get(layer);
if (layerLps == null) {
layerLps = new ArrayList<LinguisticProcessor>();
lps.put(layer, layerLps);
}
layerLps.add(lp);
return lp;
}
public void addLinguisticProcessors(Map<String, List<LinguisticProcessor>> lps) {
for (Map.Entry<String, List<LinguisticProcessor>> entry : lps.entrySet()) {
List<LinguisticProcessor> layerLps = entry.getValue();
for (LinguisticProcessor lp : layerLps) {
this.addLinguisticProcessor(entry.getKey(),
lp.name,
lp.timestamp,
lp.version);
}
}
}
/** Returns a hash of linguistic processors from the document.
* Hash: layer => LP
*/
public Map<String, List<LinguisticProcessor>> getLinguisticProcessors() {
return lps;
}
/** Returns wether the given linguistic processor is already defined or not. */
public boolean linguisticProcessorExists(String layer, String name, String version) {
List<LinguisticProcessor> layerLPs = lps.get(layer);
if (layerLPs == null) {
return false;
}
for (LinguisticProcessor lp : layerLPs) {
if (lp.name.equals(name) && lp.version.equals(version)) {
return true;
}
}
return false;
}
public FileDesc createFileDesc() {
this.fileDesc = new FileDesc();
return this.fileDesc;
}
public FileDesc getFileDesc() {
return this.fileDesc;
}
public Public createPublic(String publicId) {
this._public = new Public(publicId);
return this._public;
}
public Public getPublic() {
return this._public;
}
/** Returns the annotation container used by this object */
AnnotationContainer getAnnotationContainer() {
return annotationContainer;
}
/** Set raw text **/
public void setRawText(String rawText) {
annotationContainer.setRawText(rawText);
}
/** Creates a WF object to load an existing word form. It receives the ID as an argument. The WF is added to the document object.
* @param id word form's ID.
* @param form text of the word form itself.
* @return a new word form.
*/
public WF newWF(String id, String form) {
idManager.updateWFCounter(id);
WF newWF = new WF(this.annotationContainer, id, form);
annotationContainer.add(newWF);
return newWF;
}
/** Creates a new WF object. It assigns an appropriate ID to it. The WF is added to the document object.
* @param form text of the word form itself.
* @return a new word form.
*/
public WF newWF(String form) {
String newId = idManager.getNextWFId();
//int offset = annotationContainer.getNextOffset();
WF newWF = new WF(this.annotationContainer, newId, form);
//newWF.setOffset(offset);
//newWF.setLength(form.length());
annotationContainer.add(newWF);
return newWF;
}
/** Creates a new WF object. It assigns an appropriate ID to it and it also assigns offset and length
* attributes. The WF is added to the document object.
* @param form text of the word form itself.
* @return a new word form.
*/
public WF newWF(String form, int offset) {
String newId = idManager.getNextWFId();
int offsetVal = offset;
WF newWF = new WF(this.annotationContainer, newId, form);
newWF.setOffset(offsetVal);
newWF.setLength(form.length());
annotationContainer.add(newWF);
return newWF;
}
/** Creates a Term object to load an existing term. It receives the ID as an argument. The Term is added to the document object.
* @param id term's ID.
* @param type type of term. There are two types of term: open and close.
* @param lemma the lemma of the term.
* @param pos part of speech of the term.
* @param wfs the list of word forms this term is formed by.
* @return a new term.
*/
public Term newTerm(String id, String type, String lemma, String pos, Span<WF> span) {
idManager.updateTermCounter(id);
Term newTerm = new Term(id, type, lemma, pos, span);
annotationContainer.add(newTerm);
return newTerm;
}
/** Creates a new Term. It assigns an appropriate ID to it. The Term is added to the document object.
* @param type the type of the term. There are two types of term: open and close.
* @param lemma the lemma of the term.
* @param pos part of speech of the term.
* @param wfs the list of word forms this term is formed by.
* @return a new term.
*/
public Term newTerm(String type, String lemma, String pos, Span<WF> span) {
String newId = idManager.getNextTermId();
Term newTerm = new Term(newId, type, lemma, pos, span);
annotationContainer.add(newTerm);
return newTerm;
}
/** Creates a new Term. It assigns an appropriate ID to it. The Term is added to the document object.
* @param type the type of the term. There are two types of term: open and close.
* @param lemma the lemma of the term.
* @param pos part of speech of the term.
* @param wfs the list of word forms this term is formed by.
* @return a new term.
*/
public Term newTermOptions(String type, String lemma, String pos, String morphofeat, Span<WF> span) {
String newId = idManager.getNextTermId();
Term newTerm = new Term(newId, type, lemma, pos, morphofeat, span);
annotationContainer.add(newTerm);
return newTerm;
}
/** Creates a Sentiment object.
* @return a new sentiment.
*/
public Term.Sentiment newSentiment() {
Term.Sentiment newSentiment = new Term.Sentiment();
return newSentiment;
}
/** Creates a Component object to load an existing component. It receives the ID as an argument. It doesn't add the component to the term.
* @param id component's ID.
* @param term the term which this component is part of.
* @param lemma lemma of the component.
* @param pos part of speech of the component.
* @return a new component.
*/
public Term.Component newComponent(String id, Term term, String lemma, String pos) {
idManager.updateComponentCounter(id, term.getId());
Term.Component newComponent = new Term.Component(id, lemma, pos);
return newComponent;
}
/** Creates a new Component. It assigns an appropriate ID to it. It uses the ID of the term to create a new ID for the component. It doesn't add the component to the term.
* @param term the term which this component is part of.
* @param lemma lemma of the component.
* @param pos part of speech of the component.
* @return a new component.
*/
public Term.Component newComponent(Term term, String lemma, String pos) {
String newId = idManager.getNextComponentId(term.getId());
Term.Component newComponent = new Term.Component(newId, lemma, pos);
return newComponent;
}
/** Creates a new dependency. The Dep is added to the document object.
* @param from the origin term of the dependency.
* @param to the target term of the dependency.
* @param rfunc relational function of the dependency.
* @return a new dependency.
*/
public Dep newDep(Term from, Term to, String rfunc) {
Dep newDep = new Dep(from, to, rfunc);
annotationContainer.add(newDep);
return newDep;
}
/** Creates a chunk object to load an existing chunk. It receives it's ID as an argument. The Chunk is added to the document object.
* @param id chunk's ID.
* @param head the chunk head.
* @param phrase type of the phrase.
* @param terms the list of the terms in the chunk.
* @return a new chunk.
*/
public Chunk newChunk(String id, String phrase, Span<Term> span) {
idManager.updateChunkCounter(id);
Chunk newChunk = new Chunk(id, phrase, span);
annotationContainer.add(newChunk);
return newChunk;
}
/** Creates a new chunk. It assigns an appropriate ID to it. The Chunk is added to the document object.
* @param head the chunk head.
* @param phrase type of the phrase.
* @param terms the list of the terms in the chunk.
* @return a new chunk.
*/
public Chunk newChunk(String phrase, Span<Term> span) {
String newId = idManager.getNextChunkId();
Chunk newChunk = new Chunk(newId, phrase, span);
annotationContainer.add(newChunk);
return newChunk;
}
/** Creates an Entity object to load an existing entity. It receives the ID as an argument. The entity is added to the document object.
* @param id the ID of the named entity.
* @param type entity type. 8 values are posible: Person, Organization, Location, Date, Time, Money, Percent, Misc.
* @param references it contains one or more span elements. A span can be used to reference the different occurrences of the same named entity in the document. If the entity is composed by multiple words, multiple target elements are used.
* @return a new named entity.
*/
public Entity newEntity(String id, List<Span<Term>> references) {
idManager.updateEntityCounter(id);
Entity newEntity = new Entity(id, references);
annotationContainer.add(newEntity);
return newEntity;
}
/** Creates a new Entity. It assigns an appropriate ID to it. The entity is added to the document object.
* @param type entity type. 8 values are posible: Person, Organization, Location, Date, Time, Money, Percent, Misc.
* @param references it contains one or more span elements. A span can be used to reference the different occurrences of the same named entity in the document. If the entity is composed by multiple words, multiple target elements are used.
* @return a new named entity.
*/
public Entity newEntity(List<Span<Term>> references) {
String newId = idManager.getNextEntityId();
Entity newEntity = new Entity(newId, references);
annotationContainer.add(newEntity);
return newEntity;
}
/** Creates a coreference object to load an existing Coref. It receives it's ID as an argument. The Coref is added to the document.
* @param id the ID of the coreference.
* @param references different mentions (list of targets) to the same entity.
* @return a new coreference.
*/
public Coref newCoref(String id, List<Span<Term>> mentions) {
idManager.updateCorefCounter(id);
Coref newCoref = new Coref(id, mentions);
annotationContainer.add(newCoref);
return newCoref;
}
/** Creates a new coreference. It assigns an appropriate ID to it. The Coref is added to the document.
* @param references different mentions (list of targets) to the same entity.
* @return a new coreference.
*/
public Coref newCoref(List<Span<Term>> mentions) {
String newId = idManager.getNextCorefId();
Coref newCoref = new Coref(newId, mentions);
annotationContainer.add(newCoref);
return newCoref;
}
/** Creates a new property. It receives it's ID as an argument. The property is added to the document.
* @param id the ID of the property.
* @param lemma the lemma of the property.
* @param references different mentions (list of targets) to the same property.
* @return a new coreference.
*/
public Feature newProperty(String id, String lemma, List<Span<Term>> references) {
idManager.updatePropertyCounter(id);
Feature newProperty = new Feature(id, lemma, references);
annotationContainer.add(newProperty);
return newProperty;
}
/** Creates a new property. It assigns an appropriate ID to it. The property is added to the document.
* @param lemma the lemma of the property.
* @param references different mentions (list of targets) to the same property.
* @return a new coreference.
*/
public Feature newProperty(String lemma, List<Span<Term>> references) {
String newId = idManager.getNextPropertyId();
Feature newProperty = new Feature(newId, lemma, references);
annotationContainer.add(newProperty);
return newProperty;
}
/** Creates a new category. It receives it's ID as an argument. The category is added to the document.
* @param id the ID of the category.
* @param lemma the lemma of the category.
* @param references different mentions (list of targets) to the same category.
* @return a new coreference.
*/
public Feature newCategory(String id, String lemma, List<Span<Term>> references) {
idManager.updateCategoryCounter(id);
Feature newCategory = new Feature(id, lemma, references);
annotationContainer.add(newCategory);
return newCategory;
}
/** Creates a new category. It assigns an appropriate ID to it. The category is added to the document.
* @param lemma the lemma of the category.
* @param references different mentions (list of targets) to the same category.
* @return a new coreference.
*/
public Feature newCategory(String lemma, List<Span<Term>> references) {
String newId = idManager.getNextCategoryId();
Feature newCategory = new Feature(newId, lemma, references);
annotationContainer.add(newCategory);
return newCategory;
}
/** Creates a new opinion object. It assigns an appropriate ID to it. The opinion is added to the document.
* @return a new opinion.
*/
public Opinion newOpinion() {
String newId = idManager.getNextOpinionId();
Opinion newOpinion = new Opinion(newId);
annotationContainer.add(newOpinion);
return newOpinion;
}
/** Creates a new opinion object. It receives its ID as an argument. The opinion is added to the document.
* @return a new opinion.
*/
public Opinion newOpinion(String id) {
idManager.updateOpinionCounter(id);
Opinion newOpinion = new Opinion(id);
annotationContainer.add(newOpinion);
return newOpinion;
}
/** Creates a new relation between entities and/or sentiment features. It assigns an appropriate ID to it. The relation is added to the document.
* @param from source of the relation
* @param to target of the relation
* @return a new relation
*/
public Relation newRelation(Relational from, Relational to) {
String newId = idManager.getNextRelationId();
Relation newRelation = new Relation(newId, from, to);
annotationContainer.add(newRelation);
return newRelation;
}
/** Creates a new relation between entities and/or sentiment features. It receives its ID as an argument. The relation is added to the document.
* @param id the ID of the relation
* @param from source of the relation
* @param to target of the relation
* @return a new relation
*/
public Relation newRelation(String id, Relational from, Relational to) {
idManager.updateRelationCounter(id);
Relation newRelation = new Relation(id, from, to);
annotationContainer.add(newRelation);
return newRelation;
}
/** Creates a new srl predicate. It receives its ID as an argument. The predicate is added to the document.
* @param id the ID of the predicate
* @param span span containing the targets of the predicate
* @return a new predicate
*/
public Predicate newPredicate(String id, Span<Term> span) {
idManager.updatePredicateCounter(id);
Predicate newPredicate = new Predicate(id, span);
annotationContainer.add(newPredicate);
return newPredicate;
}
/** Creates a new srl predicate. It assigns an appropriate ID to it. The predicate is added to the document.
* @param span span containing all the targets of the predicate
* @return a new predicate
*/
public Predicate newPredicate(Span<Term> span) {
String newId = idManager.getNextPredicateId();
Predicate newPredicate = new Predicate(newId, span);
annotationContainer.add(newPredicate);
return newPredicate;
}
/** Creates a Role object to load an existing role. It receives the ID as an argument. It doesn't add the role to the predicate.
* @param id role's ID.
* @param predicate the predicate which this role is part of
* @param semRole semantic role
* @param span span containing all the targets of the role
* @return a new role.
*/
public Predicate.Role newRole(String id, Predicate predicate, String semRole, Span<Term> span) {
idManager.updateRoleCounter(id);
Predicate.Role newRole = new Predicate.Role(id, semRole, span);
return newRole;
}
/** Creates a new Role object. It assigns an appropriate ID to it. It uses the ID of the predicate to create a new ID for the role. It doesn't add the role to the predicate.
* @param predicate the predicate which this role is part of
* @param semRole semantic role
* @param span span containing all the targets of the role
* @return a new role.
*/
public Predicate.Role newRole(Predicate predicate, String semRole, Span<Term> span) {
String newId = idManager.getNextRoleId();
Predicate.Role newRole = new Predicate.Role(newId, semRole, span);
return newRole;
}
/** Creates a new external reference.
* @param resource indicates the identifier of the resource referred to.
* @param reference code of the referred element.
* @return a new external reference object.
*/
public ExternalRef newExternalRef(String resource, String reference) {
return new ExternalRef(resource, reference);
}
public Tree newConstituent(TreeNode root) {
Tree tree = new Tree(root);
annotationContainer.add(tree);
return tree;
}
public void addConstituencyFromParentheses(String parseOut) throws Exception {
Tree.parenthesesToKaf(parseOut, this);
}
public NonTerminal newNonTerminal(String id, String label) {
NonTerminal tn = new NonTerminal(id, label);
return tn;
}
public NonTerminal newNonTerminal(String label) {
String newId = idManager.getNextNonterminalId();
String newEdgeId = idManager.getNextEdgeId();
NonTerminal newNonterminal = new NonTerminal(newId, label);
newNonterminal.setEdgeId(newEdgeId);
return newNonterminal;
}
public Terminal newTerminal(String id, Span<Term> span) {
Terminal tn = new Terminal(id, span);
return tn;
}
public Terminal newTerminal(Span<Term> span) {
String newId = idManager.getNextTerminalId();
String newEdgeId = idManager.getNextEdgeId();
Terminal tn = new Terminal(newId, span);
tn.setEdgeId(newEdgeId);
return tn;
}
public static Span<WF> newWFSpan() {
return new Span<WF>();
}
public static Span<WF> newWFSpan(List<WF> targets) {
return new Span<WF>(targets);
}
public static Span<WF> newWFSpan(List<WF> targets, WF head) {
return new Span<WF>(targets, head);
}
public static Span<Term> newTermSpan() {
return new Span<Term>();
}
public static Span<Term> newTermSpan(List<Term> targets) {
return new Span<Term>(targets);
}
public static Span<Term> newTermSpan(List<Term> targets, Term head) {
return new Span<Term>(targets, head);
}
/** Returns the raw text **/
public String getRawText() {
return annotationContainer.getRawText();
}
/** Returns a list containing all WFs in the document */
public List<WF> getWFs() {
return annotationContainer.getText();
}
/** Returns a list with all sentences. Each sentence is a list of WFs. */
public List<List<WF>> getSentences() {
return annotationContainer.getSentences();
}
/** Returns a list with all terms in the document. */
public List<Term> getTerms() {
return annotationContainer.getTerms();
}
/** Returns a list of terms containing the word forms given on argument.
* @param wfs a list of word forms whose terms will be found.
* @return a list of terms containing the given word forms.
*/
public List<Term> getTermsByWFs(List<WF> wfs) {
return annotationContainer.getTermsByWFs(wfs);
}
public List<Term> getSentenceTerms(int sent) {
return annotationContainer.getSentenceTerms(sent);
}
public List<Dep> getDeps() {
return annotationContainer.getDeps();
}
public List<Chunk> getChunks() {
return annotationContainer.getChunks();
}
/** Returns a list with all entities in the document */
public List<Entity> getEntities() {
return annotationContainer.getEntities();
}
public List<Coref> getCorefs() {
return annotationContainer.getCorefs();
}
/** Returns a list with all relations in the document */
public List<Feature> getProperties() {
return annotationContainer.getProperties();
}
/** Returns a list with all relations in the document */
public List<Feature> getCategories() {
return annotationContainer.getCategories();
}
public List<Opinion> getOpinions() {
return annotationContainer.getOpinions();
}
/** Returns a list with all relations in the document */
public List<Relation> getRelations() {
return annotationContainer.getRelations();
}
public List<Tree> getConstituents() {
return annotationContainer.getConstituents();
}
/** Returns current timestamp. */
public String getTimestamp() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD'T'kk:mm:ssZ");
String formattedDate = sdf.format(date);
return formattedDate;
}
/** Merges the document with another one. **/
public void merge(KAFDocument doc) {
HashMap<String, WF> copiedWFs = new HashMap<String, WF>(); // hash[old_id => new_WF_obj]
HashMap<String, Term> copiedTerms = new HashMap<String, Term>(); // hash[old_id => new_Term_obj]
HashMap<String, Relational> copiedRelationals = new HashMap<String, Relational>();
// Linguistic processors
Map<String, List<LinguisticProcessor>> lps = doc.getLinguisticProcessors();
for (Map.Entry<String, List<LinguisticProcessor>> entry : lps.entrySet()) {
String layer = entry.getKey();
List<LinguisticProcessor> lpList = entry.getValue();
for (LinguisticProcessor lp : lpList) {
if (!this.linguisticProcessorExists(layer, lp.name, lp.version)) {
this.addLinguisticProcessor(layer, lp.name, lp.timestamp, lp.version);
}
}
}
// WFs
for (WF wf : doc.getWFs()) {
WF wfCopy = new WF(wf, this.annotationContainer);
this.insertWF(wfCopy);
copiedWFs.put(wf.getId(), wfCopy);
}
// Terms
for (Term term : doc.getTerms()) {
Term termCopy = new Term(term, copiedWFs);
this.insertTerm(termCopy);
copiedTerms.put(term.getId(), termCopy);
}
// Deps
for (Dep dep : doc.getDeps()) {
Dep depCopy = new Dep(dep, copiedTerms);
this.insertDep(depCopy);
}
// Chunks
for (Chunk chunk : doc.getChunks()) {
Chunk chunkCopy = new Chunk(chunk, copiedTerms);
this.insertChunk(chunkCopy);
}
// Entities
for (Entity entity : doc.getEntities()) {
Entity entityCopy = new Entity(entity, copiedTerms);
this.insertEntity(entityCopy);
copiedRelationals.put(entity.getId(), entityCopy);
}
// Coreferences
for (Coref coref : doc.getCorefs()) {
Coref corefCopy = new Coref(coref, copiedTerms);
this.insertCoref(corefCopy);
}
// Properties
for (Feature property : doc.getProperties()) {
Feature propertyCopy = new Feature(property, copiedTerms);
this.insertProperty(propertyCopy);
copiedRelationals.put(property.getId(), propertyCopy);
}
// Categories
for (Feature category : doc.getCategories()) {
Feature categoryCopy = new Feature(category, copiedTerms);
this.insertCategory(categoryCopy);
copiedRelationals.put(category.getId(), categoryCopy);
}
// Opinions
for (Opinion opinion : doc.getOpinions()) {
Opinion opinionCopy = new Opinion(opinion, copiedTerms);
this.insertOpinion(opinionCopy);
}
// Relations
for (Relation relation : doc.getRelations()) {
Relation relationCopy = new Relation(relation, copiedRelationals);
this.insertRelation(relationCopy);
}
}
private String insertWF(WF wf) {
String newId = idManager.getNextWFId();
wf.setId(newId);
annotationContainer.add(wf);
return newId;
}
private String insertTerm(Term term) {
String newId = idManager.getNextTermId();
term.setId(newId);
annotationContainer.add(term);
return newId;
}
private void insertDep(Dep dep) {
annotationContainer.add(dep);
}
private String insertChunk(Chunk chunk) {
String newId = idManager.getNextChunkId();
chunk.setId(newId);
annotationContainer.add(chunk);
return newId;
}
private String insertEntity(Entity entity) {
String newId = idManager.getNextEntityId();
entity.setId(newId);
annotationContainer.add(entity);
return newId;
}
private String insertCoref(Coref coref) {
String newId = idManager.getNextCorefId();
coref.setId(newId);
annotationContainer.add(coref);
return newId;
}
private String insertProperty(Feature property) {
String newId = idManager.getNextPropertyId();
property.setId(newId);
annotationContainer.add(property);
return newId;
}
private String insertCategory(Feature category) {
String newId = idManager.getNextCategoryId();
category.setId(newId);
annotationContainer.add(category);
return newId;
}
private String insertOpinion(Opinion opinion) {
String newId = idManager.getNextOpinionId();
opinion.setId(newId);
annotationContainer.add(opinion);
return newId;
}
private String insertRelation(Relation relation) {
String newId = idManager.getNextRelationId();
relation.setId(newId);
annotationContainer.add(relation);
return newId;
}
/** Saves the KAF document to an XML file.
* @param filename name of the file in which the document will be saved.
*/
public void save(String filename) {
ReadWriteManager.save(this, filename);
}
public String toString() {
return ReadWriteManager.kafToStr(this);
}
/** Prints the document on standard output. */
public void print() {
ReadWriteManager.print(this);
}
/*** DEPRECATED METHODS ***/
/** Deprecated */
public WF createWF(String id, String form) {
return this.newWF(id, form);
}
/** Deprecated */
public WF createWF(String form) {
return this.newWF(form);
}
/** Deprecated */
public WF createWF(String form, int offset) {
return this.newWF(form, offset);
}
/** Deprecated */
public Term createTerm(String id, String type, String lemma, String pos, List<WF> wfs) {
return this.newTerm(id, type, lemma, pos, this.<WF>list2Span(wfs));
}
/** Deprecated */
public Term createTerm(String type, String lemma, String pos, List<WF> wfs) {
return this.newTerm(type, lemma, pos, this.<WF>list2Span(wfs));
}
/** Deprecated */
public Term createTermOptions(String type, String lemma, String pos, String morphofeat, List<WF> wfs) {
return this.newTermOptions(type, lemma, pos, morphofeat, this.<WF>list2Span(wfs));
}
/** Deprecated */
public Term.Sentiment createSentiment() {
return this.newSentiment();
}
/** Deprecated */
public Term.Component createComponent(String id, Term term, String lemma, String pos) {
return this.newComponent(id, term, lemma, pos);
}
/** Deprecated */
public Term.Component createComponent(Term term, String lemma, String pos) {
return this.newComponent(term, lemma, pos);
}
/** Deprecated */
public Dep createDep(Term from, Term to, String rfunc) {
return this.createDep(from, to, rfunc);
}
/** Deprecated */
public Chunk createChunk(String id, Term head, String phrase, List<Term> terms) {
return this.newChunk(id, phrase, this.<Term>list2Span(terms, head));
}
/** Deprecated */
public Chunk createChunk(Term head, String phrase, List<Term> terms) {
return this.newChunk(phrase, this.<Term>list2Span(terms, head));
}
/** Deprecated */
public Entity createEntity(String id, String type, List<List<Term>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Term> list : references) {
spanReferences.add(this.list2Span(list));
}
Entity entity = this.newEntity(id, spanReferences);
entity.setType(type);
return entity;
}
/** Deprecated */
public Entity createEntity(String type, List<List<Term>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Term> list : references) {
spanReferences.add(this.list2Span(list));
}
return this.newEntity(type, spanReferences);
}
/** Deprecated */
public Coref createCoref(String id, List<List<Target>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Target> list : references) {
spanReferences.add(this.targetList2Span(list));
}
return this.newCoref(id, spanReferences);
}
/** Deprecated */
public Coref createCoref(List<List<Target>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Target> list : references) {
spanReferences.add(this.targetList2Span(list));
}
return this.newCoref(spanReferences);
}
/** Deprecated */
public Feature createProperty(String id, String lemma, List<List<Term>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Term> list : references) {
spanReferences.add(this.list2Span(list));
}
return this.newProperty(id, lemma, spanReferences);
}
/** Deprecated */
public Feature createProperty(String lemma, List<List<Term>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Term> list : references) {
spanReferences.add(this.list2Span(list));
}
return this.newProperty(lemma, spanReferences);
}
/** Deprecated */
public Feature createCategory(String id, String lemma, List<List<Term>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Term> list : references) {
spanReferences.add(this.list2Span(list));
}
return this.newCategory(id, lemma, spanReferences);
}
/** Deprecated */
public Feature createCategory(String lemma, List<List<Term>> references) {
List<Span<Term>> spanReferences = new ArrayList<Span<Term>>();
for (List<Term> list : references) {
spanReferences.add(this.list2Span(list));
}
return this.newCategory(lemma, spanReferences);
}
/** Deprecated */
public Opinion createOpinion() {
return this.newOpinion();
}
/** Deprecated */
public Opinion createOpinion(String id) {
return this.newOpinion(id);
}
/** Deprecated */
public Relation createRelation(Relational from, Relational to) {
return this.newRelation(from, to);
}
/** Deprecated */
public Relation createRelation(String id, Relational from, Relational to) {
return this.newRelation(id, from, to);
}
/** Deprecated */
public ExternalRef createExternalRef(String resource, String reference) {
return this.newExternalRef(resource, reference);
}
public static Target createTarget(Term term) {
return new Target(term, false);
}
/** Deprecated. Creates a new target. This method is overloaded. In this case, it receives a boolean argument which defines whether the target term is the head or not.
* @param term target term.
* @param isHead a boolean argument which defines whether the target term is the head or not.
* @return a new target.
*/
public static Target createTarget(Term term, boolean isHead) {
return new Target(term, isHead);
}
/** Converts a List into a Span */
static <T> Span<T> list2Span(List<T> list) {
Span<T> span = new Span<T>();
for (T elem : list) {
span.addTarget(elem);
}
return span;
}
/** Converts a List into a Span */
static <T> Span<T> list2Span(List<T> list, T head) {
Span<T> span = new Span<T>();
for (T elem : list) {
if (head == elem) {
span.addTarget(elem, true);
} else {
span.addTarget(elem);
}
}
return span;
}
/** Converts a Target list into a Span of terms */
static Span<Term> targetList2Span(List<Target> list) {
Span<Term> span = new Span<Term>();
for (Target target : list) {
if (target.isHead()) {
span.addTarget(target.getTerm(), true);
} else {
span.addTarget(target.getTerm());
}
}
return span;
}
/** Converts a Span into a Target list */
static List<Target> span2TargetList(Span<Term> span) {
List<Target> list = new ArrayList<Target>();
for (Term t : span.getTargets()) {
list.add(KAFDocument.createTarget(t, (t==span.getHead())));
}
return list;
}
/** Deprecated. Returns a list of terms containing the word forms given on argument.
* @param wfIds a list of word form IDs whose terms will be found.
* @return a list of terms containing the given word forms.
*/
public List<Term> getTermsFromWFs(List<String> wfIds) {
return annotationContainer.getTermsByWFIds(wfIds);
}
}
|
package main;
import entities.Corpus;
import entities.Song;
import org.hibernate.Transaction;
import plsa.PLSA;
import storage.Hibernator;
import javax.persistence.TypedQuery;
import java.util.List;
public class MainHibernateTest {
public static void main(String[] args) throws Exception {
Corpus c = new Corpus();
TypedQuery<Song> query = Hibernator.mainSession.createQuery("from Song", Song.class).setMaxResults(500);
List<Song> songs = query.getResultList();
songs.forEach((song) -> c.add(song));
PLSA plsa = new PLSA(c, 10, 5);
plsa.run();
Transaction trans = Hibernator.mainSession.beginTransaction();
Hibernator.mainSession.save(plsa);
trans.commit();
Hibernator.mainSession.close();
Hibernator.sessionFactory.close();
}
}
|
package tigase.xmpp.impl;
import java.util.Map;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.db.NonAuthUserRepository;
import tigase.db.TigaseDBException;
import tigase.db.UserNotFoundException;
import tigase.server.Iq;
import tigase.server.Packet;
import tigase.xml.DomBuilderHandler;
import tigase.xml.Element;
import tigase.xml.SimpleParser;
import tigase.xml.SingletonFactory;
import tigase.xmpp.Authorization;
import tigase.xmpp.JID;
import tigase.xmpp.NoConnectionIdException;
import tigase.xmpp.NotAuthorizedException;
import tigase.xmpp.PacketErrorTypeException;
import tigase.xmpp.StanzaType;
import tigase.xmpp.XMPPResourceConnection;
import static tigase.xmpp.impl.VCard4.*;
import tigase.xmpp.impl.annotation.DiscoFeatures;
import tigase.xmpp.impl.annotation.Handle;
import tigase.xmpp.impl.annotation.Handles;
import tigase.xmpp.impl.annotation.Id;
/**
*
* @author andrzej
*/
@Id(ID)
@Handles({
@Handle(path={ Iq.ELEM_NAME, VCARD_EL },xmlns=XMLNS)
})
@DiscoFeatures({
XMLNS
})
public class VCard4 extends VCardXMPPProcessorAbstract {
private static final Logger log = Logger.getLogger(VCard4.class.getCanonicalName());
// private varibles reused in public variables
static final String ID = "vcard-xep-0292";
protected static final String VCARD_EL = "vcard";
protected static final String XMLNS = "urn:ietf:params:xml:ns:vcard-4.0";
// public variables used in other places which depends on private variables above
public static final String REPO_NODE = ID;
// private variables used only by this processor
static final String VCARD_KEY = ID;
private static final SimpleParser parser = SingletonFactory.getParserInstance();
/**
* Method description
*
*
* @param connectionId
* @param packet
* @param session
* @param repo
* @param results
* @param settings
*
* @throws PacketErrorTypeException
*/
@Override
public void processFromUserOutPacket(JID connectionId, Packet packet,
XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results,
Map<String, Object> settings)
throws PacketErrorTypeException {
if (session.isLocalDomain(packet.getStanzaTo().getDomain(), false)) {
// This is a local user so we can quickly get his vCard from the database
try {
String strvCard = repo.getPublicData(packet.getStanzaTo().getBareJID(), ID,
VCARD_KEY, null);
Packet result = null;
if (strvCard != null) {
result = parseXMLData(strvCard, packet);
} else {
result = packet.okResult((String) null, 1);
} // end of if (vcard != null)
result.setPacketTo(connectionId);
results.offer(result);
} catch (UserNotFoundException e) {
results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet,
"User not found", true));
} // end of try-catch
} else {
// Else forward the packet to a remote server
results.offer(packet.copyElementOnly());
}
}
/**
* Method description
*
*
* @param connectionId
* @param packet
* @param session
* @param repo
* @param results
* @param settings
*
* @throws PacketErrorTypeException
*/
@Override
public void processFromUserToServerPacket(JID connectionId, Packet packet,
XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results,
Map<String, Object> settings)
throws PacketErrorTypeException {
if (packet.getType() != null) {
try {
Packet result = null;
switch (packet.getType()) {
case get :
String strvCard = session.getPublicData(ID, VCARD_KEY, null);
if (strvCard != null) {
result = parseXMLData(strvCard, packet);
} else {
result = packet.okResult((String) null, 1);
} // end of if (vcard != null) else
break;
case set :
Element elvCard = packet.getElement().getChild(VCARD_EL, XMLNS);
setVCard(session, elvCard);
result = packet.okResult((String) null, 0);
break;
default :
// Ignore all others...
}
if (result != null) {
result.setPacketTo(session.getConnectionId());
results.offer(result);
}
} catch (NoConnectionIdException ex) {
// This should not happen unless somebody sends a result vcard packet
// to the server itself
log.warning("This should not happen, unless this is a vcard result packet " +
"sent to the server, which should not happen: " + packet);
} catch (NotAuthorizedException ex) {
log.warning("Received vCard request but user session is not authorized yet: " +
packet);
results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
"You must authorize session first.", true));
} catch (TigaseDBException ex) {
log.log(Level.WARNING, "Database problem, please contact admin: " + ex, ex);
results.offer(Authorization.INTERNAL_SERVER_ERROR.getResponseMessage(packet,
"Database access problem, please contact administrator.", true));
}
} else {
// TODO: if this really happen that this is clearly protocol error, as
// that would be
// vCard packet with no type set, do we really need to handle such an
// erro? Let's
// ignore it for now.
}
}
/**
* Method description
*
*
* @param packet
* @param repo
* @param results
* @param settings
*
* @throws PacketErrorTypeException
*/
@Override
public void processNullSessionPacket(Packet packet, NonAuthUserRepository repo,
Queue<Packet> results, Map<String, Object> settings)
throws PacketErrorTypeException {
if (packet.getType() == StanzaType.get) {
try {
String strvCard = repo.getPublicData(packet.getStanzaTo().getBareJID(), ID,
VCARD_KEY, null);
if (strvCard != null) {
results.offer(parseXMLData(strvCard, packet));
} else {
results.offer(packet.okResult((String) null, 1));
} // end of if (vcard != null)
} catch (UserNotFoundException e) {
results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet,
"User not found", true));
} // end of try-catch
} else {
// This is most likely a response to the user from the remote
// entity with vCard request results.
// Processed in processToUserPacket() method.
}
}
/**
* Method description
*
*
* @param packet
* @param session
* @param repo
* @param results
* @param settings
*/
@Override
public void processServerSessionPacket(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) {
// TODO: Hm, the server vCard should be sent here, not yet implemented....
}
/**
* Method description
*
*
* @param packet
* @param session
* @param repo
* @param results
* @param settings
*
* @throws PacketErrorTypeException
*/
@Override
public void processToUserPacket(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings)
throws PacketErrorTypeException {
processNullSessionPacket(packet, repo, results, settings);
if ((session != null) && session.isAuthorized() && (packet.getType() != StanzaType
.get)) {
try {
JID conId = session.getConnectionId(packet.getStanzaTo());
if (conId == null) {
// Drop it, user is no longer online.
return;
}
Packet result = packet.copyElementOnly();
result.setPacketTo(session.getConnectionId(packet.getStanzaTo()));
results.offer(result);
} catch (NoConnectionIdException ex) {
// This should not happen unless somebody sends a result vcard packet
// to the server itself
log.warning("This should not happen, unless this is a vcard result packet " +
"sent to the server, which should not happen: " + packet);
}
}
}
@Override
protected String getVCardXMLNS() {
return XMLNS;
}
@Override
protected void storeVCard(XMPPResourceConnection session, Element elvCard) throws TigaseDBException, NotAuthorizedException {
if (elvCard != null && elvCard.getChildren() != null) {
if (log.isLoggable(Level.FINER)) {
log.finer("Adding vCard: " + elvCard);
}
session.setPublicData(ID, VCARD_KEY, elvCard.toString());
} else {
if (log.isLoggable(Level.FINER)) {
log.finer("Removing vCard");
}
session.removePublicData(ID, VCARD_KEY);
} // end of else
}
private Packet parseXMLData(String data, Packet packet) {
DomBuilderHandler domHandler = new DomBuilderHandler();
parser.parse(domHandler, data.toCharArray(), 0, data.length());
Queue<Element> elems = domHandler.getParsedElements();
Packet result = packet.okResult((Element) null, 0);
result.setPacketFrom(null);
result.setPacketTo(null);
for (Element el : elems) {
result.getElement().addChild(el);
} // end of for (Element el: elems)
return result;
}
}
|
package org.cactoos.scalar;
import org.cactoos.Func;
import org.cactoos.Scalar;
import org.cactoos.iterable.IterableOf;
import org.cactoos.iterable.Mapped;
/**
* Logical conjunction.
* This class performs short-circuit evaluation in which arguments are
* executed only if the preceding argument does not suffice to determine
* the value of the expression.
*
* <p>This class could be also used for matching multiple boolean
* expressions:</p>
*
* {@code
* new And(
* new True(),
* new True(),
* new True()
* ).value(); // the result is true
*
* new And(
* new True(),
* new False(),
* new True()
* ).value(); // the result is false
* }
*
* <p>This class implements {@link Scalar}, which throws a checked
* {@link Exception}. This may not be convenient in many cases. To make
* it more convenient and get rid of the checked exception you can
* use the {@link Unchecked} decorator. Or you may use
* {@link IoChecked} to wrap it in an IOException.</p>
*
* <p>There is no thread-safety guarantee.
*
* @see Unchecked
* @see IoChecked
* @since 0.8
*/
public final class And implements Scalar<Boolean> {
/**
* The iterator.
*/
private final Iterable<? extends Scalar<Boolean>> origin;
/**
* Ctor.
* @param func Func to map
* @param src The iterable
* @param <X> Type of items in the iterable
*/
@SafeVarargs
public <X> And(final Func<? super X, Boolean> func, final X... src) {
this(func, new IterableOf<>(src));
}
/**
* Ctor.
* @param func Func to map
* @param src The iterable
* @param <X> Type of items in the iterable
* @since 0.24
*/
public <X> And(
final Func<? super X, Boolean> func,
final Iterable<? extends X> src
) {
this(
new Mapped<>(
item -> new ScalarOf<>(() -> func.apply(item)),
src
)
);
}
/**
* Ctor.
* @param subject The subject
* @param conditions Funcs to map
* @param <X> Type of items in the iterable
* @since 0.34
*/
@SafeVarargs
public <X> And(final X subject, final Func<? super X, Boolean>... conditions) {
this(subject, new IterableOf<>(conditions));
}
/**
* Ctor.
* @param subject The subject
* @param conditions Funcs to map
* @param <X> Type of items in the iterable
* @since 0.49
*/
public <X> And(final X subject, final Iterable<? extends Func<? super X, Boolean>> conditions) {
this(
new Mapped<>(
item -> new ScalarOf<>(() -> item.apply(subject)),
conditions
)
);
}
/**
* Ctor.
* @param scalar The Scalar.
*/
@SafeVarargs
public And(final Scalar<Boolean>... scalar) {
this(new IterableOf<>(scalar));
}
/**
* Ctor.
* @param iterable The iterable.
*/
public And(final Iterable<? extends Scalar<Boolean>> iterable) {
this.origin = iterable;
}
@Override
public Boolean value() throws Exception {
boolean result = true;
for (final Scalar<Boolean> item : this.origin) {
if (!item.value()) {
result = false;
break;
}
}
return result;
}
}
|
package org.dita.dost.util;
import static org.dita.dost.util.Constants.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
/**
* Definition of current job.
*
* <p>Instances are thread-safe.</p>
*
* @since 1.5.4
*/
public final class Job {
private static final String JOB_FILE = ".job.xml";
private static final String ELEMENT_JOB = "job";
private static final String ATTRIBUTE_KEY = "key";
private static final String ELEMENT_ENTRY = "entry";
private static final String ELEMENT_MAP = "map";
private static final String ELEMENT_SET = "set";
private static final String ELEMENT_STRING = "string";
private static final String ATTRIBUTE_NAME = "name";
private static final String ELEMENT_PROPERTY = "property";
private static final String ELEMENT_FILES = "files";
private static final String ELEMENT_FILE = "file";
private static final String ATTRIBUTE_PATH = "path";
private static final String ATTRIBUTE_FORMAT = "format";
private static final String ATTRIBUTE_CHUNKED = "chunked";
private static final String ATTRIBUTE_HAS_CONREF = "has-conref";
private static final String ATTRIBUTE_HAS_KEYREF = "has-keyref";
private static final String ATTRIBUTE_HAS_CODEREF = "has-coderef";
private static final String ATTRIBUTE_RESOURCE_ONLY = "resource-only";
private static final String ATTRIBUTE_TARGET = "target";
private static final String ATTRIBUTE_CONREF_TARGET = "conref-target";
private static final String ATTRIBUTE_NON_CONREF_TARGET = "non-conref-target";
private static final String ATTRIBUTE_CONREF_PUSH = "conrefpush";
private static final String ATTRIBUTE_SUBJECT_SCHEME = "subjectscheme";
private static final String ATTRIBUTE_HAS_LINK = "has-link";
private static final String ATTRIBUTE_COPYTO_SOURCE_LIST = "copy-to-source";
private static final String ATTRIBUTE_OUT_DITA_FILES_LIST = "out-dita";
private static final String ATTRIBUTE_CHUNKED_DITAMAP_LIST = "chunked-ditamap";
private static final String ATTRIBUTE_FLAG_IMAGE_LIST = "flag-image";
private static final String ATTRIBUTE_SUBSIDIARY_TARGET_LIST = "subtarget";
private static final String ATTRIBUTE_CHUNK_TOPIC_LIST = "skip-chunk";
private static final String ATTRIBUTE_ACTIVE = "active";
/** File name for chuncked dita map list file */
public static final String CHUNKED_DITAMAP_LIST_FILE = "chunkedditamap.list";
/** File name for chunked topic list file */
public static final String CHUNKED_TOPIC_LIST_FILE = "chunkedtopic.list";
/** File name for skip chunk list file */
public static final String CHUNK_TOPIC_LIST_FILE = "skipchunk.list";
/** File name for coderef list file */
public static final String CODEREF_LIST_FILE = "coderef.list";
/** File name for conref list file */
public static final String CONREF_LIST_FILE = "conref.list";
/** File name for conref push list file */
public static final String CONREF_PUSH_LIST_FILE = "conrefpush.list";
/** File name for conref targets list file */
public static final String CONREF_TARGET_LIST_FILE = "conreftargets.list";
/** File name for copy-to source list file */
public static final String COPYTO_SOURCE_LIST_FILE = "copytosource.list";
/** File name for copy-to target2sourcemap list file */
public static final String COPYTO_TARGET_TO_SOURCE_MAP_LIST_FILE = "copytotarget2sourcemap.list";
/** File name for flag image list file */
public static final String FLAG_IMAGE_LIST_FILE = "flagimage.list";
/** File name for map list file */
public static final String FULL_DITAMAP_LIST_FILE = "fullditamap.list";
/** File name for map and topic list file */
public static final String FULL_DITAMAP_TOPIC_LIST_FILE = "fullditamapandtopic.list";
/** File name for topic list file */
public static final String FULL_DITA_TOPIC_LIST_FILE = "fullditatopic.list";
/** File name for href topic list file */
public static final String HREF_DITA_TOPIC_LIST_FILE = "hrefditatopic.list";
/** File name for href targets list file */
public static final String HREF_TARGET_LIST_FILE = "hreftargets.list";
/** File name for candidate topics list file */
public static final String HREF_TOPIC_LIST_FILE = "canditopics.list";
/** File name for html list file */
public static final String HTML_LIST_FILE = "html.list";
/** File name for image list file */
public static final String IMAGE_LIST_FILE = "image.list";
/** File name for input file list file */
public static final String INPUT_DITAMAP_LIST_FILE = "user.input.file.list";
/** File name for key definition file */
public static final String KEYDEF_LIST_FILE = "keydef.xml";
/** File name for key definition file */
public static final String SUBJECT_SCHEME_KEYDEF_LIST_FILE = "schemekeydef.xml";
/** File name for keyref list file */
public static final String KEYREF_LIST_FILE = "keyref.list";
/** File name for key list file */
public static final String KEY_LIST_FILE = "key.list";
/** File name for out dita files list file */
public static final String OUT_DITA_FILES_LIST_FILE = "outditafiles.list";
/** File name for relflag image list file */
public static final String REL_FLAGIMAGE_LIST_FILE = "relflagimage.list";
/** File name for resource-only list file */
public static final String RESOURCE_ONLY_LIST_FILE = "resourceonly.list";
/** File name for subject scheme list file */
public static final String SUBJEC_SCHEME_LIST_FILE = "subjectscheme.list";
/** File name for subtargets list file */
public static final String SUBSIDIARY_TARGET_LIST_FILE = "subtargets.list";
/** File name for temporary input file list file */
public static final String USER_INPUT_FILE_LIST_FILE = "usr.input.file.list";
/** Map of legacy list files to file info boolean fields. */
private static final Map<String, Field> listToFieldMap = new HashMap<String, Field>();
/** Map of serialization attributes to file info boolean fields. */
private static final Map<String, Field> attrToFieldMap= new HashMap<String, Field>();
static {
try {
listToFieldMap.put(CHUNKED_TOPIC_LIST, FileInfo.class.getField("isChunked"));
listToFieldMap.put(CONREF_LIST, FileInfo.class.getField("hasConref"));
listToFieldMap.put(HREF_DITA_TOPIC_LIST, FileInfo.class.getField("hasLink"));
listToFieldMap.put(KEYREF_LIST, FileInfo.class.getField("hasKeyref"));
listToFieldMap.put(CODEREF_LIST, FileInfo.class.getField("hasCoderef"));
listToFieldMap.put(RESOURCE_ONLY_LIST, FileInfo.class.getField("isResourceOnly"));
listToFieldMap.put(HREF_TARGET_LIST, FileInfo.class.getField("isTarget"));
listToFieldMap.put(CONREF_TARGET_LIST, FileInfo.class.getField("isConrefTarget"));
listToFieldMap.put(HREF_TOPIC_LIST, FileInfo.class.getField("isNonConrefTarget"));
listToFieldMap.put(CONREF_PUSH_LIST, FileInfo.class.getField("isConrefPush"));
listToFieldMap.put(SUBJEC_SCHEME_LIST, FileInfo.class.getField("isSubjectScheme"));
listToFieldMap.put(COPYTO_SOURCE_LIST, FileInfo.class.getField("isCopyToSource"));
listToFieldMap.put(OUT_DITA_FILES_LIST, FileInfo.class.getField("isOutDita"));
listToFieldMap.put(CHUNKED_DITAMAP_LIST, FileInfo.class.getField("isChunkedDitaMap"));
listToFieldMap.put(FLAG_IMAGE_LIST, FileInfo.class.getField("isFlagImage"));
listToFieldMap.put(SUBSIDIARY_TARGET_LIST, FileInfo.class.getField("isSubtarget"));
listToFieldMap.put(CHUNK_TOPIC_LIST, FileInfo.class.getField("isSkipChunk"));
attrToFieldMap.put(ATTRIBUTE_CHUNKED, FileInfo.class.getField("isChunked"));
attrToFieldMap.put(ATTRIBUTE_HAS_LINK, FileInfo.class.getField("hasLink"));
attrToFieldMap.put(ATTRIBUTE_HAS_CONREF, FileInfo.class.getField("hasConref"));
attrToFieldMap.put(ATTRIBUTE_HAS_KEYREF, FileInfo.class.getField("hasKeyref"));
attrToFieldMap.put(ATTRIBUTE_HAS_CODEREF, FileInfo.class.getField("hasCoderef"));
attrToFieldMap.put(ATTRIBUTE_RESOURCE_ONLY, FileInfo.class.getField("isResourceOnly"));
attrToFieldMap.put(ATTRIBUTE_TARGET, FileInfo.class.getField("isTarget"));
attrToFieldMap.put(ATTRIBUTE_CONREF_TARGET, FileInfo.class.getField("isConrefTarget"));
attrToFieldMap.put(ATTRIBUTE_NON_CONREF_TARGET, FileInfo.class.getField("isNonConrefTarget"));
attrToFieldMap.put(ATTRIBUTE_CONREF_PUSH, FileInfo.class.getField("isConrefPush"));
attrToFieldMap.put(ATTRIBUTE_SUBJECT_SCHEME, FileInfo.class.getField("isSubjectScheme"));
attrToFieldMap.put(ATTRIBUTE_COPYTO_SOURCE_LIST, FileInfo.class.getField("isCopyToSource"));
attrToFieldMap.put(ATTRIBUTE_OUT_DITA_FILES_LIST, FileInfo.class.getField("isOutDita"));
attrToFieldMap.put(ATTRIBUTE_CHUNKED_DITAMAP_LIST, FileInfo.class.getField("isChunkedDitaMap"));
attrToFieldMap.put(ATTRIBUTE_FLAG_IMAGE_LIST, FileInfo.class.getField("isFlagImage"));
attrToFieldMap.put(ATTRIBUTE_SUBSIDIARY_TARGET_LIST, FileInfo.class.getField("isSubtarget"));
attrToFieldMap.put(ATTRIBUTE_CHUNK_TOPIC_LIST, FileInfo.class.getField("isSkipChunk"));
attrToFieldMap.put(ATTRIBUTE_ACTIVE, FileInfo.class.getField("isActive"));
} catch (final NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
private final Map<String, Object> prop;
private final File tempDir;
private final Map<String, FileInfo> files = new HashMap<String, FileInfo>();
public Job(final File tempDir) throws IOException {
this.tempDir = tempDir;
prop = new HashMap<String, Object>();
read();
}
private void read() throws IOException {
final File jobFile = new File(tempDir, JOB_FILE);
if (jobFile.exists()) {
InputStream in = null;
try {
final XMLReader parser = StringUtils.getXMLReader();
parser.setContentHandler(new JobHandler(prop, files));
in = new FileInputStream(jobFile);
parser.parse(new InputSource(in));
} catch (final SAXException e) {
throw new IOException("Failed to read job file: " + e.getMessage());
} finally {
if (in != null) {
in.close();
}
}
return;
}
final Properties p = new Properties();
final File ditalist = new File(tempDir, FILE_NAME_DITA_LIST);
final File xmlDitalist=new File(tempDir, FILE_NAME_DITA_LIST_XML);
InputStream in = null;
try{
if(xmlDitalist.exists()) {
in = new FileInputStream(xmlDitalist);
p.loadFromXML(in);
} else if(ditalist.exists()) {
in = new FileInputStream(ditalist);
p.load(in);
}
} catch(final IOException e) {
throw new IOException("Failed to read file: " + e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (final IOException e) {
throw new IOException("Failed to close file: " + e.getMessage());
}
}
}
readProperties(p);
}
private void readProperties(final Properties p) {
for (final Map.Entry<Object, Object> e: p.entrySet()) {
if (((String) e.getValue()).length() > 0) {
final String key = e.getKey().toString();
if (key.equals(COPYTO_TARGET_TO_SOURCE_MAP_LIST)) {
setMap(e.getKey().toString(), StringUtils.restoreMap(e.getValue().toString()));
} else if (key.endsWith("list")) {
setSet(e.getKey().toString(), StringUtils.restoreSet(e.getValue().toString()));
} else {
setProperty(e.getKey().toString(), e.getValue().toString());
}
}
}
}
private final static class JobHandler extends DefaultHandler {
private final Map<String, Object> prop;
private final Map<String, FileInfo> files;
private StringBuilder buf;
private String name;
private String key;
private Set<String> set;
private Map<String, String> map;
JobHandler(final Map<String, Object> prop, final Map<String, FileInfo> files) {
this.prop = prop;
this.files = files;
}
@Override
public void characters(final char[] ch, final int start, final int length) throws SAXException {
if (buf != null) {
buf.append(ch, start, length);
}
}
@Override
public void ignorableWhitespace(final char[] ch, final int start, final int length) throws SAXException {
if (buf != null) {
buf.append(ch, start, length);
}
}
@Override
public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException {
final String n = localName != null ? localName : qName;
if (n.equals(ELEMENT_PROPERTY)) {
name = atts.getValue(ATTRIBUTE_NAME);
} else if (n.equals(ELEMENT_STRING)) {
buf = new StringBuilder();
} else if (n.equals(ELEMENT_SET)) {
set = new HashSet<String>();
} else if (n.equals(ELEMENT_MAP)) {
map = new HashMap<String, String>();
} else if (n.equals(ELEMENT_ENTRY)) {
key = atts.getValue(ATTRIBUTE_KEY);
} else if (n.equals(ELEMENT_FILE)) {
final String path = atts.getValue(ATTRIBUTE_PATH);
final FileInfo i = new FileInfo(path);
i.format = atts.getValue(ATTRIBUTE_FORMAT);
try {
for (Map.Entry<String, Field> e: attrToFieldMap.entrySet()) {
e.getValue().setBoolean(i, Boolean.parseBoolean(atts.getValue(e.getKey())));
}
} catch (final IllegalAccessException ex) {
throw new RuntimeException(ex);
}
files.put(path, i);
}
}
@Override
public void endElement(final String uri, final String localName, final String qName) throws SAXException {
final String n = localName != null ? localName : qName;
if (n.equals(ELEMENT_PROPERTY)) {
name = null;
} else if (n.equals(ELEMENT_STRING)) {
if (set != null) {
set.add(buf.toString());
} else if (map != null) {
map.put(key, buf.toString());
} else {
prop.put(name, buf.toString());
}
buf = null;
} else if (n.equals(ELEMENT_SET)) {
prop.put(name, set);
set = null;
} else if (n.equals(ELEMENT_MAP)) {
prop.put(name, map);
map = null;
} else if (n.equals(ELEMENT_ENTRY)) {
key = null;
}
}
}
/**
* Store job into temporary configuration files.
*
* @throws IOException if writing configuration files failed
*/
public void write() throws IOException {
OutputStream outStream = null;
XMLStreamWriter out = null;
try {
outStream = new FileOutputStream(new File(tempDir, JOB_FILE));
out = XMLOutputFactory.newInstance().createXMLStreamWriter(outStream, "UTF-8");
out.writeStartDocument();
out.writeStartElement(ELEMENT_JOB);
for (final Map.Entry<String, Object> e: prop.entrySet()) {
out.writeStartElement(ELEMENT_PROPERTY);
out.writeAttribute(ATTRIBUTE_NAME, e.getKey());
if (e.getValue() instanceof String) {
out.writeStartElement(ELEMENT_STRING);
out.writeCharacters(e.getValue().toString());
out.writeEndElement(); //string
} else if (e.getValue() instanceof Set) {
out.writeStartElement(ELEMENT_SET);
final Set<?> s = (Set<?>) e.getValue();
for (final Object o: s) {
out.writeStartElement(ELEMENT_STRING);
out.writeCharacters(o.toString());
out.writeEndElement(); //string
}
out.writeEndElement(); //set
} else if (e.getValue() instanceof Map) {
out.writeStartElement(ELEMENT_MAP);
final Map<?, ?> s = (Map<?, ?>) e.getValue();
for (final Map.Entry<?, ?> o: s.entrySet()) {
out.writeStartElement(ELEMENT_ENTRY);
out.writeAttribute(ATTRIBUTE_KEY, o.getKey().toString());
out.writeStartElement(ELEMENT_STRING);
out.writeCharacters(o.getValue().toString());
out.writeEndElement(); //string
out.writeEndElement(); //entry
}
out.writeEndElement(); //string
} else {
out.writeStartElement(e.getValue().getClass().getName());
out.writeCharacters(e.getValue().toString());
out.writeEndElement(); //string
}
out.writeEndElement(); //property
}
out.writeStartElement(ELEMENT_FILES);
for (final FileInfo i: files.values()) {
out.writeStartElement(ELEMENT_FILE);
out.writeAttribute(ATTRIBUTE_PATH, i.file);
if (i.format != null) {
out.writeAttribute(ATTRIBUTE_FORMAT, i.format);
}
try {
for (Map.Entry<String, Field> e: attrToFieldMap.entrySet()) {
out.writeAttribute(e.getKey(), Boolean.toString(e.getValue().getBoolean(i)));
}
} catch (final IllegalAccessException ex) {
throw new RuntimeException(ex);
}
out.writeEndElement(); //file
}
out.writeEndElement(); //files
out.writeEndElement(); //job
out.writeEndDocument();
} catch (final IOException e) {
throw new IOException("Failed to write file: " + e.getMessage());
} catch (final XMLStreamException e) {
throw new IOException("Failed to serialize job file: " + e.getMessage());
} finally {
if (out != null) {
try {
out.close();
} catch (final XMLStreamException e) {
throw new IOException("Failed to close file: " + e.getMessage());
}
}
if (outStream != null) {
try {
outStream.close();
} catch (final IOException e) {
throw new IOException("Failed to close file: " + e.getMessage());
}
}
}
final Properties p = new Properties();
for (final Map.Entry<String, Object> e: prop.entrySet()) {
if (e.getValue() instanceof Set) {
p.put(e.getKey(), StringUtils.assembleString((Collection) e.getValue(), COMMA));
} else if (e.getValue() instanceof Map) {
p.put(e.getKey(), StringUtils.assembleString((Map) e.getValue(), COMMA));
} else {
p.put(e.getKey(), e.getValue());
}
}
FileOutputStream propertiesOutputStream = null;
try {
propertiesOutputStream = new FileOutputStream(new File(tempDir, FILE_NAME_DITA_LIST));
p.store(propertiesOutputStream, null);
propertiesOutputStream.flush();
} catch (final IOException e) {
throw new IOException("Failed to write file: " + e.getMessage());
} finally {
if (propertiesOutputStream != null) {
try {
propertiesOutputStream.close();
} catch (final IOException e) {
throw new IOException("Failed to close file: " + e.getMessage());
}
}
}
FileOutputStream xmlOutputStream = null;
try {
xmlOutputStream = new FileOutputStream(new File(tempDir, FILE_NAME_DITA_LIST_XML));
p.storeToXML(xmlOutputStream, null);
xmlOutputStream.flush();
} catch (final IOException e) {
throw new IOException("Failed to write file: " + e.getMessage());
} finally {
if (xmlOutputStream != null) {
try {
xmlOutputStream.close();
} catch (final IOException e) {
throw new IOException("Failed to close file: " + e.getMessage());
}
}
}
}
/**
* Searches for the property with the specified key in this property list.
*
* @param key property key
* @return the value in this property list with the specified key value, {@code null} if not found
*/
public String getProperty(final String key) {
final Object value = prop.get(key);
if (value == null) {
return null;
} else if (value instanceof Set) { // migration support
return StringUtils.assembleString((Collection) value, COMMA);
} else if (value instanceof Map) { // migration support
return StringUtils.assembleString((Map) value, COMMA);
} else {
return (String) value;
}
}
/**
* Searches for the property with the specified key in this property list.
*
* @param key property key
* @return the value in this property list with the specified key value, empty map if not found
*/
public Map<String, String> getMap(final String key) {
final Object value = prop.get(key);
if (value == null) {
return Collections.emptyMap();
} else if (value instanceof String) { // migration support
return StringUtils.restoreMap((String) value);
} else {
return (Map<String, String>) value;
}
}
/**
* Searches for the property with the specified key in this property list.
*
* @param key property key
* @return the value in this property list with the specified key value, empty set if not found
*/
public Set<String> getSet(final String key) {
if (key.equals(FULL_DITAMAP_TOPIC_LIST)) {
final Set<String> ret = new HashSet<String>();
ret.addAll(getSet(FULL_DITA_TOPIC_LIST));
ret.addAll(getSet(FULL_DITAMAP_LIST));
return ret;
} else if (key.equals(FULL_DITA_TOPIC_LIST)) {
final Set<String> ret = new HashSet<String>();
for (final FileInfo f: files.values()) {
if (f.isActive && "dita".equals(f.format)) {
ret.add(f.file);
}
}
return ret;
} else if (key.equals(FULL_DITAMAP_LIST)) {
final Set<String> ret = new HashSet<String>();
for (final FileInfo f: files.values()) {
if (f.isActive && "ditamap".equals(f.format)) {
ret.add(f.file);
}
}
return ret;
} else if (key.equals(HTML_LIST)) {
return getFilesByFormat("html");
} else if (key.equals(IMAGE_LIST)) {
return getFilesByFormat("image");
} else if (listToFieldMap.containsKey(key)) {
final Set<String> ret = new HashSet<String>();
try {
final Field field = listToFieldMap.get(key);
for (final FileInfo f: files.values()) {
if (field.getBoolean(f)) {
ret.add(f.file);
}
}
} catch (final IllegalAccessException e) {
throw new RuntimeException(e);
}
return ret;
} else {
final Object value = prop.get(key);
if (value == null) {
return Collections.emptySet();
} else if (value instanceof String) { // migration support
return StringUtils.restoreSet((String) value);
} else {
return (Set<String>) value;
}
}
}
private Set<String> getFilesByFormat(final String...formats) {
final Set<String> ret = new HashSet<String>();
for (final FileInfo f: files.values()) {
format: for (final String format: formats) {
if (format.equals(f.format)) {
ret.add(f.file);
break format;
}
}
}
return ret;
}
/**
* Set property value.
*
* @param key property key
* @param value property value
* @return the previous value of the specified key in this property list, or {@code null} if it did not have one
*/
public Object setProperty(final String key, final String value) {
return prop.put(key, value);
}
/**
* Set property value.
*
* @param key property key
* @param value property value
* @return the previous value of the specified key in this property list, or {@code null} if it did not have one
*/
public Set<String> setSet(final String key, final Set<String> value) {
Object previous = null;
if (key.equals(FULL_DITAMAP_TOPIC_LIST)) {
//throw new RuntimeException(FULL_DITAMAP_TOPIC_LIST + " is a compound set, cannot be directly generated");
} else if (key.equals(FULL_DITA_TOPIC_LIST)) {
for (FileInfo f: files.values()) {
if ("dita".equals(f.format)) {
f.isActive = false;
}
}
for (final String f: value) {
final FileInfo ff = getOrAdd(f);
ff.format = "dita";
ff.isActive = true;
}
} else if (key.equals(FULL_DITAMAP_LIST)) {
for (FileInfo f: files.values()) {
if ("ditamap".equals(f.format)) {
f.isActive = false;
}
}
for (final String f: value) {
final FileInfo ff = getOrAdd(f);
ff.format = "ditamap";
ff.isActive = true;
}
} else if (key.equals(HTML_LIST)) {
for (final String f: value) {
getOrAdd(f).format = "html";
}
} else if (key.equals(IMAGE_LIST)) {
for (final String f: value) {
getOrAdd(f).format = "image";
}
} else if (listToFieldMap.containsKey(key)) {
try {
final Field field = listToFieldMap.get(key);
for (final String f: value) {
field.setBoolean(getOrAdd(f), true);
}
} catch (final IllegalAccessException e) {
throw new RuntimeException(e);
}
} else {
previous = prop.put(key, value);
if (previous == null) {
return null;
} else if (previous instanceof String) { // migration support
return StringUtils.restoreSet((String) previous);
} else {
return (Set<String>) previous;
}
}
return (Set<String>) previous;
}
private FileInfo getOrAdd(final String f) {
FileInfo i = files.get(f);
if (i == null) {
i = new FileInfo(f);
files.put(f, i);
}
return i;
}
/**
* Set property value.
*
* @param key property key
* @param value property value
* @return the previous value of the specified key in this property list, or {@code null} if it did not have one
*/
public Map<String, String> setMap(final String key, final Map<String, String> value) {
final Object previous = prop.put(key, value);
if (previous == null) {
return null;
} else if (previous instanceof String) { // migration support
return StringUtils.restoreMap((String) previous);
} else {
return (Map<String, String>) previous;
}
}
/**
* Return the copy-to map.
* @return copy-to map
*/
public Map<String, String> getCopytoMap() {
return getMap(COPYTO_TARGET_TO_SOURCE_MAP_LIST);
}
/**
* @return the schemeSet
*/
public Set<String> getSchemeSet() {
return getSet(SUBJEC_SCHEME_LIST);
}
/**
* Get input file
*
* @return input file path relative to input directory
*/
public String getInputMap() {
return getProperty(INPUT_DITAMAP);
}
/**
* Get input directory.
*
* @return absolute input directory path
*/
public String getInputDir() {
return getProperty(INPUT_DIR);
}
/**
* Get all file info objects
*
* @return map of file info objects
*/
public Map<String, FileInfo> getFileInfo() {
return Collections.unmodifiableMap(files);
}
/**
* Add a collection of file info objects
*
* @param fs file info objects
*/
public void addAll(final Collection<FileInfo> fs) {
for (final FileInfo f: fs) {
files.put(f.file, f);
}
}
// Utility methods
/**
* Write list file.
*
* @param prop property name
* @throws IOException if writing fails
*/
@Deprecated
public void writeList(final String prop) throws IOException {
final String filename = prop.equals(INPUT_DITAMAP)
? INPUT_DITAMAP_LIST_FILE
: prop.substring(0, prop.lastIndexOf("list")) + ".list";
writeList(prop, filename);
}
/**
* Write list file.
*
* @param prop property name
* @param filename list file name
* @throws IOException if writing fails
*/
@Deprecated
private void writeList(final String prop, final String filename) throws IOException {
final File listFile = new File(tempDir, filename);
BufferedWriter topicWriter = null;
try {
topicWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(listFile)));
final Set<String> topics = getSet(prop);
for (final Iterator<String> i = topics.iterator(); i.hasNext();) {
topicWriter.write(i.next());
if (i.hasNext()) {
topicWriter.write("\n");
}
}
topicWriter.flush();
} finally {
if (topicWriter != null) {
topicWriter.close();
}
}
}
/**
* File info object.
*/
public static final class FileInfo {
public final String file;
public String format;
public boolean hasConref;
public boolean isChunked;
public boolean hasLink;
public boolean isResourceOnly;
public boolean isTarget;
public boolean isConrefTarget;
public boolean isNonConrefTarget;
public boolean isConrefPush;
public boolean hasKeyref;
public boolean hasCoderef;
public boolean isSubjectScheme;
public boolean isSkipChunk;
public boolean isSubtarget;
public boolean isFlagImage;
public boolean isChunkedDitaMap;
public boolean isOutDita;
public boolean isCopyToSource;
public boolean isActive;
FileInfo(final String file) {
this.file = file;
}
public static class Builder {
private String file;
private String format;
private boolean hasConref;
private boolean isChunked;
private boolean hasLink;
private boolean isResourceOnly;
private boolean isTarget;
private boolean isConrefTarget;
private boolean isNonConrefTarget;
private boolean isConrefPush;
private boolean hasKeyref;
private boolean hasCoderef;
private boolean isSubjectScheme;
private boolean isSkipChunk;
private boolean isSubtarget;
private boolean isFlagImage;
private boolean isChunkedDitaMap;
private boolean isOutDita;
private boolean isCopyToSource;
private boolean isActive;
public Builder() {}
public Builder(final FileInfo orig) {
file = orig.file;
format = orig.format;
hasConref = orig.hasConref;
isChunked = orig.isChunked;
hasLink = orig.hasLink;
isResourceOnly = orig.isResourceOnly;
isTarget = orig.isTarget;
isConrefTarget = orig.isConrefTarget;
isNonConrefTarget = orig.isNonConrefTarget;
isConrefPush = orig.isConrefPush;
hasKeyref = orig.hasKeyref;
hasCoderef = orig.hasCoderef;
isSubjectScheme = orig.isSubjectScheme;
isSkipChunk = orig.isSkipChunk;
isSubtarget = orig.isSubtarget;
isFlagImage = orig.isFlagImage;
isChunkedDitaMap = orig.isChunkedDitaMap;
isOutDita = orig.isOutDita;
isCopyToSource = orig.isCopyToSource;
isActive = orig.isActive;
}
public Builder file(final String file) { this.file = file; return this; }
public Builder format(final String format) { this.format = format; return this; }
public Builder hasConref(final boolean hasConref) { this.hasConref = hasConref; return this; }
public Builder isChunked(final boolean isChunked) { this.isChunked = isChunked; return this; }
public Builder hasLink(final boolean hasLink) { this.hasLink = hasLink; return this; }
public Builder isResourceOnly(final boolean isResourceOnly) { this.isResourceOnly = isResourceOnly; return this; }
public Builder isTarget(final boolean isTarget) { this.isTarget = isTarget; return this; }
public Builder isConrefTarget(final boolean isConrefTarget) { this.isConrefTarget = isConrefTarget; return this; }
public Builder isNonConrefTarget(final boolean isNonConrefTarget) { this.isNonConrefTarget = isNonConrefTarget; return this; }
public Builder isConrefPush(final boolean isConrefPush) { this.isConrefPush = isConrefPush; return this; }
public Builder hasKeyref(final boolean hasKeyref) { this.hasKeyref = hasKeyref; return this; }
public Builder hasCoderef(final boolean hasCoderef) { this.hasCoderef = hasCoderef; return this; }
public Builder isSubjectScheme(final boolean isSubjectScheme) { this.isSubjectScheme = isSubjectScheme; return this; }
public Builder isSkipChunk(final boolean isSkipChunk) { this.isSkipChunk = isSkipChunk; return this; }
public Builder isSubtarget(final boolean isSubtarget) { this.isSubtarget = isSubtarget; return this; }
public Builder isFlagImage(final boolean isFlagImage) { this.isFlagImage = isFlagImage; return this; }
public Builder isChunkedDitaMap(final boolean isChunkedDitaMap) { this.isChunkedDitaMap = isChunkedDitaMap; return this; }
public Builder isOutDita(final boolean isOutDita) { this.isOutDita = isOutDita; return this; }
public Builder isCopyToSource(final boolean isCopyToSource) { this.isCopyToSource = isCopyToSource; return this; }
public Builder isActive(final boolean isActive) { this.isActive = isActive; return this; }
public FileInfo build() {
if (file == null) {
throw new IllegalArgumentException("file may not be null");
}
final FileInfo fi = new FileInfo(file);
fi.format = format;
fi.hasConref = hasConref;
fi.isChunked = isChunked;
fi.hasLink = hasLink;
fi.isResourceOnly = isResourceOnly;
fi.isTarget = isTarget;
fi.isConrefTarget = isConrefTarget;
fi.isNonConrefTarget = isNonConrefTarget;
fi.isConrefPush = isConrefPush;
fi.hasKeyref = hasKeyref;
fi.hasCoderef = hasCoderef;
fi.isSubjectScheme = isSubjectScheme;
fi.isSkipChunk = isSkipChunk;
fi.isSubtarget = isSubtarget;
fi.isFlagImage = isFlagImage;
fi.isChunkedDitaMap = isChunkedDitaMap;
fi.isOutDita = isOutDita;
fi.isCopyToSource = isCopyToSource;
fi.isActive = isActive;
return fi;
}
}
}
}
|
package org.jenetics.util;
import javolution.lang.Immutable;
public interface ISeq<T>
extends
Seq<T>,
Copyable<MSeq<T>>,
Immutable
{
@Override
public ISeq<T> subSeq(final int start, final int end);
@Override
public ISeq<T> subSeq(final int start);
@Override
public <B> ISeq<B> map(final Function<? super T, ? extends B> mapper);
/**
* <p>
* Helper method for up-casting an given immutable sequence. This allows you
* to assign this sequence to an sequence where the element type is a super
* type of {@code T}.
* </p>
* [code]
* ISeq<Double> da = new Array<Double>(0.0, 1.0, 2.0).toISeq();
* ISeq<Number> na = da.upcast(da);
* ISeq<Object>; oa = na.upcast(na);
* oa = da.upcast(da);
* [/code]
*
* @param seq the sequence to cast.
* @return the up-casted sequence.
*/
public <A> ISeq<A> upcast(final ISeq<? extends A> seq);
/**
* Return a shallow copy of this sequence. The sequence elements are not
* cloned.
*
* @return a shallow copy of this sequence.
*/
@Override
public MSeq<T> copy();
}
|
package org.jfree.chart;
import java.awt.Color;
public class Colors {
private Colors() {
// no need to instantiate this class
}
/**
* Returns the default colors.
*
* @return The default colors.
*/
public static Color[] getDefaultColors() {
return createFancyLightColors();
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Fancy (light background)" settings. A new array
* instance is created for each call to this method. A link to the
* "i want hue" utility is given in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createFancyLightColors() {
Color[] result = new Color[10];
result[0] = new Color(239, 164, 127);
result[1] = new Color(140, 228, 139);
result[2] = new Color(155, 208, 227);
result[3] = new Color(221, 228, 95);
result[4] = new Color(118, 223, 194);
result[5] = new Color(240, 166, 184);
result[6] = new Color(231, 185, 98);
result[7] = new Color(186, 214, 150);
result[8] = new Color(217, 184, 226);
result[9] = new Color(201, 212, 116);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Fancy (dark background)" settings. A new array
* instance is created for each call to this method. A link to the
* "i want hue" utility is given in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createFancyDarkColors() {
Color[] result = new Color[10];
result[0] = new Color(78, 81, 97);
result[1] = new Color(91, 104, 51);
result[2] = new Color(138, 75, 65);
result[3] = new Color(72, 62, 34);
result[4] = new Color(58, 100, 75);
result[5] = new Color(39, 63, 59);
result[6] = new Color(105, 68, 75);
result[7] = new Color(120, 90, 120);
result[8] = new Color(119, 90, 50);
result[9] = new Color(59, 103, 111);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Shades" settings. A new array instance is created for
* each call to this method. A link to the "i want hue" utility is given
* in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createShadesColors() {
Color[] result = new Color[10];
result[0] = new Color(137, 132, 104);
result[1] = new Color(217, 232, 208);
result[2] = new Color(53, 48, 40);
result[3] = new Color(240, 225, 172);
result[4] = new Color(196, 160, 128);
result[5] = new Color(92, 96, 87);
result[6] = new Color(136, 141, 136);
result[7] = new Color(106, 93, 66);
result[8] = new Color(205, 199, 168);
result[9] = new Color(158, 168, 143);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Tarnish" settings. A new array instance is created for
* each call to this method. A link to the "i want hue" utility is given
* in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createTarnishColors() {
Color[] result = new Color[10];
result[0] = new Color(148, 129, 121);
result[1] = new Color(179, 181, 136);
result[2] = new Color(204, 163, 140);
result[3] = new Color(102, 93, 80);
result[4] = new Color(164, 178, 159);
result[5] = new Color(156, 130, 100);
result[6] = new Color(129, 142, 124);
result[7] = new Color(186, 168, 159);
result[8] = new Color(144, 148, 108);
result[9] = new Color(189, 169, 131);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Pastel" settings. A new array instance is created for
* each call to this method. A link to the "i want hue" utility is given
* in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createPastelColors() {
Color[] result = new Color[10];
result[0] = new Color(232, 177, 165);
result[1] = new Color(207, 235, 142);
result[2] = new Color(142, 220, 220);
result[3] = new Color(228, 186, 115);
result[4] = new Color(187, 200, 230);
result[5] = new Color(157, 222, 177);
result[6] = new Color(234, 183, 210);
result[7] = new Color(213, 206, 169);
result[8] = new Color(202, 214, 205);
result[9] = new Color(195, 204, 133);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Pimp" settings. A new array instance is created for
* each call to this method. A link to the "i want hue" utility is given
* in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createPimpColors() {
Color[] result = new Color[10];
result[0] = new Color(197, 75, 103);
result[1] = new Color(85, 154, 48);
result[2] = new Color(122, 110, 206);
result[3] = new Color(190, 100, 50);
result[4] = new Color(201, 79, 209);
result[5] = new Color(95, 127, 170);
result[6] = new Color(147, 129, 39);
result[7] = new Color(63, 142, 96);
result[8] = new Color(186, 84, 150);
result[9] = new Color(219, 66, 52);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Intense" settings. A new array instance is created for
* each call to this method. A link to the "i want hue" utility is given
* in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createIntenseColors() {
Color[] result = new Color[10];
result[0] = new Color(107, 122, 160);
result[1] = new Color(99, 176, 67);
result[2] = new Color(214, 85, 52);
result[3] = new Color(202, 79, 200);
result[4] = new Color(184, 149, 57);
result[5] = new Color(82, 168, 146);
result[6] = new Color(194, 84, 128);
result[7] = new Color(77, 102, 50);
result[8] = new Color(132, 108, 197);
result[9] = new Color(144, 74, 61);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Fluo" settings. A new array instance is created for
* each call to this method. A link to the "i want hue" utility is given
* in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createFluoColors() {
Color[] result = new Color[10];
result[0] = new Color(108, 236, 137);
result[1] = new Color(253, 187, 46);
result[2] = new Color(56, 236, 216);
result[3] = new Color(171, 231, 51);
result[4] = new Color(221, 214, 74);
result[5] = new Color(106, 238, 70);
result[6] = new Color(172, 230, 100);
result[7] = new Color(242, 191, 82);
result[8] = new Color(221, 233, 56);
result[9] = new Color(242, 206, 47);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Red Roses" settings. A new array instance is created
* for each call to this method. A link to the "i want hue" utility is
* given in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createRedRosesColors() {
Color[] result = new Color[10];
result[0] = new Color(230, 129, 128);
result[1] = new Color(233, 56, 39);
result[2] = new Color(225, 45, 102);
result[3] = new Color(172, 79, 55);
result[4] = new Color(214, 154, 128);
result[5] = new Color(156, 96, 81);
result[6] = new Color(190, 77, 91);
result[7] = new Color(228, 121, 91);
result[8] = new Color(216, 63, 80);
result[9] = new Color(209, 75, 46);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Ochre Sand" settings. A new array instance is created
* for each call to this method. A link to the "i want hue" utility is
* given in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createOchreSandColors() {
Color[] result = new Color[10];
result[0] = new Color(218, 180, 125);
result[1] = new Color(245, 184, 36);
result[2] = new Color(159, 103, 28);
result[3] = new Color(124, 96, 55);
result[4] = new Color(224, 132, 56);
result[5] = new Color(185, 143, 48);
result[6] = new Color(229, 171, 97);
result[7] = new Color(232, 165, 54);
result[8] = new Color(171, 102, 53);
result[9] = new Color(160, 122, 71);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Yellow Lime" settings. A new array instance is created
* for each call to this method. A link to the "i want hue" utility is
* given in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createYellowLimeColors() {
Color[] result = new Color[10];
result[0] = new Color(235, 203, 59);
result[1] = new Color(113, 108, 56);
result[2] = new Color(222, 206, 134);
result[3] = new Color(169, 166, 62);
result[4] = new Color(214, 230, 54);
result[5] = new Color(225, 221, 105);
result[6] = new Color(128, 104, 23);
result[7] = new Color(162, 151, 86);
result[8] = new Color(117, 121, 25);
result[9] = new Color(183, 179, 40);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Green Mint" settings. A new array instance is created
* for each call to this method. A link to the "i want hue" utility is
* given in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createGreenMintColors() {
Color[] result = new Color[10];
result[0] = new Color(99, 224, 113);
result[1] = new Color(98, 132, 83);
result[2] = new Color(145, 234, 49);
result[3] = new Color(181, 215, 158);
result[4] = new Color(95, 171, 43);
result[5] = new Color(100, 208, 142);
result[6] = new Color(172, 222, 84);
result[7] = new Color(75, 139, 53);
result[8] = new Color(177, 216, 123);
result[9] = new Color(83, 223, 60);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Ice Cube" settings. A new array instance is created
* for each call to this method. A link to the "i want hue" utility is
* given in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createIceCubeColors() {
Color[] result = new Color[10];
result[0] = new Color(112, 235, 233);
result[1] = new Color(54, 110, 100);
result[2] = new Color(211, 232, 208);
result[3] = new Color(94, 230, 191);
result[4] = new Color(76, 154, 155);
result[5] = new Color(156, 181, 157);
result[6] = new Color(67, 152, 126);
result[7] = new Color(112, 135, 119);
result[8] = new Color(155, 213, 192);
result[9] = new Color(80, 195, 190);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Blue Ocean" settings. A new array instance is created
* for each call to this method. A link to the "i want hue" utility is
* given in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createBlueOceanColors() {
Color[] result = new Color[10];
result[0] = new Color(53, 84, 154);
result[1] = new Color(41, 46, 57);
result[2] = new Color(115, 124, 151);
result[3] = new Color(38, 52, 91);
result[4] = new Color(84, 117, 211);
result[5] = new Color(76, 125, 181);
result[6] = new Color(109, 108, 112);
result[7] = new Color(48, 105, 134);
result[8] = new Color(72, 82, 107);
result[9] = new Color(91, 99, 144);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Indigo Night" settings. A new array instance is
* created for each call to this method. A link to the "i want hue"
* utility is given in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createIndigoNightColors() {
Color[] result = new Color[10];
result[0] = new Color(127, 88, 147);
result[1] = new Color(201, 67, 217);
result[2] = new Color(112, 97, 218);
result[3] = new Color(219, 134, 222);
result[4] = new Color(154, 80, 172);
result[5] = new Color(170, 106, 231);
result[6] = new Color(142, 111, 210);
result[7] = new Color(194, 149, 235);
result[8] = new Color(152, 118, 188);
result[9] = new Color(214, 101, 237);
return result;
}
/**
* Returns a palette of ten colors created using the "i want hue" utility,
* using the preset "Purple Wine" settings. A new array instance is created
* for each call to this method. A link to the "i want hue" utility is
* given in the class description.
*
* @return An array of ten colors (never <code>null</code>).
*/
public static Color[] createPurpleWineColors() {
Color[] result = new Color[10];
result[0] = new Color(116, 28, 93);
result[1] = new Color(112, 79, 75);
result[2] = new Color(178, 37, 101);
result[3] = new Color(109, 24, 56);
result[4] = new Color(167, 42, 140);
result[5] = new Color(66, 30, 40);
result[6] = new Color(128, 70, 95);
result[7] = new Color(78, 20, 56);
result[8] = new Color(155, 62, 111);
result[9] = new Color(139, 61, 75);
return result;
}
/**
* Returns a palette of 7 colors with earth tones.
*
* @return An array of 7 colors (never <code>null</code>).
*/
public static Color[] getEarthColors() {
Color[] result = new Color[7];
result[0] = new Color(98, 98, 98);
result[1] = new Color(159, 87, 43);
result[2] = new Color(194, 176, 46);
result[3] = new Color(134, 155, 64);
result[4] = new Color(57, 118, 40);
result[5] = new Color(40, 114, 110);
result[6] = new Color(78, 79, 62);
return result;
}
public static Color[] getBrewerQualitativeSet1N9Colors() {
Color[] result = new Color[9];
result[0] = new Color(228, 26, 28);
result[1] = new Color(55, 126, 184);
result[2] = new Color(77, 175, 74);
result[3] = new Color(152, 78, 163);
result[4] = new Color(255, 127, 0);
result[5] = new Color(255, 255, 51);
result[6] = new Color(166, 86, 40);
result[7] = new Color(247, 129, 191);
result[8] = new Color(153, 153, 153);
return result;
}
public static Color[] getBrewerQualitativePairedN12Colors() {
Color[] result = new Color[12];
result[0] = new Color(166, 206, 227);
result[1] = new Color(31, 120, 180);
result[2] = new Color(178, 223, 138);
result[3] = new Color(51, 160, 44);
result[4] = new Color(251, 154, 153);
result[5] = new Color(227, 26, 28);
result[6] = new Color(253, 191, 111);
result[7] = new Color(255, 127, 0);
result[8] = new Color(202, 178, 214);
result[9] = new Color(106, 61, 154);
result[10] = new Color(255, 255, 153);
result[11] = new Color(177, 89, 40);
return result;
}
public static Color[] getBrewerQualitativeSet3N12Colors() {
Color[] result = new Color[12];
result[0] = new Color(141, 211, 199);
result[1] = new Color(255, 255, 179);
result[2] = new Color(190, 186, 218);
result[3] = new Color(251, 128, 114);
result[4] = new Color(128, 177, 211);
result[5] = new Color(253, 180, 98);
result[6] = new Color(179, 222, 105);
result[7] = new Color(252, 205, 229);
result[8] = new Color(217, 217, 217);
result[9] = new Color(188, 128, 189);
result[10] = new Color(204, 235, 197);
result[11] = new Color(255, 237, 111);
return result;
}
public static Color[] getSAPMultiColor() {
return new Color[] {
new Color(255, 248, 163),
new Color(169, 204, 143),
new Color(178, 200, 217),
new Color(190, 163, 122),
new Color(243, 170, 121),
new Color(181, 181, 169),
new Color(230, 165, 164),
new Color(248, 215, 83),
new Color(92, 151, 70),
new Color(62, 117, 167),
new Color(122, 101, 62),
new Color(225, 102, 42),
new Color(116, 121, 111),
new Color(196, 56, 79)
};
}
}
|
package org.jpmml.xgboost;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteOrder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import org.dmg.pmml.FieldName;
import org.dmg.pmml.PMML;
import org.jpmml.model.MetroJAXBUtil;
public class Main {
@Parameter (
names = {"--fmap-input"},
description = "XGBoost feature map input file",
required = true
)
private File fmapInput = null;
@Parameter (
names = {"--help"},
description = "Show the list of configuration options and exit",
help = true
)
private boolean help = false;
@Parameter (
names = {"--model-input"},
description = "XGBoost model input file",
required = true
)
private File modelInput = null;
@Parameter (
names = {"--byte-order"},
description = "Endianness of XGBoost model input file. Possible values \"BIG_ENDIAN\" (\"BE\") or \"LITTLE_ENDIAN\" (\"LE\")"
)
private String byteOrder = (ByteOrder.nativeOrder()).toString();
@Parameter (
names = {"--charset"},
description = "Charset of XGBoost model input file"
)
private String charset = null;
@Parameter (
names = {"--missing-value"},
description = "String representation of feature value(s) that should be regarded as missing"
)
private String missingValue = null;
@Parameter (
names = {"--pmml-output"},
description = "PMML output file",
required = true
)
private File pmmlOutput = null;
@Parameter (
names = {"--target-name"},
description = "Target name. Defaults to \"_target\""
)
private String targetName = null;
@Parameter (
names = {"--target-categories"},
description = "Target categories. Defaults to 0-based index [0, 1, .., num_class - 1]"
)
private List<String> targetCategories = null;
@Parameter (
names = {"--ntree-limit"},
description = "Limit the number of trees. Defaults to all trees"
)
private Integer ntreeLimit = null;
@Parameter (
names = {"--compact"},
description = "Transform XGBoost-style trees to PMML-style trees",
arity = 1
)
private boolean compact = true;
static
public void main(String... args) throws Exception {
Main main = new Main();
JCommander commander = new JCommander(main);
commander.setProgramName(Main.class.getName());
try {
commander.parse(args);
} catch(ParameterException pe){
StringBuilder sb = new StringBuilder();
sb.append(pe.toString());
sb.append("\n");
commander.usage(sb);
System.err.println(sb.toString());
System.exit(-1);
}
if(main.help){
StringBuilder sb = new StringBuilder();
commander.usage(sb);
System.out.println(sb.toString());
System.exit(0);
}
main.run();
}
private void run() throws Exception {
Learner learner;
ByteOrder byteOrder = ByteOrderUtil.forValue(this.byteOrder);
try(InputStream is = new FileInputStream(this.modelInput)){
learner = XGBoostUtil.loadLearner(is, byteOrder, this.charset);
}
FeatureMap featureMap;
try(InputStream is = new FileInputStream(this.fmapInput)){
featureMap = XGBoostUtil.loadFeatureMap(is);
}
if(this.missingValue != null){
featureMap.addMissingValue(this.missingValue);
}
Map<String, Object> options = new LinkedHashMap<>();
options.put(HasXGBoostOptions.OPTION_COMPACT, this.compact);
options.put(HasXGBoostOptions.OPTION_NTREE_LIMIT, this.ntreeLimit);
PMML pmml = learner.encodePMML(this.targetName != null ? FieldName.create(this.targetName) : null, this.targetCategories, featureMap, options);
try(OutputStream os = new FileOutputStream(this.pmmlOutput)){
MetroJAXBUtil.marshalPMML(pmml, os);
}
}
}
|
package org.scm4j.vcs.api;
import org.scm4j.vcs.api.exceptions.EVCSBranchExists;
import org.scm4j.vcs.api.exceptions.EVCSFileNotFound;
import org.scm4j.vcs.api.exceptions.EVCSTagExists;
import org.scm4j.vcs.api.workingcopy.IVCSWorkspace;
import java.util.List;
import java.util.Set;
public interface IVCS {
void createBranch(String srcBranchName, String dstBranchName, String commitMessage) throws EVCSBranchExists;
VCSMergeResult merge(String srcBranchName, String dstBranchName, String commitMessage);
void deleteBranch(String branchName, String commitMessage);
void setCredentials(String user, String password);
void setProxy(String host, int port, String proxyUser, String proxyPassword);
String getRepoUrl();
String getFileContent(String branchName, String fileRelativePath, String encoding) throws EVCSFileNotFound;
String getFileContent(String branchName, String fileRelativePath) throws EVCSFileNotFound;
VCSCommit setFileContent(String branchName, String filePath, String content, String commitMessage);
List<VCSDiffEntry> getBranchesDiff(String srcBranchName, String destBranchName);
Set<String> getBranches();
List<VCSCommit> log(String branchName, int limit);
String getVCSTypeString();
VCSCommit removeFile(String branchName, String filePath, String commitMessage);
List<VCSCommit> getCommitsRange(String branchName, String firstCommitId, String untilCommitId);
List<VCSCommit> getCommitsRange(String branchName, String firstCommitId, WalkDirection direction, int limit);
IVCSWorkspace getWorkspace();
VCSCommit getHeadCommit(String branchName);
Boolean fileExists(String branchName, String filePath);
VCSTag createTag(String branchName, String tagName, String tagMessage) throws EVCSTagExists;
List<VCSTag> getTags();
VCSTag getLastTag();
void removeTag(String tagName);
void checkout(String branchName, String targetPath);
}
|
package quadcitydjs;
import java.lang.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Point;
/* I am thnking that this class will handle the GUI much like minesweeper. I also believe that we should use
the enable option should be used to distinguish between the two players. Maybe add a player_enable and AI_enable. I also think this class
should house the code for the AI as well. I am also kinda thinking about using the observable even though I really do not want to.*/
public class Battleship extends JPanel implements ActionListener {
private final ImageIcon CARRIER_ICON1 = new ImageIcon(getClass().getClassLoader().getResource("carrier1.png"));
private final ImageIcon CARRIER_ICON2 = new ImageIcon(getClass().getClassLoader().getResource("carrier2.png"));
private final ImageIcon CARRIER_ICON3 = new ImageIcon(getClass().getClassLoader().getResource("carrier3.png"));
private final ImageIcon CARRIER_ICON4 = new ImageIcon(getClass().getClassLoader().getResource("carrier4.png"));
private final ImageIcon CARRIER_ICON5 = new ImageIcon(getClass().getClassLoader().getResource("carrier5.png"));
private final ImageIcon BATTLESHIP_ICON1 = new ImageIcon(getClass().getClassLoader().getResource("battleship1.png"));
private final ImageIcon BATTLESHIP_ICON2 = new ImageIcon(getClass().getClassLoader().getResource("battleship2.png"));
private final ImageIcon BATTLESHIP_ICON3 = new ImageIcon(getClass().getClassLoader().getResource("battleship3.png"));
private final ImageIcon BATTLESHIP_ICON4 = new ImageIcon(getClass().getClassLoader().getResource("battleship4.png"));
private final ImageIcon CRUISER_ICON1 = new ImageIcon(getClass().getClassLoader().getResource("cruiser1.png"));
private final ImageIcon CRUISER_ICON2 = new ImageIcon(getClass().getClassLoader().getResource("cruiser2.png"));
private final ImageIcon CRUISER_ICON3 = new ImageIcon(getClass().getClassLoader().getResource("cruiser3.png"));
private final ImageIcon SUBMARINE_ICON1 = new ImageIcon(getClass().getClassLoader().getResource("submarine1.png"));
private final ImageIcon SUBMARINE_ICON2 = new ImageIcon(getClass().getClassLoader().getResource("submarine2.png"));
private final ImageIcon SUBMARINE_ICON3 = new ImageIcon(getClass().getClassLoader().getResource("submarine3.png"));
private final ImageIcon DESTROYER_ICON1 = new ImageIcon(getClass().getClassLoader().getResource("destroyer1.png"));
private final ImageIcon DESTROYER_ICON2 = new ImageIcon(getClass().getClassLoader().getResource("destroyer2.png"));
private Grid grid;
private Grid gridAI;
private JButton[][] AI_button;
private JButton[][] button;
private int shipCount;
private int ships;
private boolean player_enabled;
private boolean AI_enabled;
private JLabel shipLabel_1;
private JLabel shipLabel_2;
public Battleship() {
this(10,10);
}
public Battleship(int height, int width) {
player_enabled = true;
AI_enabled = false;
gridAI = new Grid(height, width, true);
JPanel gridAIPanel = new JPanel();
gridAIPanel.setLayout(new GridLayout(height, width));
AI_button = new JButton[height][width];
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
AI_button[i][j] = new JButton();
AI_button[i][j].setName("cell:" + i + ":" + j);
AI_button[i][j].setPreferredSize(new Dimension(50,50));
AI_button[i][j].setHorizontalAlignment(0);
AI_button[i][j].setBorder(BorderFactory.createRaisedBevelBorder());
add(AI_button[i][j]);
AI_button[i][j].addActionListener(this);
gridAIPanel.add(AI_button[i][j]);
}
}
grid = new Grid(height, width);
JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(height, width));
button = new JButton[height][width];
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
button[i][j] = new JButton();
button[i][j].setName("cell:" + i + ":" + j);
button[i][j].setPreferredSize(new Dimension(50,50));
button[i][j].setHorizontalAlignment(0);
button[i][j].setBorder(BorderFactory.createRaisedBevelBorder());
add(button[i][j]);
button[i][j].addActionListener(this);
gridPanel.add(button[i][j]);
}
}
setShipIcons();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1,5));
panel.add(new JLabel("Player 1: "));
ships = 5;
shipLabel_1 = new JLabel("" + ships);
panel.add(shipLabel_1);
shipLabel_1.setName("ships_1");
/* button = new JButton("Restart");
button.addActionListener(this);
panel.add(button);
*/
panel.add(new JLabel("Player 2: "));
shipLabel_2 = new JLabel();
panel.add(shipLabel_2);
shipLabel_2.setName("ships_2");
setLayout(new BorderLayout(3, 1));
add(gridAIPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
add(gridPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent event) {
if(player_enabled){
JButton button_temp = new JButton();
button_temp = (JButton)event.getSource();
Point p = findSourceIndex(event);
if(gridAI.isEmpty(p.x, p.y)) {
gridAI.isMiss(p.x, p.y);
AI_button[p.x][p.y].setEnabled(false);
player_enabled = false;
AI();
}
if(gridAI.isShip(p.x, p.y)) {
gridAI.isHit(p.x, p.y);
AI_button[p.x][p.y].setEnabled(false);
player_enabled = false;
AI();
}
}
}
private Point findSourceIndex(ActionEvent event) {
Point p = new Point();
Component c = (Component)event.getSource();
if(c.getName().startsWith("cell")){
String s = c.getName();
Scanner scanner = new Scanner(s);
scanner.useDelimiter(":");
scanner.next();
p.x = scanner.nextInt();
p.y = scanner.nextInt();
}
return p;
}
public void AI() {
Random random = new Random();
int x = random.nextInt(10);
int y = random.nextInt(10);
if(button[x][y].isEnabled()) {
if(grid.isEmpty(x, y)) {
grid.isMiss(x, y);
button[x][y].setEnabled(false);
player_enabled = true;
AI();
}
if(grid.isShip(x, y)) {
grid.isHit(x, y);
button[x][y].setEnabled(false);
player_enabled = true;
AI();
}
}
else{
AI();
}
}
public void setShipIcons(){
int shipIcon;
Ship[] ship = grid.getShipArray();
for(int i = 0; i < 5; i++){
for(int j = 0; j < ship[i].getHealth(); j++){
if(ship[i].getShipType() == Ship.ShipType.CARRIER){
shipIcon = 5;
Location[] loc = ship[i].getLocation();
Point p = grid.findLocation(loc[i]);
if(ship[i].getShipType().getVertical()){
}
else{
if(shipIcon == 5){
button[p.x][p. y].setIcon(CARRIER_ICON1);
shipIcon
}
else if(shipIcon == 4){
button[p.x][p.y].setIcon(CARRIER_ICON2);
shipIcon
}
else if(shipIcon == 3){
button[p.x][p.y].setIcon(CARRIER_ICON3);
shipIcon
}
else if(shipIcon == 2){
button[p.x][p.y].setIcon(CARRIER_ICON4);
shipIcon
}
else {
button[p.x][p.y].setIcon(CARRIER_ICON5);
}
}
}
if(ship[i].getShipType() == Ship.ShipType.BATTLESHIP){
shipIcon = 4;
Location[] loc = ship[i].getLocation();
Point p = grid.findLocation(loc[i]);
if(ship[i].getShipType().getVertical()){
}
else{
if(shipIcon == 4){
button[p.x][p. y].setIcon(BATTLESHIP_ICON1);
shipIcon
}
else if(shipIcon == 3){
button[p.x][p.y].setIcon(BATTLESHIP_ICON2);
shipIcon
}
else if(shipIcon == 2){
button[p.x][p.y].setIcon(BATTLESHIP_ICON3);
shipIcon
}
else {
button[p.x][p.y].setIcon(BATTLESHIP_ICON4);
}
}
}
if(ship[i].getShipType() == Ship.ShipType.CRUISER){
shipIcon = 3;
Location[] loc = ship[i].getLocation();
Point p = grid.findLocation(loc[i]);
if(ship[i].getShipType().getVertical()){
}
else{
if(shipIcon == 3){
button[p.x][p. y].setIcon(CRUISER_ICON1);
shipIcon
}
else if(shipIcon == 2){
button[p.x][p.y].setIcon(CRUISER_ICON2);
shipIcon
}
else {
button[p.x][p.y].setIcon(CRUISER_ICON3);
}
}
}
if(ship[i].getShipType() == Ship.ShipType.SUBMARINE){
shipIcon = 3;
Location[] loc = ship[i].getLocation();
Point p = grid.findLocation(loc[i]);
if(ship[i].getShipType().getVertical()){
}
else {
if(shipIcon == 3){
button[p.x][p. y].setIcon(SUBMARINE_ICON1);
shipIcon
}
else if(shipIcon == 2){
button[p.x][p.y].setIcon(SUBMARINE_ICON2);
shipIcon
}
else {
button[p.x][p.y].setIcon(SUBMARINE_ICON3);
}
}
}
if(ship[i].getShipType() == Ship.ShipType.DESTROYER){
shipIcon = 3;
Location[] loc = ship[i].getLocation();
Point p = grid.findLocation(loc[i]);
if(ship[i].getShipType().getVertical()){
}
else{
if(shipIcon == 2){
button[p.x][p. y].setIcon(DESTROYER_ICON1);
shipIcon
}
else {
button[p.x][p.y].setIcon(DESTROYER_ICON2);
}
}
}
}
}
}
// add ships, add icons to when ships are shot and shit, change icons of places that have ships, finish AI, set icons for player ships on ther side so they can know what the fuck is going on
}
|
package utility;
import java.util.ArrayList;
/**
* A CommandHistory objects holds a history of previously-issued commands for
* a piece of data such that they can be undone/redone.
*
* @see utility.Command
*/
public class CommandHistory {
private final int NULL_INDEX = -1;
private ArrayList<Command> commands;
private int currCommandIdx;
/**
* Initialize the command history as empty
*/
public CommandHistory() {
commands = new ArrayList<Command>();
currCommandIdx = NULL_INDEX;
}
/**
* Delete the history of commands from the current command to the end, but
* not deleting the current command itself
*/
private void deleteHistoryToEndFromCurrent() {
int numCommands = commands.size();
for (int i = currCommandIdx; i < numCommands; i++) {
commands.remove(i);
}
}
/**
* Perform a command, adding it to the command history
* @param cmd The command to perform
*/
public void performCommand(Command cmd) {
int numCmds = commands.size();
boolean commandHistoryIsEmpty = (numCmds == 0);
boolean currCommandIsMostRecent = (numCmds == currCommandIdx - 1);
if (commandHistoryIsEmpty) {
cmd.perform();
commands.add(cmd);
currCommandIdx = 0;
} else if (currCommandIsMostRecent) {
cmd.perform();
commands.add(cmd);
currCommandIdx = commands.indexOf(cmd);
} else {
deleteHistoryToEndFromCurrent();
assert(commands.size() == currCommandIdx + 1);
cmd.perform();
commands.add(cmd);
currCommandIdx++;
}
}
/**
* Undo the most recently performed command
*/
public void undo() {
if (canUndo()) {
Command cmd = commands.get(currCommandIdx);
cmd.undo();
currCommandIdx
}
}
/**
* Redo the most recently undone command
*/
public void redo() {
if (canRedo()) {
currCommandIdx++;
Command cmd = commands.get(currCommandIdx);
cmd.perform();
}
}
/**
* Determine if there is a command to undo
* @return true if there is a command to undo, false if not
*/
public boolean canUndo() {
return (currCommandIdx >= 0);
}
/**
* Determine if there is a command to redo
* @return true if there is a command to redo, false if not
*/
public boolean canRedo() {
return (currCommandIdx < commands.size() - 1);
}
}
|
package mondrian.rolap.sql;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import mondrian.olap.MondrianDef;
import mondrian.olap.MondrianProperties;
import mondrian.olap.Util;
import org.eigenbase.util.property.Property;
import org.eigenbase.util.property.Trigger;
/**
* <code>SqlQuery</code> allows us to build a <code>select</code>
* statement and generate it in database-specific SQL syntax.
*
* <p> Notable differences in database syntax are:<dl>
*
* <dt> Identifier quoting </dt>
* <dd> Oracle (and all JDBC-compliant drivers) uses double-quotes,
* for example <code>select * from "emp"</code>. Access prefers brackets,
* for example <code>select * from [emp]</code>. mySQL allows single- and
* double-quotes for string literals, and therefore does not allow
* identifiers to be quoted, for example <code>select 'foo', "bar" from
* emp</code>. </dd>
*
* <dt> AS in from clause </dt>
* <dd> Oracle doesn't like AS in the from * clause, for example
* <code>select from emp as e</code> vs. <code>select * from emp
* e</code>. </dd>
*
* <dt> Column aliases </dt>
* <dd> Some databases require that every column in the select list
* has a valid alias. If the expression is an expression containing
* non-alphanumeric characters, an explicit alias is needed. For example,
* Oracle will barfs at <code>select empno + 1 from emp</code>. </dd>
*
* <dt> Parentheses around table names </dt>
* <dd> Oracle doesn't like <code>select * from (emp)</code> </dd>
*
* <dt> Queries in FROM clause </dt>
* <dd> PostgreSQL and hsqldb don't allow, for example, <code>select * from
* (select * from emp) as e</code>.</dd>
*
* <dt> Uniqueness of index names </dt>
* <dd> In PostgreSQL and Oracle, index names must be unique within the
* database; in Access and hsqldb, they must merely be unique within their
* table </dd>
*
* <dt> Datatypes </dt>
* <dd> In Oracle, BIT is CHAR(1), TIMESTAMP is DATE.
* In PostgreSQL, DOUBLE is DOUBLE PRECISION, BIT is BOOL. </dd>
* </ul>
*
* <p>
* NOTE: Instances of this class are NOT thread safe so the user must make
* sure this is accessed by only one thread at a time.
*
* @author jhyde
* @version $Id$
*/
public class SqlQuery
{
/** This static variable controls the formatting of the sql string. */
private static boolean generateFormattedSql =
MondrianProperties.instance().GenerateFormattedSql.get();
static {
// Trigger is used to lookup and change the value of the
// variable that controls formatting.
// Using a trigger means we don't have to look up the property eveytime.
MondrianProperties.instance().GenerateFormattedSql.addTrigger(
new Trigger() {
public boolean isPersistent() {
return true;
}
public int phase() {
return Trigger.PRIMARY_PHASE;
}
public void execute(Property property, String value) {
generateFormattedSql = property.booleanValue();
}
}
);
}
private boolean distinct;
private final ClauseList select;
private final ClauseList from;
private final ClauseList where;
private final ClauseList groupBy;
private final ClauseList having;
private final ClauseList orderBy;
/**
* This list is used to keep track of what aliases have been used in the
* FROM clause. One might think that a java.util.Set would be a more
* appropriate Collection type, but if you only have a couple of "from
* aliases", then iterating over a list is faster than doing a hash lookup
* (as is used in java.util.HashSet).
*/
private final List<String> fromAliases;
/** The SQL dialect this query is to be generated in. */
private final Dialect dialect;
/** Scratch buffer. Clear it before use. */
private final StringBuilder buf;
/**
* Base constructor used by all other constructors to create an empty
* instance.
*/
public SqlQuery(Dialect dialect) {
// both select and from allow duplications
this.select = new ClauseList(true);
this.from = new ClauseList(true);
this.where = new ClauseList(false);
this.groupBy = new ClauseList(false);
this.having = new ClauseList(false);
this.orderBy = new ClauseList(false);
this.fromAliases = new ArrayList<String>();
this.buf = new StringBuilder(128);
this.dialect = dialect;
}
/**
* Creates a <code>SqlQuery</code>
*
* @param databaseMetaData used to determine which dialect of
* SQL to generate. Must not be held beyond the constructor.
*/
public SqlQuery(final DatabaseMetaData databaseMetaData) {
this(Dialect.create(databaseMetaData));
}
/**
* Creates an empty <code>SqlQuery</code> with the same environment as this
* one. (As per the Gang of Four 'prototype' pattern.)
*/
public SqlQuery cloneEmpty()
{
return new SqlQuery(dialect);
}
public void setDistinct(final boolean distinct) {
this.distinct = distinct;
}
/**
* The size required to add quotes around a string - this ought to be
* large enough to prevent a reallocation.
*/
private static final int SINGLE_QUOTE_SIZE = 10;
/**
* Two strings are quoted and the character '.' is placed between them.
*/
private static final int DOUBLE_QUOTE_SIZE = 2 * SINGLE_QUOTE_SIZE + 1;
/**
* Adds a subquery to the FROM clause of this Query with a given alias.
* If the query already exists it either, depending on
* <code>failIfExists</code>, throws an exception or does not add the query
* and returns false.
*
* @param query
* @param alias (if not null, must not be zero length).
* @param failIfExists if true, throws exception if alias already exists
* @return true if query *was* added
*
* @pre alias != null
*/
public boolean addFromQuery(final String query,
final String alias,
final boolean failIfExists) {
Util.assertPrecondition(alias != null);
if (fromAliases.contains(alias)) {
if (failIfExists) {
throw Util.newInternal(
"query already contains alias '" + alias + "'");
} else {
return false;
}
}
buf.setLength(0);
buf.append('(');
buf.append(query);
buf.append(')');
if (alias != null) {
Util.assertTrue(alias.length() > 0);
if (dialect.allowsAs()) {
buf.append(" as ");
} else {
buf.append(' ');
}
dialect.quoteIdentifier(alias, buf);
fromAliases.add(alias);
}
from.add(buf.toString());
return true;
}
/**
* Adds <code>[schema.]table AS alias</code> to the FROM clause.
*
* @param schema schema name; may be null
* @param table table name
* @param alias table alias, may not be null
* (if not null, must not be zero length).
* @param failIfExists
*
* @pre alias != null
* @return true if table *was* added
*/
private boolean addFromTable(final String schema,
final String table,
final String alias,
final String filter,
final boolean failIfExists) {
if (fromAliases.contains(alias)) {
if (failIfExists) {
throw Util.newInternal(
"query already contains alias '" + alias + "'");
} else {
return false;
}
}
buf.setLength(0);
dialect.quoteIdentifier(schema, table, buf);
if (alias != null) {
Util.assertTrue(alias.length() > 0);
if (dialect.allowsAs()) {
buf.append(" as ");
} else {
buf.append(' ');
}
dialect.quoteIdentifier(alias, buf);
fromAliases.add(alias);
}
from.add(buf.toString());
if (filter != null) {
// append filter condition to where clause
addWhere("(", filter, ")");
}
return true;
}
public void addFrom(final SqlQuery sqlQuery,
final String alias,
final boolean failIfExists)
{
addFromQuery(sqlQuery.toString(), alias, failIfExists);
}
/**
* Adds a relation to a query, adding appropriate join conditions, unless
* it is already present.
*
* <p>Returns whether the relation was added to the query.
*
* @param relation Relation to add
* @param alias Alias of relation. If null, uses relation's alias.
* @param failIfExists Whether to fail if relation is already present
* @return true, if relation *was* added to query
*/
public boolean addFrom(final MondrianDef.Relation relation,
final String alias,
final boolean failIfExists)
{
if (relation instanceof MondrianDef.View) {
final MondrianDef.View view = (MondrianDef.View) relation;
final String viewAlias = (alias == null)
? view.getAlias()
: alias;
final String sqlString = dialect.chooseQuery(view.selects);
return addFromQuery(sqlString, viewAlias, false);
} else if (relation instanceof MondrianDef.Table) {
final MondrianDef.Table table = (MondrianDef.Table) relation;
final String tableAlias = (alias == null)
? table.getAlias()
: alias;
return addFromTable(table.schema, table.name, tableAlias,
table.getFilter(), failIfExists);
} else if (relation instanceof MondrianDef.Join) {
final MondrianDef.Join join = (MondrianDef.Join) relation;
final String leftAlias = join.getLeftAlias();
final String rightAlias = join.getRightAlias();
boolean addLeft = addFrom(join.left, leftAlias, failIfExists);
boolean addRight = addFrom(join.right, rightAlias, failIfExists);
boolean added = addLeft || addRight;
if (added) {
buf.setLength(0);
dialect.quoteIdentifier(leftAlias, join.leftKey, buf);
buf.append(" = ");
dialect.quoteIdentifier(rightAlias, join.rightKey, buf);
addWhere(buf.toString());
}
return added;
} else {
throw Util.newInternal("bad relation type " + relation);
}
}
/**
* Adds an expression to the select clause, automatically creating a
* column alias.
*/
public void addSelect(final String expression) {
// Some DB2 versions (AS/400) throw an error if a column alias is
// *not* used in a subsequent order by (Group by).
// Derby fails on 'SELECT... HAVING' if column has alias.
if (dialect.isAS400() || dialect.isDerby()) {
addSelect(expression, null);
} else {
addSelect(expression, nextColumnAlias());
}
}
public String nextColumnAlias() {
return "c" + select.size();
}
/** Adds an expression to the select clause, with a specified column
* alias. */
public void addSelect(final String expression, final String alias) {
buf.setLength(0);
buf.append(expression);
if (alias != null) {
buf.append(" as ");
dialect.quoteIdentifier(alias, buf);
}
select.add(buf.toString());
}
public void addWhere(
final String exprLeft,
final String exprMid,
final String exprRight)
{
int len = exprLeft.length() + exprMid.length() + exprRight.length();
StringBuilder buf = new StringBuilder(len);
buf.append(exprLeft);
buf.append(exprMid);
buf.append(exprRight);
addWhere(buf.toString());
}
public void addWhere(final String expression)
{
where.add(expression);
}
public void addGroupBy(final String expression)
{
groupBy.add(expression);
}
public void addHaving(final String expression)
{
having.add(expression);
}
/**
* Adds an item to the ORDER BY clause.
*
* @param expr the expr to order by
* @param ascending sort direction
* @param prepend whether to prepend to the current list of items
* @param nullable whether the expression might be null
*/
public void addOrderBy(
String expr,
boolean ascending,
boolean prepend,
boolean nullable)
{
if (nullable && !dialect.isNullsCollateLast()) {
expr = dialect.forceNullsCollateLast(expr);
}
if (ascending) {
expr = expr + " ASC";
} else {
expr = expr + " DESC";
}
if (prepend) {
orderBy.add(0, expr);
} else {
orderBy.add(expr);
}
}
public String toString()
{
if (generateFormattedSql) {
StringWriter sw = new StringWriter(256);
PrintWriter pw = new PrintWriter(sw);
print(pw, "");
pw.flush();
return sw.toString();
} else {
buf.setLength(0);
select.toBuffer(buf,
distinct ? "select distinct " : "select ", ", ");
from.toBuffer(buf, " from ", ", ");
where.toBuffer(buf, " where ", " and ");
groupBy.toBuffer(buf, " group by ", ", ");
having.toBuffer(buf, " having ", " and ");
orderBy.toBuffer(buf, " order by ", ", ");
return buf.toString();
}
}
public void print(PrintWriter pw, String prefix) {
// This <CR> is added to the front because the part of the code
// that prints out the sql (if the trace level is non-zero),
// RolapUtil, does not print the sql at the start of a new line.
pw.println();
select.print(pw, prefix,
distinct ? "select distinct " : "select ", ", ");
from.print(pw, prefix, "from ", ", ");
where.print(pw, prefix, "where ", " and ");
groupBy.print(pw, prefix, "group by ", ", ");
having.print(pw, prefix, "having ", " and ");
orderBy.print(pw, prefix, "order by ", ", ");
}
public Dialect getDialect() {
return dialect;
}
private class ClauseList extends ArrayList<String> {
private final boolean allowDups;
ClauseList(final boolean allowDups) {
this.allowDups = allowDups;
}
/**
* Parameter element is added if either duplicates are allowed or if
* it has not already been added.
*
* @param element
*/
public boolean add(final String element) {
if (allowDups || !contains(element)) {
return super.add(element);
}
return false;
}
void toBuffer(final StringBuilder buf,
final String first,
final String sep) {
Iterator it = iterator();
boolean firstTime = true;
while (it.hasNext()) {
String s = (String) it.next();
if (firstTime) {
buf.append(first);
firstTime = false;
} else {
buf.append(sep);
}
buf.append(s);
}
}
void print(final PrintWriter pw,
final String prefix,
final String first,
final String sep) {
String subprefix = prefix + " ";
boolean firstTime = true;
for (Iterator it = iterator(); it.hasNext(); ) {
String s = (String) it.next();
if (firstTime) {
pw.print(prefix);
pw.print(first);
firstTime = false;
} else {
pw.print(sep);
}
pw.println();
pw.print(subprefix);
pw.print(s);
}
if (! firstTime) {
pw.println();
}
}
}
/**
* Description of a SQL dialect. It is immutable.
*/
public static class Dialect {
private final String quoteIdentifierString;
private final String productName;
private final String productVersion;
Dialect(
String quoteIdentifierString,
String productName,
String productVersion) {
this.quoteIdentifierString = quoteIdentifierString;
this.productName = productName;
this.productVersion = productVersion;
}
/**
* Creates a {@link SqlQuery.Dialect} from a {@link DatabaseMetaData}.
*/
public static Dialect create(final DatabaseMetaData databaseMetaData) {
String productName;
try {
productName = databaseMetaData.getDatabaseProductName();
} catch (SQLException e1) {
throw Util.newInternal(e1, "while detecting database product");
}
String quoteIdentifierString;
try {
quoteIdentifierString =
databaseMetaData.getIdentifierQuoteString();
} catch (SQLException e) {
throw Util.newInternal(e, "while quoting identifier");
}
if ((quoteIdentifierString == null) ||
(quoteIdentifierString.trim().length() == 0)) {
if (productName.toUpperCase().equals("MYSQL")) {
// mm.mysql.2.0.4 driver lies. We know better.
quoteIdentifierString = "`";
} else {
// Quoting not supported
quoteIdentifierString = null;
}
}
String productVersion;
try {
productVersion = databaseMetaData.getDatabaseProductVersion();
} catch (SQLException e11) {
throw Util.newInternal(e11,
"while detecting database product version");
}
return new Dialect(
quoteIdentifierString,
productName,
productVersion);
}
// -- detect various databases --
public boolean isAccess() {
return productName.equals("ACCESS");
}
public boolean isDerby() {
return productName.trim().toUpperCase().equals("APACHE DERBY");
}
public boolean isCloudscape() {
return productName.trim().toUpperCase().equals("DBMS:CLOUDSCAPE");
}
public boolean isDB2() {
// DB2 on NT returns "DB2/NT"
return productName.startsWith("DB2");
}
public boolean isAS400() {
// DB2/AS400 Product String = "DB2 UDB for AS/400"
return productName.startsWith("DB2 UDB for AS/400");
}
public boolean isOldAS400() {
if (!isAS400()) {
return false;
}
// TB "04.03.0000 V4R3m0"
// this version cannot handle subqueries and is considered "old"
// DEUKA "05.01.0000 V5R1m0" is ok
String[] version_release = productVersion.split("\\.", 3);
/*
if ( version_release.length > 2 &&
"04".compareTo(version_release[0]) > 0 ||
("04".compareTo(version_release[0]) == 0
&& "03".compareTo(version_release[1]) >= 0) )
return true;
*/
// assume, that version <= 04 is "old"
return ("04".compareTo(version_release[0]) >= 0);
}
// Note: its not clear that caching the best name would actually save
// very much time, so we do not do so.
private String getBestName() {
String best;
if (isOracle()) {
best = "oracle";
} else if (isMSSQL()) {
best = "mssql";
} else if (isMySQL()) {
best = "mysql";
} else if (isAccess()) {
best = "access";
} else if (isPostgres()) {
best = "postgres";
} else if (isSybase()) {
best = "sybase";
} else if (isCloudscape() || isDerby()) {
best = "derby";
} else if (isDB2()) {
best = "db2";
} else if (isFirebird()) {
best = "firebird";
} else if (isInterbase()) {
best = "interbase";
} else if (isIngres()) {
best = "ingres";
} else if (isLucidDB()) {
best = "luciddb";
} else if (isTeradata()) {
best = "teradata";
} else {
best = "generic";
}
return best;
}
/**
* @return SQL syntax that converts <code>expr</code>
* into upper case.
*/
public String toUpper(String expr) {
if (isDB2() || isAccess())
return "UCASE(" + expr + ")";
return "UPPER(" + expr + ")";
}
public String caseWhenElse(String cond, String thenExpr, String elseExpr) {
if (isAccess()) {
return "IIF(" + cond + "," + thenExpr + "," + elseExpr + ")";
}
return "CASE WHEN " + cond + " THEN " + thenExpr + " ELSE " + elseExpr + " END";
}
/**
* Encloses an identifier in quotation marks appropriate for the
* current SQL dialect. For example,
* <code>quoteIdentifier("emp")</code> yields a string containing
* <code>"emp"</code> in Oracle, and a string containing
* <code>[emp]</code> in Access.
*/
public String quoteIdentifier(final String val) {
int size = val.length() + SINGLE_QUOTE_SIZE;
StringBuilder buf = new StringBuilder(size);
quoteIdentifier(val, buf);
return buf.toString();
}
/**
* Appends to a buffer an identifier, quoted appropriately for this
* Dialect.
*
* @param val identifier to quote (must not be null).
* @param buf Buffer
*/
public void quoteIdentifier(final String val, final StringBuilder buf) {
String q = getQuoteIdentifierString();
if (q == null) {
// quoting is not supported
buf.append(val);
return;
}
// if the value is already quoted, do nothing
// if not, then check for a dot qualified expression
// like "owner.table".
// In that case, prefix the single parts separately.
if (val.startsWith(q) && val.endsWith(q)) {
// already quoted - nothing to do
buf.append(val);
return;
}
int k = val.indexOf('.');
if (k > 0) {
// qualified
String val1 = Util.replace(val.substring(0,k), q, q + q);
String val2 = Util.replace(val.substring(k+1), q, q + q);
buf.append(q);
buf.append(val1);
buf.append(q);
buf.append(".");
buf.append(q);
buf.append(val2);
buf.append(q);
} else {
// not Qualified
String val2 = Util.replace(val, q, q + q);
buf.append(q);
buf.append(val2);
buf.append(q);
}
}
/**
* Encloses an identifier in quotation marks appropriate for the
* current SQL dialect. For example, in Oracle, where the identifiers
* are quoted using double-quotes,
* <code>quoteIdentifier("schema","table")</code> yields a string
* containing <code>"schema"."table"</code>.
*
* @param qual Qualifier. If it is not null,
* <code>"<em>qual</em>".</code> is prepended.
* @param name Name to be quoted.
*/
public String quoteIdentifier(final String qual, final String name) {
// We know if the qalifier is null, then only the name is going
// to be quoted.
int size = name.length()
+ ((qual == null)
? SINGLE_QUOTE_SIZE
: (qual.length() + DOUBLE_QUOTE_SIZE));
StringBuilder buf = new StringBuilder(size);
quoteIdentifier(qual, name, buf);
return buf.toString();
}
/**
* Appends to a buffer an identifier and optional qualifier, quoted
* appropriately for this Dialect.
*
* @param qual optional qualifier to be quoted.
* @param name name to be quoted (must not be null).
* @param buf Buffer
*/
public void quoteIdentifier(
final String qual,
final String name,
final StringBuilder buf)
{
if (qual == null) {
quoteIdentifier(name, buf);
} else {
Util.assertTrue(
(qual.length() != 0),
"qual should probably be null, not empty");
quoteIdentifier(qual, buf);
buf.append('.');
quoteIdentifier(name, buf);
}
}
/**
* Returns the character which is used to quote identifiers, or null
* if quoting is not supported.
*/
public String getQuoteIdentifierString() {
if (isDB2()) {
return "";
} else {
return quoteIdentifierString;
}
}
/**
* Appends to a buffer a single-quoted SQL string.
*
* <p>For example, in the default dialect,
* <code>quoteStringLiteral(buf, "Can't")</code> appends
* "<code>'Can''t'</code>" to <code>buf</code>.
*/
public void quoteStringLiteral(StringBuilder buf, String s) {
Util.singleQuoteString(s, buf);
}
/**
* Appends to a buffer a numeric literal.
*
* <p>In the default dialect, numeric literals are printed as is.
*/
public void quoteNumericLiteral(StringBuilder buf, String value) {
buf.append(value);
}
/**
* Appends to a buffer a boolean literal.
*
* <p>In the default dialect, boolean literals are printed as is.
*/
public void quoteBooleanLiteral(StringBuilder buf, String value) {
buf.append(value);
}
/**
* Appends to a buffer a date literal.
*
* <p>For example, in the default dialect,
* <code>quoteStringLiteral(buf, "1969-03-17")</code>
* appends <code>DATE '1969-03-17'</code>.
*/
public void quoteDateLiteral(StringBuilder buf, String value) {
buf.append("DATE ");
Util.singleQuoteString(value, buf);
}
/**
* Appends to a buffer a time literal.
*
* <p>For example, in the default dialect,
* <code>quoteStringLiteral(buf, "12:34:56")</code>
* appends <code>TIME '12:34:56'</code>.
*/
public void quoteTimeLiteral(StringBuilder buf, String value) {
buf.append("TIME ");
Util.singleQuoteString(value, buf);
}
/**
* Appends to a buffer a timestamp literal.
*
* <p>For example, in the default dialect,
* <code>quoteStringLiteral(buf, "1969-03-17 12:34:56")</code>
* appends <code>TIMESTAMP '1969-03-17 12:34:56'</code>.
*/
public void quoteTimestampLiteral(StringBuilder buf, String value) {
buf.append("TIMESTAMP ");
Util.singleQuoteString(value, buf);
}
/**
* Returns whether the underlying database is Firebird.
*/
public boolean isFirebird() {
return productName.toUpperCase().indexOf("FIREBIRD") >= 0;
}
/**
* Returns whether the underlying database is Informix.
*/
public boolean isInformix() {
return productName.startsWith("Informix");
}
/**
* Returns whether the underlying database is Ingres.
*/
public boolean isIngres() {
return productName.toUpperCase().equals("INGRES");
}
/**
* Returns whether the underlying database is Interbase.
*/
public boolean isInterbase() {
return productName.equals("Interbase");
}
/**
* Returns whether the underlying database is LucidDB.
*/
public boolean isLucidDB() {
return productName.toUpperCase().equals("LUCIDDB");
}
/**
* Returns whether the underlying database is Microsoft SQL Server.
*/
public boolean isMSSQL() {
return productName.toUpperCase().indexOf("SQL SERVER") >= 0;
}
/**
* Returns whether the underlying database is Oracle.
*/
public boolean isOracle() {
return productName.equals("Oracle");
}
/**
* Returns whether the underlying database is Postgres.
*/
public boolean isPostgres() {
return productName.toUpperCase().indexOf("POSTGRE") >= 0;
}
/**
* Returns whether the underlying database is MySQL.
*/
public boolean isMySQL() {
return productName.toUpperCase().equals("MYSQL");
}
/**
* Returns whether the underlying database is Sybase.
*/
public boolean isSybase() {
return productName.toUpperCase().indexOf("SYBASE") >= 0;
}
/**
* Returns whether the underlying database is Teradata.
*/
public boolean isTeradata() {
return productName.toUpperCase().indexOf("SYBASE") >= 0;
}
// -- behaviors --
protected boolean requiresAliasForFromItems() {
return isPostgres();
}
/**
* Returns whether the SQL dialect allows "AS" in the FROM clause.
* If so, "SELECT * FROM t AS alias" is a valid query.
*/
protected boolean allowsAs() {
return !isOracle() && !isSybase() && !isFirebird() &&
!isInterbase();
}
/**
* Whether "select * from (select * from t)" is OK.
*/
public boolean allowsFromQuery() {
// older versions of AS400 do not allow FROM subqueries
return !isMySQL() && !isOldAS400() && !isInformix() &&
!isSybase() && !isInterbase();
}
/**
* Whether "select count(distinct x, y) from t" is OK.
*/
public boolean allowsCompoundCountDistinct() {
return isMySQL();
}
/**
* Whether "select count(distinct x) from t" is OK.
*/
public boolean allowsCountDistinct() {
return !isAccess();
}
/**
* Chooses the variant within an array of
* {@link mondrian.olap.MondrianDef.SQL} which best matches the current
* SQL dialect.
*/
public String chooseQuery(final MondrianDef.SQL[] sqls) {
String best = getBestName();
String generic = null;
for (MondrianDef.SQL sql : sqls) {
if (sql.dialect.equals(best)) {
return sql.cdata;
}
if (sql.dialect.equals("generic")) {
generic = sql.cdata;
}
}
if (generic == null) {
throw Util.newError("View has no 'generic' variant");
}
return generic;
}
/**
* Generates a SQL statement to represent an inline dataset.
*
* <p>For example, for Oracle, generates
*
* <pre>
* SELECT 1 AS FOO, 'a' AS BAR FROM dual
* UNION ALL
* SELECT 2 AS FOO, 'b' AS BAR FROM dual
* </pre>
*
* <p>For ANSI SQL, generates:
*
* <pre>
* VALUES (1, 'a'), (2, 'b')
* </pre>
*
* @param columnNames List of column names
* @param columnTypes List of column types ("String" or "Numeric")
* @param valueList List of rows values
* @return SQL string
*/
public String generateInline(
List<String> columnNames,
List<String> columnTypes,
List<String[]> valueList) {
if (isOracle()) {
return generateInlineGeneric(
columnNames, columnTypes, valueList,
"from dual");
} else if (isAccess()) {
// Fall back to using the FoodMart 'days' table, because
// Access SQL has no way to generate values not from a table.
return generateInlineGeneric(
columnNames, columnTypes, valueList,
"from [days] where [day] = 1");
} else if (isMySQL()) {
return generateInlineGeneric(
columnNames, columnTypes, valueList, null);
} else if (isLucidDB()) {
// TODO jvs 26-Nov-2006: Eliminate this once LucidDB
// can support applying column names to a VALUES clause
// (needed by generateInlineForAnsi).
return generateInlineGeneric(
columnNames, columnTypes, valueList,
" from (values(0))");
} else {
return generateInlineForAnsi("t", columnNames, columnTypes, valueList);
}
}
/**
* Generic algorithm to generate inline values list,
* using an optional FROM clause, specified by the caller of this
* method, appropriate to the dialect of SQL.
*/
private String generateInlineGeneric(
List<String> columnNames,
List<String> columnTypes,
List<String[]> valueList,
String fromClause) {
final StringBuilder buf = new StringBuilder();
for (int i = 0; i < valueList.size(); i++) {
if (i > 0) {
buf.append(" union all ");
}
String[] values = valueList.get(i);
buf.append("select ");
for (int j = 0; j < values.length; j++) {
String value = values[j];
if (j > 0) {
buf.append(", ");
}
final String columnType = columnTypes.get(j);
final String columnName = columnNames.get(j);
Datatype datatype = Datatype.valueOf(columnType);
quote(buf, value, datatype);
if (allowsAs()) {
buf.append(" as ");
} else {
buf.append(' ');
}
quoteIdentifier(columnName, buf);
}
if (fromClause != null) {
buf.append(fromClause);
}
}
return buf.toString();
}
/**
* Generates inline values list using ANSI 'VALUES' syntax.
* For example,
*
* <blockquote><code>SELECT * FROM
* (VALUES (1, 'a'), (2, 'b')) AS t(x, y)</code></blockquote>
*
* <p>If NULL values are present, we use a CAST to ensure that they
* have the same type as other columns:
*
* <blockquote><code>SELECT * FROM
* (VALUES (1, 'a'), (2, CASE(NULL AS VARCHAR(1)))) AS t(x, y)
* </code></blockquote>
*
* <p>This syntax is known to work on Derby, but not Oracle 10 or
* Access.
*/
private String generateInlineForAnsi(
String alias,
List<String> columnNames,
List<String> columnTypes,
List<String[]> valueList) {
final StringBuilder buf = new StringBuilder();
buf.append("SELECT * FROM (VALUES ");
// Derby pads out strings to a common length, so we cast the
// string values to avoid this. Determine the cast type for each
// column.
String[] castTypes = null;
if (isDerby()) {
castTypes = new String[columnNames.size()];
for (int i = 0; i < columnNames.size(); i++) {
String columnType = columnTypes.get(i);
if (columnType.equals("String")) {
castTypes[i] =
guessSqlType(columnType, valueList, i);
}
}
}
for (int i = 0; i < valueList.size(); i++) {
if (i > 0) {
buf.append(", ");
}
String[] values = valueList.get(i);
buf.append("(");
for (int j = 0; j < values.length; j++) {
String value = values[j];
if (j > 0) {
buf.append(", ");
}
final String columnType = columnTypes.get(j);
Datatype datatype = Datatype.valueOf(columnType);
if (value == null) {
String sqlType =
guessSqlType(columnType, valueList, j);
buf.append("CAST(NULL AS ")
.append(sqlType)
.append(")");
} else if (isDerby() && castTypes[j] != null) {
buf.append("CAST(");
quote(buf, value, datatype);
buf.append(" AS ")
.append(castTypes[j])
.append(")");
} else {
quote(buf, value, datatype);
}
}
buf.append(")");
}
buf.append(") AS ");
quoteIdentifier(alias, buf);
buf.append(" (");
for (int j = 0; j < columnNames.size(); j++) {
final String columnName = columnNames.get(j);
if (j > 0) {
buf.append(", ");
}
quoteIdentifier(columnName, buf);
}
buf.append(")");
return buf.toString();
}
/**
* Appends to a buffer a value quoted for its type.
*/
public void quote(StringBuilder buf, Object value, Datatype datatype) {
if (value == null) {
buf.append("null");
} else {
datatype.quoteValue(buf, this, value.toString());
}
}
/**
* Guesses the type of a column based upon (a) its basic type,
* (b) a list of values.
*/
private static String guessSqlType(
String basicType, List<String[]> valueList, int column) {
if (basicType.equals("String")) {
int maxLen = 1;
for (String[] values : valueList) {
final String value = values[column];
if (value == null) {
continue;
}
maxLen = Math.max(maxLen, value.length());
}
return "VARCHAR(" + maxLen + ")";
} else {
return "INTEGER";
}
}
/**
* Returns whether this dialect supports common SQL Data Definition
* Language (DDL) statements such as <code>CREATE TABLE</code> and
* <code>DROP INDEX</code>.
*/
public boolean allowsDdl() {
return !isAccess();
}
/**
* Returns whether NULL values appear last when sorted using ORDER BY.
* According to the SQL standard, this is implementation-specific.
*/
public boolean isNullsCollateLast() {
if (isMySQL()) {
return false;
}
return true;
}
/**
* Modifies an expression in the ORDER BY clause to ensure that NULL
* values collate after all non-NULL values.
* If {@link #isNullsCollateLast()} is true, there's nothing to do.
*/
public String forceNullsCollateLast(String expr) {
// If we need to support other DBMSes, note that the SQL standard
// provides the syntax 'ORDER BY x ASC NULLS LAST'.
if (isMySQL()) {
String addIsNull = "ISNULL(" + expr + "), ";
expr = addIsNull + expr;
}
return expr;
}
/**
* Returns whether this Dialect supports expressions in the GROUP BY
* clause. Derby/Cloudscape do not.
*
* @return Whether this Dialect allows expressions in the GROUP BY
* clause
*/
public boolean supportsGroupByExpressions() {
return !(isDerby() || isCloudscape());
}
public boolean requiresOrderByAlias() {
return isMySQL() || isDB2() || isIngres();
}
/**
* Returns true if this dialect supports multi-value IN expressions.
* E.g.,
*
* <code>WHERE (col1, col2) IN ((val1a, val2a), (val1b, val2b))</code>
*
* @return true if the dialect supports multi-value IN expressions
*/
public boolean supportsMultiValueInExpr() {
return isLucidDB() || isMySQL();
}
}
/**
* Datatype of a column.
*/
public enum Datatype {
String {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteStringLiteral(buf, value);
}
},
Numeric {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteNumericLiteral(buf, value);
}
public boolean isNumeric() {
return true;
}
},
Integer {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteNumericLiteral(buf, value);
}
public boolean isNumeric() {
return true;
}
},
Boolean {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteBooleanLiteral(buf, value);
}
},
Date {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteDateLiteral(buf, value);
}
},
Time {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteTimeLiteral(buf, value);
}
},
Timestamp {
public void quoteValue(StringBuilder buf, Dialect dialect, String value) {
dialect.quoteTimestampLiteral(buf, value);
}
};
/**
* Appends to a buffer a value of this type, in the appropriate format
* for this dialect.
*
* @param buf Buffer
* @param dialect Dialect
* @param value Value
*/
public abstract void quoteValue(
StringBuilder buf,
Dialect dialect,
String value);
public boolean isNumeric() {
return false;
}
}
}
// End SqlQuery.java
|
package picoded.struct;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class DeferredMapEntry_test {
private DeferredMapEntry<String, String> deferredMapEntry;
private String key = "key1";
private Map<String, String> map = null;
@Before
public void setUp() {
map = new HashMap<String, String>();
map.put(key, "value_one");
deferredMapEntry = new DeferredMapEntry<String, String>(map, key);
}
@After
public void tearDown() {
}
@Test
public void getKeyTest() {
assertEquals("key1", deferredMapEntry.getKey());
}
@Test
public void getValueTest() {
assertEquals("value_one", deferredMapEntry.getValue());
}
@Test
public void setValueTest() {
deferredMapEntry.setValue("value_new");
assertEquals("value_new", deferredMapEntry.getValue());
}
@Test
public void equalsTest() {
assertTrue(deferredMapEntry.equals(deferredMapEntry));
}
@Test
public void hashCodeTest() {
deferredMapEntry.hashCode();
}
}
|
package picoded.struct;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class DeferredMapEntry_test {
private DeferredMapEntry<String, String> deferredMapEntry;
private String key = "key1";
private Map<String, String> map = null;
@Before
public void setUp() {
map = new HashMap<String, String>();
map.put(key, "value_one");
deferredMapEntry = new DeferredMapEntry<String, String>(map, key);
}
@After
public void tearDown() {
}
@Test
public void getKeyTest() {
assertEquals("key1", deferredMapEntry.getKey());
}
@Test
public void getValueTest() {
assertEquals("value_one", deferredMapEntry.getValue());
}
@Test
public void setValueTest() {
deferredMapEntry.setValue("value_new");
assertEquals("value_new", deferredMapEntry.getValue());
}
@Test
public void equalsTest() {
assertTrue(deferredMapEntry.equals(deferredMapEntry));
assertFalse(deferredMapEntry.equals((key = null)));
assertFalse(deferredMapEntry.equals((key = "")));
DeferredMapEntry<String, String> temp = new DeferredMapEntry<String, String>(map, key);
assertFalse(deferredMapEntry.equals(temp));
temp = new DeferredMapEntry<String, String>(null, key);
map = new HashMap<String, String>();
map.put(null, null);
deferredMapEntry = new DeferredMapEntry<String, String>(map, key);
temp = new DeferredMapEntry<String, String>(map, key);
assertTrue(deferredMapEntry.equals(temp));
map = new HashMap<String, String>();
map.put(key, "value_one");
deferredMapEntry = new DeferredMapEntry<String, String>(map, key);
map = new HashMap<String, String>();
map.put(null, null);
temp = new DeferredMapEntry<String, String>(map, key);
assertFalse(deferredMapEntry.equals(temp));
map = new HashMap<String, String>();
map.put(null, null);
deferredMapEntry = new DeferredMapEntry<String, String>(map, key);
map = new HashMap<String, String>();
map.put(key, "value_one");
temp = new DeferredMapEntry<String, String>(map, key);
assertFalse(deferredMapEntry.equals(temp));
map = new HashMap<String, String>();
map.put(key, "value_one");
deferredMapEntry = new DeferredMapEntry<String, String>(map, key);
temp = new DeferredMapEntry<String, String>(map, key);
assertTrue(deferredMapEntry.equals(temp));
map = new HashMap<String, String>();
map.put("", "");
deferredMapEntry = new DeferredMapEntry<String, String>(map, key);
temp = new DeferredMapEntry<String, String>(map, key);
assertTrue(deferredMapEntry.equals(temp));
map = new HashMap<String, String>();
map.put(key, "value_one");
deferredMapEntry = new DeferredMapEntry<String, String>(map, key);
map = new HashMap<String, String>();
map.put("", "");
temp = new DeferredMapEntry<String, String>(map, key);
assertFalse(deferredMapEntry.equals(temp));
map = new HashMap<String, String>();
map.put("", "");
deferredMapEntry = new DeferredMapEntry<String, String>(map, key);
map = new HashMap<String, String>();
map.put(key, "value_one");
temp = new DeferredMapEntry<String, String>(map, key);
assertFalse(deferredMapEntry.equals(temp));
map = new HashMap<String, String>();
map.put(key, null);
deferredMapEntry = new DeferredMapEntry<String, String>(map, key);
map = new HashMap<String, String>();
map.put(null, "value_one");
temp = new DeferredMapEntry<String, String>(map, key);
assertTrue(deferredMapEntry.equals(temp));
map = new HashMap<String, String>();
map.put(null, "value_one");
deferredMapEntry = new DeferredMapEntry<String, String>(map, key);
map = new HashMap<String, String>();
map.put(key, null);
temp = new DeferredMapEntry<String, String>(map, key);
assertTrue(deferredMapEntry.equals(temp));
}
@Test
public void equalsWithNullTest() {
assertFalse(deferredMapEntry.equals(null));
}
@Test
public void equalsWithDifferentClassObjectTest() {
assertFalse(deferredMapEntry.equals(map));
}
@Test
public void equalsWithDifferentObjectTest() {
DeferredMapEntry<String, String> temp = new DeferredMapEntry<String, String>(map, key);
assertTrue(deferredMapEntry.equals(temp));
}
@Test
public void hashCodeTest() {
deferredMapEntry.hashCode();
map = new HashMap<String, String>();
map.put(null, null);
DeferredMapEntry<String, String> temp = new DeferredMapEntry<String, String>(map, null);
temp.hashCode();
map = new HashMap<String, String>();
map.put("", "");
temp = new DeferredMapEntry<String, String>(map, "");
temp.hashCode();
map = new HashMap<String, String>();
map.put("key", "val");
temp = new DeferredMapEntry<String, String>(map, "key1");
temp.hashCode();
}
}
|
package pt.fccn.arquivo.pages;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.StringReader;
import java.sql.Driver;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import net.sourceforge.htmlunit.corejs.javascript.ast.NewExpression;
/**
* @author Hugo Viana
*
*/
public class OpenSearchPage {
private final WebDriver driver;
private final String numberOfResultsTag = "feedContent";
private final String listOfResultsTag = "resultados-lista";
private static final String searchBox = "txtSearch";
private static final String searchButton = "btnSubmit";
private final String pageURLCheck = "opensearch";
// Patern to detect if there are results
private Pattern noResultsPattern = Pattern.compile("\\d Resultados");
private boolean isPredProd=false;
/**
* Create a new OpenSearchPage from navigation
* @param driver
*/
public OpenSearchPage(WebDriver driver,boolean isPreProd){
this.isPredProd=isPreProd;
this.driver= driver;
// Check that we're on the right page.
if (!(driver.getCurrentUrl().contains(pageURLCheck))) {
throw new IllegalStateException("This is not the results opensearch page\n URL of current page: " + driver.getCurrentUrl());
}
}
/**
* Gather search for a term
* @param query Term that was searched
* @return true if the term exists in the first result title or in the snippet text
*/
public boolean existsResults() throws Exception{
System.out.println("Checking if results are presented!");
String resultsTags = driver.findElement(By.id(numberOfResultsTag)).getText();
/**
* Verify coherence in result between opensarch api and search on arquivo.pt
* @param firstTitleOfResultList The first result when searching for a query through arquivo.pt full text-search
* @return true if the first result are coherent with opensearch result, false otherwises
*/
public boolean inspectCoherence(String firstTitleOfResultList) {
/**
* It is only needed when the test is run individually, if not IndexPage will set this variable
* Verify that the term exists in as a search result
* @param query Term that was searched
* @return true if the term exists in the first result title or in the snippet text
*/
public String setFirstResult(String searchTerms) {
//Create a new firefox driver
System.out.println("Current URL: " + driver.getCurrentUrl());
System.out.println(driver.getCurrentUrl().split("opensearch")[0]);
WebDriver searchDriver = new FirefoxDriver();
searchDriver.get(driver.getCurrentUrl().split("opensearch")[0]);
searchDriver.findElement(By.id(searchBox)).clear();
searchDriver.findElement(By.id(searchBox)).sendKeys(searchTerms);
searchDriver.findElement(By.id(searchButton)).submit();
WebElement listOfResults = searchDriver.findElement(By.id(listOfResultsTag));
searchDriver.close();
|
package org.exist.xquery.xqts;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import junit.framework.Assert;
import org.custommonkey.xmlunit.Diff;
import org.exist.dom.ElementImpl;
import org.exist.dom.NodeProxy;
import org.exist.dom.QName;
import org.exist.security.xacml.AccessContext;
import org.exist.storage.DBBroker;
import org.exist.util.serializer.SAXSerializer;
import org.exist.w3c.tests.TestCase;
import org.exist.xmldb.XQueryService;
import org.exist.xmldb.XmldbURI;
import org.exist.xquery.ErrorCodes.ErrorCode;
import org.exist.xquery.CompiledXQuery;
import org.exist.xquery.Variable;
import org.exist.xquery.VariableImpl;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQuery;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.Type;
import org.w3c.dom.Attr;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XMLResource;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
*
*/
public class QT3TS_case extends TestCase {
protected static final String FOLDER = "test/external/QT3-test-suite/";
protected static final String QT_NS = "http:
protected static final XmldbURI QT3_URI = XmldbURI.DB.append("QT3");
protected static final String xquery3declaration = "xquery version \"3.0\";\n";
@Override
public void loadTS() throws Exception {
System.out.println("loading QT3...");
QT3TS_To_junit convertor = new QT3TS_To_junit();
convertor.init();
try {
convertor.load();
System.out.println("loaded QT3.");
} finally {
convertor.release();
}
}
private Sequence enviroment(String file) throws Exception {
DBBroker broker = null;
XQuery xquery = null;
try {
broker = pool.get(pool.getSecurityManager().getSystemSubject());
xquery = broker.getXQueryService();
broker.getConfiguration().setProperty( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL, true);
String query = "xmldb:document('"+file+"')";
return xquery.execute(query, null, AccessContext.TEST);
} finally {
pool.release(broker);
}
}
private HashMap<String, Sequence> enviroments(String file) {
HashMap<String, Sequence> enviroments = new HashMap<String, Sequence>();
DBBroker broker = null;
try {
broker = pool.get(pool.getSecurityManager().getSystemSubject());
XQuery xquery = broker.getXQueryService();
broker.getConfiguration().setProperty( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL, true);
String query = "declare namespace qt='"+QT_NS+"';\n"+
"let $testCases := xmldb:document('/db/QT3/"+file+"')\n"+
"let $tc := $testCases//qt:environment\n"+
"return $tc";
Sequence result = xquery.execute(query, null, AccessContext.TEST);
String col = XmldbURI.create("/db/QT3/"+file).removeLastSegment().toString();
for (NodeProxy node : result.toNodeSet()) {
ElementImpl el = (ElementImpl) node.getNode();
String name = el.getAttribute("name");
if (name == null)
continue;
NodeList sources = el.getElementsByTagNameNS(QT_NS, "source");
for (int j = 0; j < sources.getLength(); j++) {
ElementImpl source = (ElementImpl) sources.item(j);
String role = source.getAttribute("role");
Assert.assertEquals(".", role);
String url = source.getAttribute("file");
Assert.assertFalse("".equals(url));
Assert.assertFalse(enviroments.containsKey(name));
try {
enviroments.put(name, enviroment(col+"/"+url));
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.release(broker);
}
return enviroments;
}
private Sequence getEnviroment(String file, String name) {
Sequence enviroment = null;
DBBroker broker = null;
try {
broker = pool.get(pool.getSecurityManager().getSystemSubject());
XQuery xquery = broker.getXQueryService();
broker.getConfiguration().setProperty( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL, true);
String query = "declare namespace qt='"+QT_NS+"';\n"+
"let $testCases := xmldb:document('/db/QT3/"+file+"')\n"+
"let $tc := $testCases//qt:environment[@name eq '"+name+"']\n"+
"let $catalog := xmldb:document('/db/QT3/catalog.xml')\n"+
"let $cat := $catalog//qt:environment[@name eq '"+name+"']\n"+
"return ($tc, $cat)";
Sequence result = xquery.execute(query, null, AccessContext.TEST);
String col = XmldbURI.create("/db/QT3/"+file).removeLastSegment().toString();
for (NodeProxy node : result.toNodeSet()) {
ElementImpl el = (ElementImpl) node.getNode();
String _name = el.getAttribute("name");
if (_name == null)
continue;
col = el.getDocument().getURI().removeLastSegment().toString();
NodeList sources = el.getElementsByTagNameNS(QT_NS, "source");
for (int j = 0; j < sources.getLength(); j++) {
ElementImpl source = (ElementImpl) sources.item(j);
String role = source.getAttribute("role");
Assert.assertEquals(".", role);
String url = source.getAttribute("file");
Assert.assertFalse("".equals(url));
// Assert.assertFalse(enviroments.containsKey(name));
Assert.assertNull(enviroment);
try {
enviroment = enviroment(col+"/"+url);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.release(broker);
}
return enviroment;
}
protected void testCase(String file, String tcName) {
System.out.println("test "+tcName);
DBBroker broker = null;
Sequence result = null;
XQuery xquery = null;
try {
XQueryService service = (XQueryService) testCollection.getService("XQueryService", "1.0");
Set<String> extectedError = new HashSet<String>();
try {
broker = pool.get(pool.getSecurityManager().getSystemSubject());
xquery = broker.getXQueryService();
final XQueryContext context = new XQueryContext(pool, AccessContext.TEST);
broker.getConfiguration().setProperty( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL, true);
String query = "declare namespace qt='"+QT_NS+"';\n"+
"let $testCases := xmldb:document('/db/QT3/"+file+"')\n"+
"let $tc := $testCases//qt:test-case[@name eq \""+tcName+"\"]\n"+
"return $tc";
ResourceSet results = service.query(query);
Assert.assertFalse("", results.getSize() != 1);
ElementImpl TC = (ElementImpl) ((XMLResource) results.getResource(0)).getContentAsDOM();
Sequence contextSequence = null;
NodeList expected = null;
String nodeName = "";
//compile & evaluate
String caseScript = null;
NodeList childNodes = TC.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node child = childNodes.item(i);
switch (child.getNodeType()) {
case Node.ATTRIBUTE_NODE:
// String name = ((Attr)child).getName();
// if (name.equals("scenario"))
// scenario = ((Attr)child).getValue();
break;
case Node.ELEMENT_NODE:
nodeName = ((ElementImpl) child).getLocalName();
if (nodeName.equals("test")) {
ElementImpl el = ((ElementImpl) child);
caseScript = el.getNodeValue();
} else if (nodeName.equals("environment")) {
ElementImpl el = ((ElementImpl) child);
String ref = el.getAttribute("ref");
if (!(ref == null || "empty".equals(ref) || ref.isEmpty())) {
Assert.assertNull(contextSequence);
contextSequence = getEnviroment(file, ref);
} else {
NodeList _childNodes = el.getChildNodes();
for (int j = 0; j < _childNodes.getLength(); j++) {
Node _child = _childNodes.item(j);
switch (_child.getNodeType()) {
case Node.ELEMENT_NODE:
nodeName = ((ElementImpl) _child).getLocalName();
if (nodeName.equals("param")) {
el = ((ElementImpl) _child);
Variable var = new VariableImpl(QName.parse(context, el.getAttribute("name")));
String type = el.getAttribute("as");
if ("xs:date".equals(type)) {
var.setStaticType(Type.DATE);
Sequence res = xquery.execute(el.getAttribute("select"), null, AccessContext.TEST);
Assert.assertEquals(1, res.getItemCount());
var.setValue(res);
} else if ("xs:dateTime".equals(type)) {
var.setStaticType(Type.DATE_TIME);
Sequence res = xquery.execute(el.getAttribute("select"), null, AccessContext.TEST);
Assert.assertEquals(1, res.getItemCount());
var.setValue(res);
} else {
Assert.fail("unknown type '"+type+"'");
}
context.declareGlobalVariable(var);
}
}
}
}
} else if (nodeName.equals("result")) {
ElementImpl el = ((ElementImpl) child);
possibleErrors(el, extectedError);
NodeList anyOf = el.getElementsByTagNameNS(QT_NS, "any-of");
for (int j = 0; j < anyOf.getLength(); j++) {
el = (ElementImpl) anyOf.item(j);
possibleErrors(el, extectedError);
}
expected = el.getChildNodes();
}
break;
default :
;
}
}
final CompiledXQuery compiled = xquery.compile(context, xquery3declaration+caseScript);
result = xquery.execute(compiled, contextSequence);
for (int i = 0; i < expected.getLength(); i++) {
Node node = expected.item(i);
checkResults(node.getLocalName(), node.getChildNodes(), result);
}
} catch (XPathException e) {
e.printStackTrace();
ErrorCode errorCode = e.getErrorCode();
if (errorCode != null && extectedError.contains(errorCode.getErrorQName().getLocalName()))
return;
Assert.fail("expected error code: '" + extectedError + "', but got: '" + e.getMessage() + "'");
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
} finally {
pool.release(broker);
}
} catch (XMLDBException e) {
Assert.fail(e.toString());
}
}
private void possibleErrors(ElementImpl el, Set<String> extectedError) {
NodeList errors = el.getElementsByTagNameNS(QT_NS, "error");
for (int j = 0; j < errors.getLength(); j++) {
ElementImpl error = (ElementImpl) errors.item(j);
//check error for 'code' attribute
String code = error.getAttribute("code");
if (code != null && !code.isEmpty()) {
extectedError.add(code);
}
}
}
private void checkResults(String type, NodeList expected, Sequence result) throws Exception {
if ("all-of".equals(type)) {
for (int i = 0; i < expected.getLength(); i++) {
final Node node = expected.item(i);
checkResults(node.getLocalName(), node.getChildNodes(), result);
}
} else if ("any-of".equals(type)) {
StringBuilder sb = new StringBuilder();
sb.append("at any-of all failed\n");
for (int i = 0; i < expected.getLength(); i++) {
final Node node = expected.item(i);
try {
checkResults(node.getLocalName(), node.getChildNodes(), result);
return;
} catch (Throwable e) {
e.printStackTrace();
sb.append(e.getMessage()).append("\n");
}
}
Assert.assertTrue(sb.toString(), false);
} else if ("assert".equals(type)) {
Assert.assertTrue("not implemented 'assert'", false);
} else if ("assert-type".equals(type)) {
for (int i = 0; i < expected.getLength(); i++) {
final Node node = expected.item(i);
final String expect = node.getNodeValue();
final int actual = result.itemAt(i).getType();
if (Type.subTypeOf(actual, Type.getType(expect)))
return;
Assert.assertEquals("expected '"+expect+"' get '"+Type.getTypeName(actual),
Type.getType(expect),
result.itemAt(i).getType()
);
}
} else if ("assert-eq".equals(type)) {
for (int i = 0; i < expected.getLength(); i++) {
final Node node = expected.item(i);
String expect = node.getNodeValue();
if ((expect.startsWith("\"") && expect.endsWith("\"")) || (expect.startsWith("'") && expect.endsWith("'"))) {
//? check is it xs:string ?
Assert.assertEquals(
expect.substring(1, expect.length()-1),
result.itemAt(i).getStringValue()
);
} else if (expect.startsWith("xs:float(")) {
final int actual = result.itemAt(i).getType();
if (Type.subTypeOf(actual, Type.getType("xs:float"))) {
Assert.assertEquals(
expect.substring(10, expect.length()-2),
result.itemAt(i).getStringValue()
);
return;
}
Assert.assertEquals("expected '"+expect+"' get '"+Type.getTypeName(actual),
Type.getType(expect),
result.itemAt(i).getType()
);
} else
Assert.assertEquals(
expect,
result.itemAt(i).getStringValue()
);
}
} else if ("assert-deep-eq".equals(type)) {
Assert.assertEquals(1, expected.getLength());
final Node node = expected.item(0);
String expect = node.getNodeValue();
StringBuilder got = new StringBuilder();
for (int i = 0; i < result.getItemCount(); i++) {
got.append(result.itemAt(i).getStringValue());
if (i != result.getItemCount() - 1)
got.append(", ");
}
Assert.assertEquals(
expect,
got.toString()
);
} else if ("assert-true".equals(type)) {
Assert.assertTrue("expecting true get false", result.effectiveBooleanValue());
} else if ("assert-false".equals(type)) {
Assert.assertFalse("expecting false get true", result.effectiveBooleanValue());
} else if ("assert-string-value".equals(type)) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.getItemCount(); i++) {
sb.append(result.itemAt(i).getStringValue());
if (i+1 != result.getItemCount())
sb.append(" ");
}
for (int i = 0; i < expected.getLength(); i++) {
final Node node = expected.item(i);
String expect = node.getNodeValue();
Assert.assertEquals(
expect,
sb.toString()
);
}
} else if ("assert-serialization-error".equals(type)) {
Assert.assertTrue("not implemented 'assert-serialization-error'", false);
} else if ("serialization-matches".equals(type)) {
Assert.assertTrue("not implemented 'serialization-matches'", false);
} else if ("assert-permutation".equals(type)) {
Assert.assertEquals(1, expected.getLength());
final Node node = expected.item(0);
String[] expect = node.getNodeValue().split(", ");
for (int i = 0; i < result.getItemCount(); i++) {
Item item = result.itemAt(i);
String got = item.getStringValue();
if (item.getType() == Type.STRING) {
got = '"' + got + '"';
} else if (item.getType() == Type.BOOLEAN) {
got = got + "()";
} else if (item.getType() == Type.FLOAT) {
got = "xs:float('" + got + "')";
}
boolean found = false;
for (int j = 0; j < expect.length; j++) {
if (expect[j] != null && got.equals(expect[j])) {
expect[j] = null;
found = true;
break;
}
}
if (!found) {
Assert.fail("Unexpected '"+got+"'");
}
}
for (int j = 0; j < expect.length; j++) {
if (expect[j] != null) {
Assert.fail("Unmatched '"+expect[j]+"'");
}
}
} else if ("assert-count".equals(type)) {
if (expected.getLength() == 1 && "1".equals( expected.item(0).getNodeValue()) && result != null) {
return;
}
Assert.assertEquals(
expected.item(0).getNodeValue(),
String.valueOf( result.getItemCount() )
);
} else if ("assert-empty".equals(type)) {
Assert.assertTrue(result.isEmpty());
} else if ("assert-xml".equals(type)) {
for(int i = 0; i < expected.getLength(); i++) {
final int ic = i;
boolean ignorePrefixes = false;
final Node exNode = expected.item(i);
String exString = null;
if(exNode.getNodeType() == Node.ATTRIBUTE_NODE) {
final Attr attr = (Attr)exNode;
if(attr.getName().equals("file")) {
final Sequence seq = enviroment(XmldbURI.create(attr.getBaseURI()).removeLastSegment()+"/"+attr.getValue());
StringBuilder sb = new StringBuilder();
for(int j = 0; j < seq.getItemCount(); j++) {
sb.append(toString(seq.itemAt(j)));
}
exString = sb.toString();
} else if(attr.getName().equals("ignore-prefixes")) {
ignorePrefixes = Boolean.parseBoolean(attr.getValue());
exString = expected.item(++i).getNodeValue();
} else {
Assert.fail("eXist XQTS3 Test Suite Error: Unknown Attribute '" +attr.getName() + "'");
return;
}
} else {
exString = exNode.getNodeValue();
}
final Item acNode = result.itemAt(ic);
Assert.assertTrue(
diffXML(exString, toString(acNode), ignorePrefixes)
);
}
} else if ("error".equals(type)) {
Assert.assertTrue("unhandled error "+expected, false);
} else {
Assert.assertTrue("unknown '"+type+"'", false);
}
}
private static final Properties properties = new Properties();
private String toString(Item item) throws SAXException {
StringWriter writer = new StringWriter();
SAXSerializer serializer = new SAXSerializer(writer, properties);
item.toSAX(pool.getActiveBroker(), serializer, properties);
String serialized = writer.toString();
//System.out.println(serialized);
return serialized;
}
private boolean diffXML(final String expectedResult, final String result) throws SAXException, IOException {
return diffXML(expectedResult, result, false);
}
/**
* @param expectedResult
* @param result
* @param lax When set to false, expectedResult and result must be 'identical', when set to true it is acceptable if they are 'similar'
*/
private boolean diffXML(final String expectedResult, final String result, final boolean lax) throws SAXException, IOException {
final Diff diff = new Diff(expectedResult.trim(), result);
boolean match = false;
if(lax) {
match = diff.similar();
} else {
match = diff.identical();
}
if(match) {
//pass
return true;
}
//fail
System.out.println("expected:");
System.out.println(expectedResult);
System.out.println("but got:");
System.out.println(result);
System.out.println(diff.toString());
return false;
}
private void diffXML(final Node expectedNode, final Node actualNode) {
Assert.assertTrue("expected: " + expectedNode+ " but got: " +actualNode, expectedNode.isEqualNode(actualNode));
}
@Override
protected String getCollection() {
return QT3_URI.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.