answer
stringlengths 17
10.2M
|
|---|
package com.qmetry.qaf.automation.report;
import static com.qmetry.qaf.automation.core.ConfigurationManager.getBundle;
import static com.qmetry.qaf.automation.data.MetaDataScanner.formatMetaData;
import static com.qmetry.qaf.automation.util.JSONUtil.getJsonObjectFromFile;
import static com.qmetry.qaf.automation.util.JSONUtil.writeJsonObjectToFile;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;
import com.qmetry.qaf.automation.core.CheckpointResultBean;
import com.qmetry.qaf.automation.core.LoggingBean;
import com.qmetry.qaf.automation.integration.TestCaseResultUpdator;
import com.qmetry.qaf.automation.integration.TestCaseRunResult;
import com.qmetry.qaf.automation.keys.ApplicationProperties;
import com.qmetry.qaf.automation.testng.report.ClassInfo;
import com.qmetry.qaf.automation.testng.report.MetaInfo;
import com.qmetry.qaf.automation.testng.report.MethodInfo;
import com.qmetry.qaf.automation.testng.report.MethodResult;
import com.qmetry.qaf.automation.testng.report.Report;
import com.qmetry.qaf.automation.testng.report.ReportEntry;
import com.qmetry.qaf.automation.testng.report.TestOverview;
import com.qmetry.qaf.automation.util.DateUtil;
import com.qmetry.qaf.automation.util.FileUtil;
import com.qmetry.qaf.automation.util.StringUtil;
/**
*
* @author chirag.jayswal
*
*/
public class JsonReporter implements TestCaseResultUpdator {
private static final Log logger = LogFactoryImpl.getLog(JsonReporter.class);
private static final String REPORT_DIR = ApplicationProperties.JSON_REPORT_DIR
.getStringVal(ApplicationProperties.JSON_REPORT_ROOT_DIR.getStringVal("test-results") + "/"
+ DateUtil.getDate(0, "EdMMMyy_hhmmssa"));
private static List<StatusCounter> suiteStatusCounters = new ArrayList<StatusCounter>();
private static List<StatusCounter> testSetStatusCounters = new ArrayList<StatusCounter>();
@Override
public boolean updateResult(TestCaseRunResult result) {
String suiteName = result.getExecutionInfo().getOrDefault("suiteName", "Default Suite").toString();
String testName = StringUtil.toTitleCaseIdentifier(suiteName) + "/" +StringUtil.toTitleCaseIdentifier((String) result.getExecutionInfo().getOrDefault("testName", "Default Set"));
String suitReportDir = REPORT_DIR ;
String testReportDir = suitReportDir + "/" + testName;
StatusCounter suiteStatusCounter = getStatusCounter(suiteStatusCounters,
StatusCounter.of(suiteName).withFile(suitReportDir));
StatusCounter testStatusCounter = getStatusCounter(testSetStatusCounters,
StatusCounter.of(testName).withFile(testReportDir));
suiteStatusCounter.add(result.getStatus());
testStatusCounter.add(result.getStatus());
// suite meta-info
updateSuiteMetaData(result, suiteStatusCounter, testStatusCounter);
// test overview
updateTestOverView(result, testStatusCounter);
addMethodResult(result, testStatusCounter);
return true;
}
@Override
public String getToolName() {
return "QAF Json Reporter";
}
@Override
public boolean allowConfigAndRetry() {
return true;
}
@Override
public boolean enabled() {
return getBundle().getBoolean("disable.qaf.testng.reporter", true)
&& getBundle().getBoolean("qaf.json.reporter", true);
}
@Override
public boolean allowParallel() {
return false;
}
public static List<StatusCounter> getSuiteStatusCounters() {
return Collections.unmodifiableList(suiteStatusCounters) ;
}
public static List<StatusCounter> getTestSetStatusCounters() {
return Collections.unmodifiableList(testSetStatusCounters);
}
private StatusCounter getStatusCounter(List<StatusCounter> statusCounters, StatusCounter statusCounter) {
int index = statusCounters.indexOf(statusCounter);
if (index >= 0) {
return statusCounters.get(index);
}
statusCounters.add(statusCounter);
FileUtil.checkCreateDir(statusCounter.toString());
return statusCounter;
}
@SuppressWarnings("unchecked")
private void addMethodResult(TestCaseRunResult result,
StatusCounter testStatusCounter) {
// method details
int index = 1;
MethodResult methodResult = new MethodResult();
methodResult.setSeleniumLog((List<LoggingBean>) result.getCommandLogs());
methodResult.setCheckPoints((List<CheckpointResultBean>) result.getCheckPoints());
methodResult.setThrowable(result.getThrowable());
//calculate filename
String identifierKey = ApplicationProperties.TESTCASE_IDENTIFIER_KEY.getStringVal("testCaseId");
String methodResultFile = result.getMetaData().getOrDefault(identifierKey, "").toString();
if (result.getTestData() != null && result.getTestData().size() > 0) {
Object testData = result.getTestData().iterator().next();
if (testData instanceof Map<?, ?>) {
methodResultFile = ((Map<String, Object>) testData).getOrDefault(identifierKey, methodResultFile).toString();
index = (int) ((Map<String, Object>) testData).getOrDefault("__index", 1);
}
}
if (StringUtil.isBlank(methodResultFile)) {
methodResultFile = result.getName();
}
methodResultFile = StringUtil.toTitleCaseIdentifier(methodResultFile);
if (methodResultFile.length() > 45) {
methodResultFile = methodResultFile.substring(0, 45);
}
String methodResultDir = testStatusCounter.toString() + "/" + result.getClassName();
if (new File(methodResultDir, methodResultFile + ".json").exists()) {
methodResultFile = methodResultFile + testStatusCounter.getTotal();
}
//write details
writeJsonObjectToFile(methodResultDir + "/" + methodResultFile + ".json", methodResult);
// update Class Meta Info meta-data
String classInfoFile = methodResultDir + "/meta-info.json";
ClassInfo classInfo = getJsonObjectFromFile(classInfoFile, ClassInfo.class);
MethodInfo methodInfo = new MethodInfo();
methodInfo.setStartTime(result.getStarttime());
methodInfo.setDuration(result.getEndtime() - result.getStarttime());
methodInfo.setArgs(result.getTestData().toArray());
methodInfo.setIndex(index);
methodInfo.setType(result.isTest() ? "test" : "config");
methodInfo.setResult(result.getStatus().toQAF());
Map<String, Object> metaData = result.getMetaData();
metaData.put("name", result.getName());
metaData.put("resultFileName", methodResultFile);
formatMetaData(metaData);
methodInfo.setMetaData(metaData);
int retryCount = (int) result.getExecutionInfo().getOrDefault("retryCount", 0);
if (retryCount > 0) {
methodInfo.setRetryCount(retryCount);
}
if (!classInfo.getMethods().contains(methodInfo)) {
classInfo.getMethods().add(methodInfo);
writeJsonObjectToFile(classInfoFile, classInfo);
} else {
logger.warn("methodInfo already wrritten for " + methodInfo.getName());
}
}
private void updateSuiteMetaData(TestCaseRunResult result, StatusCounter suiteStatusCounter,
StatusCounter testStatusCounter) {
String file = suiteStatusCounter.toString() + "/meta-info.json";
Report report;
if (new File(file).exists()) {
report = getJsonObjectFromFile(file, Report.class);
report.getTests().add(testStatusCounter.getName());
} else {
report = new Report();
report.setStartTime(result.getStarttime());
Set<String> tests = new HashSet<String>();
tests.add(testStatusCounter.getName());
report.setTests(tests);
report.setName(suiteStatusCounter.getName());
ReportEntry reportEntry = new ReportEntry();
reportEntry.setName(suiteStatusCounter.getName());
reportEntry.setDir(suiteStatusCounter.toString());
reportEntry.setStartTime(getBundle().getLong("execution.start.ts", result.getStarttime()));
String reportMetaInfoFile = ApplicationProperties.JSON_REPORT_ROOT_DIR.getStringVal("test-results")
+ "/meta-info.json";
MetaInfo metaInfo = getJsonObjectFromFile(reportMetaInfoFile, MetaInfo.class);
// metaInfo.getReports().remove(reportEntry);
metaInfo.getReports().add(reportEntry);
writeJsonObjectToFile(reportMetaInfoFile, metaInfo);
}
report.setEndTime(result.getEndtime());
report.setPass(suiteStatusCounter.getPass());
report.setFail(suiteStatusCounter.getFail());
report.setSkip(suiteStatusCounter.getSkip());
report.setTotal(suiteStatusCounter.getTotal());
report.setStatus(suiteStatusCounter.getStatus());
writeJsonObjectToFile(file, report);
}
private void updateTestOverView(TestCaseRunResult result, StatusCounter testStatusCounter) {
String file = testStatusCounter.toString() + "/overview.json";
TestOverview testOverview;
if (new File(file).exists()) {
testOverview = getJsonObjectFromFile(file, TestOverview.class);
testOverview.getClasses().add(result.getClassName());
Object dc = result.getExecutionInfo().get("driverCapabilities");
if(null!=dc ) {
testOverview.getEnvInfo().put("browser-desired-capabilities", getBundle().getObject("driver.desiredCapabilities"));
testOverview.getEnvInfo().put("browser-actual-capabilities", dc);
}
} else {
testOverview = new TestOverview();
testOverview.setStartTime(result.getStarttime());
Set<String> classes = new HashSet<String>();
classes.add(result.getClassName());
testOverview.setClasses(classes);
Map<String, Object> envInfo = new HashMap<String, Object>();
Map<String, Object> executionEnvInfo = new HashMap<String, Object>();
envInfo.put("execution-env-info", executionEnvInfo);
testOverview.setEnvInfo(envInfo);
envInfo.put("isfw-build-info", getBundle().getObject("isfw.build.info"));
envInfo.put("run-parameters", result.getExecutionInfo().get("env"));
Object dc = result.getExecutionInfo().get("driverCapabilities");
if(null!=dc ) {
envInfo.put("browser-desired-capabilities", getBundle().getObject("driver.desiredCapabilities"));
envInfo.put("browser-actual-capabilities", dc);
}
executionEnvInfo.put("os.name", System.getProperty("os.name"));
executionEnvInfo.put("os.version", System.getProperty("os.version"));
executionEnvInfo.put("os.arch", System.getProperty("os.arch"));
executionEnvInfo.put("java.version", System.getProperty("java.version"));
executionEnvInfo.put("java.vendor", System.getProperty("java.vendor"));
executionEnvInfo.put("java.arch", System.getProperty("sun.arch.data.model"));
executionEnvInfo.put("user.name", System.getProperty("user.name"));
executionEnvInfo.put("host", System.getProperty("host.name"));
}
testOverview.setEndTime(result.getEndtime());
testOverview.setPass(testStatusCounter.getPass());
testOverview.setFail(testStatusCounter.getFail());
testOverview.setSkip(testStatusCounter.getSkip());
testOverview.setTotal(testStatusCounter.getTotal());
writeJsonObjectToFile(file, testOverview);
}
}
|
package com.stromberglabs.jopensurf;
public class GaussianConstants {
public static final double[][] Gauss25 = {
{ 0.02546481, 0.02350698, 0.01849125, 0.01239505, 0.00708017, 0.00344629, 0.00142946 },
{ 0.02350698, 0.02169968, 0.01706957, 0.01144208, 0.00653582, 0.00318132, 0.00131956 },
{ 0.01849125, 0.01706957, 0.01342740, 0.00900066, 0.00514126, 0.00250252, 0.00103800 },
{ 0.01239505, 0.01144208, 0.00900066, 0.00603332, 0.00344629, 0.00167749, 0.00069579 },
{ 0.00708017, 0.00653582, 0.00514126, 0.00344629, 0.00196855, 0.00095820, 0.00039744 },
{ 0.00344629, 0.00318132, 0.00250252, 0.00167749, 0.00095820, 0.00046640, 0.00019346 },
{ 0.00142946, 0.00131956, 0.00103800, 0.00069579, 0.00039744, 0.00019346, 0.00008024 }
};
public static double[][] getGaussianDistribution(int sampleCount, float range, float sigma){
double[][] distribution = new double[sampleCount][sampleCount];
double sigmaSquared = Math.pow(sigma,2);
double inverseTwoPiSigmaSquared = 1 / (2 * Math.PI * sigmaSquared);
for ( int i = 0; i < sampleCount; i++ ){
for ( int j = 0; j < sampleCount; j++ ){
double x = (range / (sampleCount-1)) * i;
double y = (range / (sampleCount-1)) * j;
double power = Math.pow(x,2)/(2*sigmaSquared) + Math.pow(y,2)/(2*sigmaSquared);
distribution[i][j] = inverseTwoPiSigmaSquared * Math.pow(Math.E,-1*power);
}
}
return distribution;
}
public static void main(String args[]){
double[][] dist = getGaussianDistribution(7,5.5F,2.5F);
for ( double[] row : dist ){
for ( double value : row ){
System.out.format("%.14f,",value);
}
System.out.println("");
}
}
}
|
package com.valkryst.AsciiPanel.component;
import com.valkryst.AsciiPanel.AsciiCharacter;
import com.valkryst.AsciiPanel.AsciiFont;
import com.valkryst.AsciiPanel.AsciiPanel;
import com.valkryst.AsciiPanel.AsciiString;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import lombok.Getter;
public class AsciiButton extends AsciiComponent {
/** Whether or not the button is in the normal state. */
private boolean isInNormalState = true;
/** whether or not the button is in the hovered state. */
private boolean isInHoveredState = false;
/** Whether or not the button is in the pressed state. */
private boolean isInPressedState = false;
/** The first character of the button's text. This is used to identify the text as a button. */
@Getter private char startingCharacter = '<';
/** The last character of the button's text. This is used to identify the text as a button. */
@Getter private char endingCharacter = '>';
/** The background color for when the button is in the normal state. */
@Getter private Paint backgroundColor_normal = Color.BLACK;
/** The foreground color for when the button is in the normal state. */
@Getter private Paint foregroundColor_normal = Color.WHITE;
/** The background color for when the button is in the hover state. */
@Getter private Paint backgroundColor_hover = Color.YELLOW;
/** The foreground color for when the button is in the hover state. */
@Getter private Paint foregroundColor_hover = Color.BLACK;
/** The background color for when the button is in the pressed state. */
@Getter private Paint backgroundColor_pressed = Color.WHITE;
/** The foreground color for when the button is in the pressed state. */
@Getter private Paint foregroundColor_pressed = Color.BLACK;
/** The function to run when the button is clicked. */
@Getter private final Runnable onClickFunction;
/**
* Constructs a new AsciiButton.
*
* @param columnIndex
* The x-axis (column) coordinate of the top-left character.
*
* @param rowIndex
* The y-axis (row) coordinate of the top-left character.
*
* @param text
* The text to display on the button.
*
* @param onClickFunction
* The function to run when the button is clicked.
*/
public AsciiButton(final int columnIndex, final int rowIndex, final String text, final Runnable onClickFunction) {
// The width of the button is "text.length() + 2" because the button text is startingCharacter + text endingCharacter.
super(columnIndex, rowIndex, text.length() + 2, 1);
if (onClickFunction == null) {
throw new IllegalArgumentException("You must specify an instance of runnable when creating an AsciiButton.");
}
this.onClickFunction = onClickFunction;
// Set the button's text:
final AsciiCharacter[] characters = super.getStrings()[0].getCharacters();
characters[0] = new AsciiCharacter(startingCharacter);
characters[characters.length - 1] = new AsciiCharacter(endingCharacter);
for (int column = 1 ; column < characters.length - 1 ; column++) {
characters[column] = new AsciiCharacter(text.charAt(column - 1));
}
// Set the button's colors (must be done after setting text):
setColors(backgroundColor_normal, foregroundColor_normal);
}
@Override
public void registerEventHandlers(final AsciiPanel panel) {
final AsciiFont font = panel.getFont();
final int fontWidth = font.getWidth();
final int fontHeight = font.getHeight();
panel.addEventFilter(MouseEvent.MOUSE_MOVED, event -> {
if (intersects(event, fontWidth, fontHeight)) {
setStateHovered();
} else {
setStateNormal();
}
});
panel.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> {
if (event.getButton().equals(MouseButton.PRIMARY)) {
if (intersects(event, fontWidth, fontHeight)) {
setStatePressed();
}
}
});
panel.addEventFilter(MouseEvent.MOUSE_RELEASED, event -> {
if (event.getButton().equals(MouseButton.PRIMARY)) {
if (isInPressedState) {
onClickFunction.run();
} else {
if (intersects(event, fontWidth, fontHeight)) {
setStateHovered();
} else {
setStateNormal();
}
}
}
});
}
/** Sets the button state to normal if the current state allows for the normal state to be set. */
private void setStateNormal() {
boolean canSetState = isInNormalState == false;
canSetState &= isInHoveredState || isInPressedState;
if (canSetState) {
isInNormalState = true;
isInHoveredState = false;
isInPressedState = false;
setColors(backgroundColor_normal, foregroundColor_normal);
}
}
/** Sets the button state to hovered if the current state allows for the normal state to be set. */
private void setStateHovered() {
boolean canSetState = isInNormalState || isInPressedState;
canSetState &= isInHoveredState == false;
if (canSetState) {
isInNormalState = false;
isInHoveredState = true;
isInPressedState = false;
setColors(backgroundColor_hover, foregroundColor_hover);
}
}
/** Sets the button state to pressed if the current state allows for the normal state to be set. */
private void setStatePressed() {
boolean canSetState = isInNormalState || isInHoveredState;
canSetState &= isInPressedState == false;
if (canSetState) {
isInNormalState = false;
isInHoveredState = false;
isInPressedState = true;
setColors(backgroundColor_pressed, foregroundColor_pressed);
}
}
/**
* Sets the back/foreground colors of all characters to the specified colors.
*
* @param backgroundColor
* The new background color.
*
* @param foregroundColor
* The new foreground color.
*/
private void setColors(final Paint backgroundColor, final Paint foregroundColor) {
for (final AsciiString s : super.getStrings()) {
s.setBackgroundColor(backgroundColor);
s.setForegroundColor(foregroundColor);
}
}
/**
* Sets the starting character of the button's text.
*
* @param startingCharacter
* The new starting character.
*/
public void setStartingCharacter(final char startingCharacter) {
this.startingCharacter = startingCharacter;
super.getStrings()[0].getCharacters()[0].setCharacter(startingCharacter);
}
/**
* Sets the ending character of the button's text.
*
* @param endingCharacter
* The new ending character.
*/
public void setEndingCharacter(final char endingCharacter) {
this.endingCharacter = endingCharacter;
final AsciiCharacter[] characters = super.getStrings()[0].getCharacters();
characters[characters.length - 1].setCharacter(endingCharacter);
}
/**
* Sets the normal background color.
*
* @param color
* The new normal background color.
*/
public void setBackgroundColor_normal(final Paint color) {
if (color == null) {
return;
}
backgroundColor_normal = color;
if (isInNormalState) {
setColors(backgroundColor_normal, foregroundColor_normal);
}
}
/**
* Sets the normal foreground color.
*
* @param color
* The new normal foreground color.
*/
public void setForegroundColor_normal(final Paint color) {
if (color == null) {
return;
}
foregroundColor_normal = color;
if (isInNormalState) {
setColors(backgroundColor_normal, foregroundColor_normal);
}
}
/**
* Sets the hovered background color.
*
* @param color
* The new normal background color.
*/
public void setBackgroundColor_hover(final Paint color) {
if (color == null) {
return;
}
backgroundColor_hover = color;
if (isInHoveredState) {
setColors(backgroundColor_normal, foregroundColor_normal);
}
}
/**
* Sets the hovered foreground color.
*
* @param color
* The new hovered foreground color.
*/
public void setForegroundColor_hover(final Paint color) {
if (color == null) {
return;
}
foregroundColor_hover = color;
if (isInHoveredState) {
setColors(backgroundColor_normal, foregroundColor_normal);
}
}
/**
* Sets the pressed background color.
*
* @param color
* The new pressed background color.
*/
public void setBackgroundColor_pressed(final Paint color) {
if (color == null) {
return;
}
backgroundColor_pressed = color;
if (isInPressedState) {
setColors(backgroundColor_normal, foregroundColor_normal);
}
}
/**
* Sets the pressed foreground color.
*
* @param color
* The new pressed foreground color.
*/
public void setForegroundColor_pressed(final Paint color) {
if (color == null) {
return;
}
foregroundColor_pressed = color;
if (isInPressedState) {
setColors(backgroundColor_normal, foregroundColor_normal);
}
}
}
|
package com.vdesmet.lib.calendar;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import com.viewpagerindicator.TitleProvider;
import java.util.Calendar;
public class MultiCalendarAdapter extends PagerAdapter implements TitleProvider{
private final Context mContext;
private final MultiCalendarView mCalendarView;
public MultiCalendarAdapter(final Context context, final MultiCalendarView calendarView) {
super();
this.mCalendarView = calendarView;
this.mContext = context;
}
@Override
public int getCount() {
final MultiCalendarView calendarView = mCalendarView;
final Calendar firstDay = calendarView.getFirstValidDay();
final Calendar lastDay = calendarView.getLastValidDay();
// get the difference in years and in months
// note that months may be smaller than zero,
// for example, when firstDay is December 2012 and lastDay is January 2013: (1*12) + (0 - 11) = 1 month
final int years = lastDay.get(Calendar.YEAR) - firstDay.get(Calendar.YEAR);
final int months = lastDay.get(Calendar.MONTH) - firstDay.get(Calendar.MONTH);
final int diffMonths = (years * 12 ) + months;
// January - February is 1 month later, but we have 2 months to show
return diffMonths + 1;
}
@Override
public void destroyItem(final ViewGroup container, final int position, final Object item) {
if(item instanceof View) {
container.removeView((View)item);
}
}
@Override
public View instantiateItem(final ViewGroup container, final int position) {
// initialize variables
final MultiCalendarView multiCalendarView = mCalendarView;
final Context context = multiCalendarView.getContext();
final Calendar firstDay = multiCalendarView.getFirstValidDay();
final Calendar lastDay = multiCalendarView.getLastValidDay();
final DayAdapter dayAdapter = multiCalendarView.getDayAdapter();
final OnDayClickListener onDayClickListener = multiCalendarView.getOnDayClickListener();
final int firstDayOfWeek = multiCalendarView.getFirstDayOfWeek();
final int lastDayOfWeek = multiCalendarView.getLastDayOfWeek();
// create first day of the monthView
final Calendar firstMonthDay = Calendar.getInstance();
firstMonthDay.setTimeInMillis(firstDay.getTimeInMillis());
firstMonthDay.add(Calendar.MONTH, position);
if(position != 0) {
firstMonthDay.set(Calendar.DAY_OF_MONTH, 1);
}
// create and configure the view
final CalendarView monthView = new CalendarView(context);
monthView.setFirstValidDay(firstMonthDay);
if(lastDay.get(Calendar.MONTH) == firstMonthDay.get(Calendar.MONTH)) {
// the last day is in this month
monthView.setLastValidDay(lastDay);
}
// add adapter and onClickListener
monthView.setOnDayClickListener(onDayClickListener);
monthView.setDayAdapter(dayAdapter);
// set first and last day of week
monthView.setFirstDayOfWeek(firstDayOfWeek);
monthView.setLastDayOfWeek(lastDayOfWeek);
// FIXME Should be called automatically
monthView.initView();
// return view
container.addView(monthView);
return monthView;
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
@Override
public boolean isViewFromObject(final View view, final Object o) {
return view == o;
}
@Override
public String getTitle(final int position) {
return mContext.getString(R.string.lib_month_august) + " 2013";
}
}
|
package me.nallar.insecurity;
import java.security.Permission;
import java.util.logging.Handler;
import cpw.mods.fml.common.FMLLog;
import me.nallar.tickthreading.Log;
import net.minecraft.client.Minecraft;
import net.minecraft.server.MinecraftServer;
public class InsecurityManager extends java.lang.SecurityManager {
static {
System.setSecurityManager(new InsecurityManager());
}
@SuppressWarnings ("EmptyMethod")
public static void init() {
}
@Override
public void checkPermission(Permission perm) {
}
@Override
public void checkPermission(Permission perm, Object context) {
}
@Override
public void checkExit(int status) {
super.checkExit(status);
if (MinecraftServer.getServer().isServerRunning()) {
Log.info("Server shutting down - requested at ", new ThisIsNotAnError());
}
for (Handler handler : FMLLog.getLogger().getHandlers()) {
handler.flush();
}
for (Handler handler : Log.LOGGER.getHandlers()) {
handler.flush();
}
}
}
|
package fr.masciulli.drinks.adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import fr.masciulli.drinks.Holder;
import fr.masciulli.drinks.R;
import fr.masciulli.drinks.model.Drink;
import com.squareup.picasso.Picasso;
public class DrinksListAdapter extends BaseAdapter {
private List<Drink> mDrinks = new ArrayList<Drink>();
private Context mContext;
public DrinksListAdapter(Context context) {
mContext = context;
for (int i = 0; i < 100; i++) {
mDrinks.add(new Drink("Amaretto Frost", "http:
mDrinks.add(new Drink("Americano", "http:
mDrinks.add(new Drink("Tom Collins", "http:
mDrinks.add(new Drink("Mojito", "http://2eat2drink.files.wordpress.com/2011/04/mojito-final2.jpg"));
mDrinks.add(new Drink("Dry Martini", "http:
}
}
@Override
public int getCount() {
return mDrinks.size();
}
@Override
public Drink getItem(int i) {
return mDrinks.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View root, ViewGroup parent) {
if (root == null) {
root = LayoutInflater.from(mContext).inflate(R.layout.item_drink, parent, false);
}
final ImageView imageView = Holder.get(root, R.id.image);
final TextView nameView = Holder.get(root, R.id.name);
final Drink drink = getItem(i);
nameView.setText(drink.getName());
Picasso.with(mContext).load(drink.getImageURL()).into(imageView);
return root;
}
}
|
package CreatorMapJavaFx.ObjectsInJavaFXWindow;
import CreatorMapJavaFx.Modules.*;
import Editor.EditorThread;
import Main.Transform;
import Wraps.BackgroundWrap;
import Wraps.DecalWrap;
import com.jfoenix.controls.JFXTextField;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javax.swing.*;
import java.net.URL;
import java.util.ResourceBundle;
import static CreatorMapJavaFx.Modules.CollisionsNames.addCollision;
import static CreatorMapJavaFx.Modules.TexturesInfo.getAllTextures;
import static CreatorMapJavaFx.Modules.TexturesInfo.getTextures;
import static Editor.EditorThread.toMode0;
import static Editor.EditorThread.toMode4;
public class WindowController implements Initializable {
@FXML
private JFXTextField textEditMapPath;
@FXML
private ListView listBackgroundPaths;
@FXML
private JFXTextField textBackgroundLayout;
@FXML
private ListView listDecalsPaths;
@FXML
private JFXTextField textDecalsLayout;
@FXML
private JFXTextField textDecalsHeight;
@FXML
private JFXTextField textDecalsWidth;
@FXML
private ListView listSpritesClasses;
@FXML
private ListView listSpritesTextures;
@FXML
private JFXTextField textSpritesLayout;
@FXML
private JFXTextField textSpritesHeight;
@FXML
private JFXTextField textCollisionName;
@FXML
private JFXTextField textEditFPS;
@FXML
private ListView listCollisions;
@FXML
private JFXTextField textSpritesWidth;
@FXML
private JFXTextField textEditWindowHeight;
@FXML
private JFXTextField textEditWindowWidth;
private boolean modeNullEntered = false;
@Override
public void initialize(URL location, ResourceBundle resources) {
getAllTextures();
textEditWindowHeight.setText("600");
textEditWindowWidth.setText("800");
textDecalsLayout.setText(".99");
textBackgroundLayout.setText(".99");
textSpritesLayout.setText(".99");
updatePaths();
}
public void updatePaths() {
listBackgroundPaths.setItems(BackgroundCreatorJavaFx.getImages());
listDecalsPaths.setItems(DecalsCreatorJavaFx.getImages());
listSpritesTextures.setItems(SpritesCreatorJavaFx.getImages());
}
public void btnEditMapOpen() {
}
public void btnEditMapNewMap() {
}
public void btnBackgroundDelete() {
}
public void btnBackgroundAdd() {
float layout = 0;
CustomImage ci = null;
try {
layout = Float.parseFloat(textBackgroundLayout.getText());
if (layout < 1 && layout > -1) {
textSpritesLayout.setText(String.valueOf(layout));
textDecalsLayout.setText(String.valueOf(layout));
System.out.println(layout);
System.out.println(layout + " LAYOUT");
ci = (CustomImage) listBackgroundPaths.getFocusModel().getFocusedItem();
BackgroundWrap backgroundWrap = new BackgroundWrap(ci.getKey(), layout);
EditorThread.toMode1(backgroundWrap);
} else {
JOptionPane.showMessageDialog(null, "LAYOUT MUST BE A NUMBER! 1- < NUMBER < 1");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "LAYOUT MUST BE A NUMBER! 1- < NUMBER < 1");
}
}
public void btnDecalsAdd() {
float layout;
try {
layout = Float.parseFloat(textDecalsLayout.getText());
if (layout < 1 && layout > -1) {
textSpritesLayout.setText(String.valueOf(layout));
textBackgroundLayout.setText(String.valueOf(layout));
System.out.println(textDecalsLayout.getText());
System.out.println(layout + " LAYOUT");
CustomImage ci = (CustomImage) listDecalsPaths.getFocusModel().getFocusedItem();
float height = Float.parseFloat(textDecalsHeight.getText());//ci.getImage().getHeight();
float width = Float.parseFloat(textDecalsWidth.getText()); //ci.getImage().getWidth();
Transform transform = new Transform(layout, width, height);
DecalWrap wrap = new DecalWrap(transform, ci.getKey());
EditorThread.toMode2(wrap);
} else {
JOptionPane.showMessageDialog(null, "LAYOUT MUST BE A NUMBER! 1- < NUMBER < 1");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "LAYOUT MUST BE A NUMBER! 1- < NUMBER < 1");
}
}
public void btnSpritesAdd() {
String path = "";
int layout;
try {
layout = Integer.parseInt(textSpritesLayout.getText());
if (layout < 1 && layout > -1) {
textBackgroundLayout.setText(String.valueOf(layout));
textBackgroundLayout.setText(String.valueOf(layout));
CustomImage ci = (CustomImage) listSpritesTextures.getFocusModel().getFocusedItem();
float height = (float) ci.getImage().getHeight();
float width = (float) ci.getImage().getWidth();
path = ci.getKey() + "|" + ci.getPath();
} else {
JOptionPane.showMessageDialog(null, "LAYOUT MUST BE A NUMBER! 1- < NUMBER < 1");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "LAYOUT MUST BE A NUMBER! 1- < NUMBER < 1");
}
System.out.println(path);
}
public void btnEditSaveMap() {
}
public void setModeNull() {
if (!modeNullEntered) {
toMode0();
modeNullEntered = true;
}
}
public void setModeOne() {
modeNullEntered = false;
}
public void setModeTwo() {
modeNullEntered = false;
}
public void setModeThree() {
modeNullEntered = false;
}
public void listDecalsClick() {
CustomImage ci = (CustomImage) listDecalsPaths.getFocusModel().getFocusedItem();
float height = (float) ci.getImage().getHeight();
float width = (float) ci.getImage().getWidth();
textDecalsHeight.setText(String.valueOf(height));
textDecalsWidth.setText(String.valueOf(width));
}
public void listSpritesTextureClick() {
CustomImage ci = (CustomImage) listSpritesTextures.getFocusModel().getFocusedItem();
float height = (float) ci.getImage().getHeight();
float width = (float) ci.getImage().getWidth();
textSpritesHeight.setText(String.valueOf(height));
textSpritesWidth.setText(String.valueOf(width));
}
public void btnEditOpenWindow() {
System.out.println("HERE 1");
try {
int height = Integer.parseInt(textEditWindowHeight.getText());
int width = Integer.parseInt(textEditWindowWidth.getText());
int fps = Integer.parseInt(textEditFPS.getText());
EditorThread gt;
gt = new EditorThread(width, height, fps, getTextures());
gt.run();
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "HEIGHT,WIDTH,FPS - NUMBERS");
}
}
public void listCollisionsSendCollider() {
String collision = (String) listCollisions.getFocusModel().getFocusedItem();
if (collision != null)
toMode4(collision);
}
public void btnCollisionAdd() {
addCollision(textCollisionName.getText());
listCollisions.setItems(CollisionsNames.getCollisions());
}
}
|
package org.xwiki.rendering.internal.wikimodel;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.wikimodel.wem.IWemConstants;
import org.wikimodel.wem.IWemListener;
import org.wikimodel.wem.WikiFormat;
import org.wikimodel.wem.WikiParameter;
import org.wikimodel.wem.WikiParameters;
import org.wikimodel.wem.WikiReference;
import org.xwiki.rendering.block.*;
import org.xwiki.rendering.listener.Link;
import org.xwiki.rendering.listener.Listener;
import org.xwiki.rendering.listener.SectionLevel;
import org.xwiki.rendering.listener.Format;
import org.xwiki.rendering.parser.LinkParser;
import org.xwiki.rendering.parser.ParseException;
import org.xwiki.url.XWikiURLFactory;
import org.xwiki.url.XWikiURL;
import org.xwiki.url.InvalidURLException;
import org.xwiki.url.serializer.DocumentNameSerializer;
/**
* Transforms WikiModel events into XWiki Rendering events.
*
* @version $Id$
* @since 1.5M1
*/
public class XDOMGeneratorListener implements IWemListener
{
private Stack<Block> stack = new Stack<Block>();
private final MarkerBlock marker = new MarkerBlock();
private LinkParser linkParser;
private XWikiURLFactory urlFactory;
private class MarkerBlock extends AbstractBlock
{
public void traverse(Listener listener)
{
}
}
public XDOMGeneratorListener(LinkParser linkParser, XWikiURLFactory urlFactory)
{
this.linkParser = linkParser;
this.urlFactory = urlFactory;
}
public XDOM getDocument()
{
return new XDOM(generateListFromStack());
}
/**
* {@inheritDoc}
* @see org.wikimodel.wem.IWemListener#beginDefinitionDescription()
*/
public void beginDefinitionDescription()
{
System.out.println("beginDefinitionDescription (not handled yet)");
}
/**
* {@inheritDoc}
* @see org.wikimodel.wem.IWemListener#beginDefinitionList(org.wikimodel.wem.WikiParameters)
*/
public void beginDefinitionList(WikiParameters params)
{
System.out.println("beginDefinitionList(" + params + ") (not handled yet)");
}
public void beginDefinitionTerm()
{
System.out.println("beginDefinitionTerm (not handled yet)");
}
public void beginDocument()
{
// Don't do anything since there's no notion of Document block in XWiki rendering.
}
/**
* A format is a special formatting around an inline element, such as bold, italics, etc.
*/
public void beginFormat(WikiFormat format)
{
this.stack.push(this.marker);
}
public void beginHeader(int level, WikiParameters params)
{
this.stack.push(this.marker);
}
public void beginInfoBlock(char infoType, WikiParameters params)
{
System.out.println("beginInfoBlock(" + infoType + ", " + params + ") (not handled yet)");
}
public void beginList(WikiParameters params, boolean ordered)
{
this.stack.push(this.marker);
}
public void beginListItem()
{
this.stack.push(this.marker);
}
public void beginParagraph(WikiParameters params)
{
this.stack.push(this.marker);
}
public void beginPropertyBlock(String propertyUri, boolean doc)
{
System.out.println("beginPropertyBlock(" + propertyUri + ", " + doc + ") (not handled yet)");
}
public void beginPropertyInline(String str)
{
System.out.println("beginPropertyInline(" + str + ") (not handled yet)");
}
public void beginQuotation(WikiParameters params)
{
System.out.println("beginQuotation(" + params + ") (not handled yet)");
}
public void beginQuotationLine()
{
System.out.println("beginQuotationLine (not handled yet)");
}
public void beginTable(WikiParameters params)
{
System.out.println("beginTable(" + params + ") (not handled yet)");
}
public void beginTableCell(boolean tableHead, WikiParameters params)
{
System.out.println("beginTableCell(" + tableHead + ", " + params + ") (not handled yet)");
}
public void beginTableRow(WikiParameters params)
{
System.out.println("beginTableRow(" + params + ") (not handled yet)");
}
public void endDefinitionDescription()
{
System.out.println("endDefinitionDescription (not handled yet)");
}
public void endDefinitionList(WikiParameters params)
{
System.out.println("endDefinitionList(" + params + ") (not handled yet)");
}
public void endDefinitionTerm()
{
System.out.println("endDefinitionTerm (not handled yet)");
}
public void endDocument()
{
// Don't do anything since there's no notion of Document block in XWiki rendering.
}
public void endFormat(WikiFormat format)
{
if (format.hasStyle(IWemConstants.STRONG)) {
this.stack.push(new FormatBlock(generateListFromStack(), Format.BOLD));
} else if (format.hasStyle(IWemConstants.EM)) {
this.stack.push(new FormatBlock(generateListFromStack(), Format.ITALIC));
} else if (format.hasStyle(IWemConstants.STRIKE)) {
this.stack.push(new FormatBlock(generateListFromStack(), Format.STRIKEDOUT));
} else if (format.hasStyle(IWemConstants.INS)) {
this.stack.push(new FormatBlock(generateListFromStack(), Format.UNDERLINED));
} else if (format.hasStyle(IWemConstants.SUP)) {
this.stack.push(new FormatBlock(generateListFromStack(), Format.SUPERSCRIPT));
} else if (format.hasStyle(IWemConstants.SUB)) {
this.stack.push(new FormatBlock(generateListFromStack(), Format.SUBSCRIPT));
} else if (format.hasStyle(IWemConstants.MONO)) {
this.stack.push(new FormatBlock(generateListFromStack(), Format.MONOSPACE));
} else {
// WikiModel generate begin/endFormat events even for simple text with no style
// so we need to remove our marker
for (Block block : generateListFromStack()) {
this.stack.push(block);
}
}
}
public void endHeader(int level, WikiParameters params)
{
this.stack.push(new SectionBlock(generateListFromStack(), SectionLevel.parseInt(level)));
}
public void endInfoBlock(char infoType, WikiParameters params)
{
System.out.println("endInfoBlock(" + infoType + ", " + params + ") (not handled yet)");
}
public void endList(WikiParameters params, boolean ordered)
{
ListBLock listBlock;
if (ordered) {
listBlock = new NumberedListBlock(generateListFromStack());
} else {
listBlock = new BulletedListBlock(generateListFromStack());
}
this.stack.push(listBlock);
}
public void endListItem()
{
// Note: This means we support Paragraphs inside lists.
this.stack.push(new ListItemBlock(generateListFromStack()));
}
public void endParagraph(WikiParameters params)
{
this.stack.push(new ParagraphBlock(generateListFromStack()));
}
public void endPropertyBlock(String propertyUri, boolean doc)
{
System.out.println("endPropertyBlock(" + propertyUri + ", " + doc + ") (not handled yet)");
}
public void endPropertyInline(String inlineProperty)
{
System.out.println("endPropertyInline(" + inlineProperty + ") (not handled yet)");
}
public void endQuotation(WikiParameters params)
{
System.out.println("endQuotation(" + params + ") (not handled yet)");
}
public void endQuotationLine()
{
System.out.println("endQuotationLine (not handled yet)");
}
public void endTable(WikiParameters params)
{
System.out.println("endTable(" + params + ") (not handled yet)");
}
public void endTableCell(boolean tableHead, WikiParameters params)
{
System.out.println("endTableCell(" + tableHead + ", " + params + ") (not handled yet)");
}
public void endTableRow(WikiParameters params)
{
System.out.println("endTableRow(" + params + ") (not handled yet)");
}
/**
* Called by wikimodel when there's more than 1 empty lines between blocks. For example the following will
* generate a call to <code>onEmptyLines(2)</code>:
* <code><pre>
* {{macro/}}
* ... empty line 1...
* ... empty line 2...
* {{macro/}}
* </pre></code
*
* @param count the number of empty lines separating the two blocks
*/
public void onEmptyLines(int count)
{
// TODO: Handle. Note that this event is not yet sent by wikimodel by the wikimodel XWiki parser.
System.out.println("onEmptyLines(" + count + ") (not handled yet)");
}
public void onEscape(String str)
{
this.stack.push(new EscapeBlock(str));
}
public void onExtensionBlock(String extensionName, WikiParameters params)
{
System.out.println("onExtensionBlock(" + extensionName + ", " + params + ") (not handled yet)");
}
public void onExtensionInline(String extensionName, WikiParameters params)
{
System.out.println("onExtensionInline(" + extensionName + ", " + params + ") (not handled yet)");
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#onHorizontalLine()
*/
public void onHorizontalLine()
{
this.stack.push(HorizontalLineBlock.HORIZONTAL_LINE_BLOCK);
}
/**
* Explicit line breaks. For example in XWiki syntax that would be "\\".
*/
public void onLineBreak()
{
this.stack.push(LineBreakBlock.LINE_BREAK_BLOCK);
}
/**
* A macro block was found and it's separated at least by one new line from the next block. If there's no
* new line with the next block then wikimodel calls
* {@link #onMacroInline(String, org.wikimodel.wem.WikiParameters, String)} instead.
*/
public void onMacroBlock(String macroName, WikiParameters params, String content)
{
Map<String, String> xwikiParams = new LinkedHashMap<String, String>();
for (WikiParameter wikiParameter : params.toList()) {
xwikiParams.put(wikiParameter.getKey(), wikiParameter.getValue());
}
// TODO: Handle the fact that there's a newline between this block and the next one. We need to register this
// somewhere in the XWiki blocks.
this.stack.push(new MacroBlock(macroName, xwikiParams, content));
}
/**
* @see #onMacroBlock(String, org.wikimodel.wem.WikiParameters, String)
*/
public void onMacroInline(String macroName, WikiParameters params, String content)
{
onMacroBlock(macroName, params, content);
}
/**
* "\n" character.
*/
public void onNewLine()
{
this.stack.push(NewLineBlock.NEW_LINE_BLOCK);
}
/**
* Called when WikiModel finds an inline reference such as a URI located directly in the text, as opposed to a link
* inside wiki link syntax delimiters.
*/
public void onReference(String ref)
{
// If there's no link parser defined, don't handle links...
// TODO: Generate some output log
if (this.linkParser != null) {
try {
this.stack.push(new LinkBlock(this.linkParser.parse(ref)));
} catch (ParseException e) {
// TODO: Should we instead generate ErrorBlocks?
throw new RuntimeException("Failed to parse link [" + ref + "]", e);
}
}
}
public void onReference(WikiReference ref)
{
// If there's no link parser defined, don't handle links...
// TODO: Generate some output log
if (this.linkParser != null) {
Link link;
try {
link = this.linkParser.parse(ref.getLink());
} catch (ParseException e) {
// TODO: Should we instead generate ErrorBlocks?
throw new RuntimeException("Failed to parse link [" + ref.getLink() + "]", e);
}
link.setLabel(ref.getLabel());
// Right now WikiModel puts any target element as the first element of the WikiParameters
if (ref.getParameters().getSize() > 0) {
link.setTarget(ref.getParameters().getParameter(0).getKey());
}
// Check if the reference in the link is an relative URI. If that's the case transform it into
// a document name sincce all relative URIs should point to wiki documents.
if (link.getReference().startsWith("/")) {
try {
XWikiURL url = this.urlFactory.createURL(link.getReference());
link.setReference(new DocumentNameSerializer().serialize(url));
// If the label is the same as the reference then remove it. This to prevent having the following
// use case: [[Space.Page]] --HTML--> <a href="/xwiki/bin/view/Space/Page>Space.Page</a>
// --XWIKI--> [[Space.Page>Space.Page]]
if (link.getLabel().equalsIgnoreCase(link.getReference())) {
link.setLabel(null);
}
} catch (InvalidURLException e) {
// If it fails it means this was not a link pointing to a xwiki document after all so we just
// leave it as is.
}
}
this.stack.push(new LinkBlock(link));
}
}
public void onSpace(String str)
{
this.stack.push(SpaceBlock.SPACE_BLOCK);
}
public void onSpecialSymbol(String symbol)
{
this.stack.push(new SpecialSymbolBlock(symbol));
}
public void onTableCaption(String str)
{
System.out.println("onTableCaption(" + str + ") (not handled yet)");
}
// Equivalent of <pre>
public void onVerbatimBlock(String str)
{
System.out.println("onVerbatimBlock(" + str + ") (not handled yet)");
}
// Equivalent of <tt>
public void onVerbatimInline(String str)
{
System.out.println("onVerbatimInline(" + str + ") (not handled yet)");
}
public void onWord(String str)
{
this.stack.push(new WordBlock(str));
}
private List<Block> generateListFromStack()
{
List<Block> blocks = new ArrayList<Block>();
while (!this.stack.empty()) {
if (this.stack.peek() != this.marker) {
blocks.add(this.stack.pop());
} else {
this.stack.pop();
break;
}
}
Collections.reverse(blocks);
return blocks;
}
}
|
package org.waterforpeople.mapping.portal.client.widgets.component;
import java.util.ArrayList;
import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointDto.AccessPointType;
import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointSearchCriteriaDto;
import org.waterforpeople.mapping.app.gwt.client.community.CommunityDto;
import org.waterforpeople.mapping.app.gwt.client.community.CommunityService;
import org.waterforpeople.mapping.app.gwt.client.community.CommunityServiceAsync;
import org.waterforpeople.mapping.app.gwt.client.community.CountryDto;
import org.waterforpeople.mapping.app.gwt.client.config.ConfigurationItemDto;
import org.waterforpeople.mapping.app.gwt.client.config.ConfigurationService;
import org.waterforpeople.mapping.app.gwt.client.config.ConfigurationServiceAsync;
import org.waterforpeople.mapping.app.gwt.client.survey.MetricDto;
import org.waterforpeople.mapping.app.gwt.client.survey.MetricService;
import org.waterforpeople.mapping.app.gwt.client.survey.MetricServiceAsync;
import org.waterforpeople.mapping.app.gwt.client.util.TextConstants;
import com.gallatinsystems.framework.gwt.dto.client.ResponseDto;
import com.gallatinsystems.framework.gwt.util.client.ViewUtil;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
/**
* control that can be used to build up Access Point search criteria objects
*
* @author Christopher Fagiani
*
*/
public class AccessPointSearchControl extends Composite {
private static TextConstants TEXT_CONSTANTS = GWT
.create(TextConstants.class);
private static final String POINT_TYPES_CONFIG = "pointTypes";
private static final String WP_TYPE = "WaterPoint";
private static final String SP_TYPE = "SanitationPoint";
private static final String PI_TYPE = "PublicInstitution";
private static final String HH_TYPE = "Household";
private static final String SCHOOL_TYPE = "School";
private static final String TRAWLER_TYPE = "Trawler";
private static final String PROCEDURE_TYPE = "Procedure";
public enum Mode {
ACCESS_POINT, LOCALE
};
private ListBox apTypeBox;
public static final String ANY_OPT = TEXT_CONSTANTS.any();
public static final String ALL_OPT = TEXT_CONSTANTS.all();
private ListBox countryListbox;
private ListBox communityListbox;
private String specialOption;
private CommunityServiceAsync communityService;
private MetricServiceAsync metricService;
private DateBox collectionDateFrom;
private DateBox collectionDateTo;
private DateBox constructionDateFrom;
private DateBox constructionDateTo;
private TextBox metricValue;
private ListBox metricListbox;
private Mode mode;
public AccessPointSearchControl() {
this(Mode.ACCESS_POINT);
}
public AccessPointSearchControl(Mode m) {
ConfigurationServiceAsync configService = GWT
.create(ConfigurationService.class);
configService.getConfigurationItem(POINT_TYPES_CONFIG,
new AsyncCallback<ConfigurationItemDto>() {
@Override
public void onFailure(Throwable caught) {
// add default set of points
installPointTypes(null);
}
@Override
public void onSuccess(ConfigurationItemDto result) {
if (result != null) {
installPointTypes(result.getValue().split(","));
} else {
installPointTypes(null);
}
}
});
mode = m;
countryListbox = new ListBox();
communityListbox = new ListBox();
metricListbox = new ListBox();
apTypeBox = new ListBox();
collectionDateFrom = new DateBox();
collectionDateTo = new DateBox();
constructionDateFrom = new DateBox();
constructionDateTo = new DateBox();
metricValue = new TextBox();
specialOption = ANY_OPT;
Grid grid = new Grid(4, 4);
grid.setWidget(0, 0, ViewUtil.initLabel(TEXT_CONSTANTS.country()));
grid.setWidget(0, 1, countryListbox);
if (Mode.ACCESS_POINT == mode) {
grid.setWidget(0, 2, ViewUtil.initLabel(TEXT_CONSTANTS.community()));
grid.setWidget(0, 3, communityListbox);
}
grid.setWidget(1, 0,
ViewUtil.initLabel(TEXT_CONSTANTS.collectionDateFrom()));
grid.setWidget(1, 1, collectionDateFrom);
grid.setWidget(1, 2, ViewUtil.initLabel(TEXT_CONSTANTS.to()));
grid.setWidget(1, 3, collectionDateTo);
grid.setWidget(2, 0, ViewUtil.initLabel(TEXT_CONSTANTS.pointType()));
grid.setWidget(2, 1, apTypeBox);
if (Mode.ACCESS_POINT == mode) {
grid.setWidget(3, 0,
ViewUtil.initLabel(TEXT_CONSTANTS.constructionDateFrom()));
grid.setWidget(3, 1, constructionDateFrom);
grid.setWidget(3, 2, ViewUtil.initLabel(TEXT_CONSTANTS.to()));
grid.setWidget(3, 3, constructionDateTo);
} else {
grid.setWidget(3, 0, ViewUtil.initLabel(TEXT_CONSTANTS.metric()));
grid.setWidget(3, 1, metricListbox);
grid.setWidget(3, 2, ViewUtil.initLabel(TEXT_CONSTANTS.value()));
grid.setWidget(3, 3, metricValue);
}
communityService = GWT.create(CommunityService.class);
metricService = GWT.create(MetricService.class);
loadCountries();
if (Mode.ACCESS_POINT == m) {
installChangeHandlers();
} else {
loadMetrics();
}
initWidget(grid);
}
private void installPointTypes(String[] pointTypes) {
if (Mode.LOCALE == mode) {
apTypeBox.addItem(ANY_OPT, ANY_OPT);
if (pointTypes == null || pointTypes.length == 0) {
apTypeBox.addItem(TEXT_CONSTANTS.waterPoint(), WP_TYPE);
apTypeBox.addItem(TEXT_CONSTANTS.sanitationPoint(), SP_TYPE);
apTypeBox.addItem(TEXT_CONSTANTS.publicInst(), PI_TYPE);
apTypeBox.addItem(TEXT_CONSTANTS.school(), SCHOOL_TYPE);
apTypeBox.addItem(TEXT_CONSTANTS.household(), HH_TYPE);
} else {
for (int i = 0; i < pointTypes.length; i++) {
if (WP_TYPE.equalsIgnoreCase(pointTypes[i].trim())) {
apTypeBox.addItem(TEXT_CONSTANTS.waterPoint(), WP_TYPE);
} else if (SP_TYPE.equalsIgnoreCase(pointTypes[i].trim())) {
apTypeBox.addItem(TEXT_CONSTANTS.sanitationPoint(),
SP_TYPE);
} else if (PI_TYPE.equalsIgnoreCase(pointTypes[i].trim())) {
apTypeBox.addItem(TEXT_CONSTANTS.publicInst(), PI_TYPE);
} else if (TRAWLER_TYPE.equalsIgnoreCase(pointTypes[i]
.trim())) {
apTypeBox.addItem(TEXT_CONSTANTS.trawler(),
TRAWLER_TYPE);
} else if (SCHOOL_TYPE.equalsIgnoreCase(pointTypes[i]
.trim())) {
apTypeBox.addItem(TEXT_CONSTANTS.school(), SCHOOL_TYPE);
} else if (PROCEDURE_TYPE.equalsIgnoreCase(pointTypes[i]
.trim())) {
apTypeBox.addItem(TEXT_CONSTANTS.procedure(),
PROCEDURE_TYPE);
} else if (HH_TYPE.equalsIgnoreCase(pointTypes[i].trim())) {
apTypeBox.addItem(TEXT_CONSTANTS.household(), HH_TYPE);
}
}
}
} else {
apTypeBox.addItem(TEXT_CONSTANTS.waterPoint(),
AccessPointType.WATER_POINT.toString());
apTypeBox.addItem(TEXT_CONSTANTS.sanitationPoint(),
AccessPointType.SANITATION_POINT.toString());
apTypeBox.addItem(TEXT_CONSTANTS.publicInst(),
AccessPointType.PUBLIC_INSTITUTION.toString());
apTypeBox.addItem(TEXT_CONSTANTS.school(),
AccessPointType.SCHOOL.toString());
}
}
/**
* constructs a search criteria object using values from the form
*
* @return
*/
public AccessPointSearchCriteriaDto getSearchCriteria() {
AccessPointSearchCriteriaDto dto = new AccessPointSearchCriteriaDto();
dto.setCommunityCode(getSelectedCommunity());
dto.setCountryCode(getSelectedCountry());
dto.setCollectionDateFrom(collectionDateFrom.getValue());
dto.setCollectionDateTo(collectionDateTo.getValue());
dto.setConstructionDateFrom(constructionDateFrom.getValue());
dto.setConstructionDateTo(constructionDateTo.getValue());
dto.setPointType(getSelectedValue(apTypeBox));
String id = getSelectedValue(metricListbox);
if (id != null && id.trim().length() > 0) {
dto.setMetricId(id);
}
dto.setMetricValue(metricValue.getText());
return dto;
}
/**
* sets up anonymous callbacks for both country listbox
*/
private void installChangeHandlers() {
countryListbox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
String country = getSelectedValue(countryListbox);
communityListbox.clear();
// only proceed if they didn't select the "specialOption"
if (country != null) {
loadCommunities(country);
} else {
if (specialOption != null) {
communityListbox.addItem(specialOption, specialOption);
}
}
}
});
}
/**
* loads the countries into the control
*/
private void loadCountries() {
if (specialOption != null) {
countryListbox.addItem(specialOption, specialOption);
communityListbox.addItem(specialOption, specialOption);
}
// Set up the callback object.
AsyncCallback<CountryDto[]> countryCallback = new AsyncCallback<CountryDto[]>() {
public void onFailure(Throwable caught) {
// no-op
}
public void onSuccess(CountryDto[] result) {
if (result != null) {
for (int i = 0; i < result.length; i++) {
countryListbox.addItem(result[i].getName(),
result[i].getIsoAlpha2Code());
}
}
}
};
communityService.listCountries(countryCallback);
}
/**
* loads the metrics into the control
*/
private void loadMetrics() {
// TODO: parameterize with Organization name
// TODO: see if we need to progressively load the list or paginate or
// something if this gets to be too big
metricService.listMetrics(null, null, null, null, "all",
new AsyncCallback<ResponseDto<ArrayList<MetricDto>>>() {
public void onFailure(Throwable caught) {
// no-op
}
public void onSuccess(
ResponseDto<ArrayList<MetricDto>> result) {
metricListbox.addItem("", "");
if (result != null && result.getPayload() != null) {
for (MetricDto metric : result.getPayload())
metricListbox.addItem(metric.getName(), metric
.getKeyId().toString());
}
}
});
}
protected void loadCommunities(String country) {
if (specialOption != null) {
communityListbox.addItem(specialOption, specialOption);
}
AsyncCallback<CommunityDto[]> communityCallback = new AsyncCallback<CommunityDto[]>() {
@Override
public void onFailure(Throwable caught) {
// no-op
}
@Override
public void onSuccess(CommunityDto[] result) {
if (result != null) {
for (int i = 0; i < result.length; i++) {
communityListbox.addItem(result[i].getCommunityCode(),
result[i].getCommunityCode());
}
}
}
};
communityService.listCommunities(country, communityCallback);
}
/**
* helper method to get value out of a listbox. If the "specialOption" is
* selected, it's translated to null since we don't want to filter on
* country.
*
* @param lb
* @return
*/
private String getSelectedValue(ListBox lb) {
if (lb != null && lb.getSelectedIndex() >= 0) {
String val = lb.getValue(lb.getSelectedIndex());
if (specialOption != null && specialOption.equals(val)) {
return null;
} else {
return val;
}
} else {
return null;
}
}
/**
* sets the value of the location
*
* @param val
*/
protected void setSelectedValue(String val, Widget widget) {
ListBox control = (ListBox) widget;
if ((val == null || "null".equalsIgnoreCase(val))
&& specialOption != null) {
control.setSelectedIndex(0);
}
for (int i = 0; i < control.getItemCount(); i++) {
if (control.getValue(i).equals(val)) {
control.setSelectedIndex(i);
break;
}
}
}
/**
* returns selected country code
*
* @return
*/
protected String getSelectedCountry() {
return getSelectedValue(countryListbox);
}
/**
* returns selected community value
*
* @return
*/
protected String getSelectedCommunity() {
return getSelectedValue(communityListbox);
}
}
|
package org.unitime.timetable.test;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Transaction;
import org.unitime.timetable.model.AcademicAreaClassification;
import org.unitime.timetable.model.Assignment;
import org.unitime.timetable.model.ClassInstructor;
import org.unitime.timetable.model.ClassWaitList;
import org.unitime.timetable.model.Class_;
import org.unitime.timetable.model.CourseDemand;
import org.unitime.timetable.model.CourseOffering;
import org.unitime.timetable.model.CourseOfferingReservation;
import org.unitime.timetable.model.InstrOfferingConfig;
import org.unitime.timetable.model.InstructionalOffering;
import org.unitime.timetable.model.LastLikeCourseDemand;
import org.unitime.timetable.model.PosMajor;
import org.unitime.timetable.model.SchedulingSubpart;
import org.unitime.timetable.model.Session;
import org.unitime.timetable.model.StudentClassEnrollment;
import org.unitime.timetable.model.comparators.SchedulingSubpartComparator;
import org.unitime.timetable.model.dao.SessionDAO;
import net.sf.cpsolver.coursett.model.TimeLocation;
import net.sf.cpsolver.studentsct.StudentSectioningLoader;
import net.sf.cpsolver.studentsct.StudentSectioningModel;
import net.sf.cpsolver.studentsct.model.Config;
import net.sf.cpsolver.studentsct.model.Course;
import net.sf.cpsolver.studentsct.model.CourseRequest;
import net.sf.cpsolver.studentsct.model.Enrollment;
import net.sf.cpsolver.studentsct.model.FreeTimeRequest;
import net.sf.cpsolver.studentsct.model.Offering;
import net.sf.cpsolver.studentsct.model.Request;
import net.sf.cpsolver.studentsct.model.Section;
import net.sf.cpsolver.studentsct.model.Student;
import net.sf.cpsolver.studentsct.model.Subpart;
/**
* @author Tomas Muller
*/
public class BatchStudentSectioningLoader extends StudentSectioningLoader {
private static Log sLog = LogFactory.getLog(BatchStudentSectioningLoader.class);
private boolean iIncludeCourseDemands = true;
private boolean iIncludeLastLikeStudents = true;
private boolean iIncludeUseCommittedAssignments = false;
private String iInitiative = null;
private String iTerm = null;
private String iYear = null;
public BatchStudentSectioningLoader(StudentSectioningModel model) {
super(model);
iIncludeCourseDemands = model.getProperties().getPropertyBoolean("Load.IncludeCourseDemands", iIncludeCourseDemands);
iIncludeLastLikeStudents = model.getProperties().getPropertyBoolean("Load.IncludeLastLikeStudents", iIncludeLastLikeStudents);
iIncludeUseCommittedAssignments = model.getProperties().getPropertyBoolean("Load.IncludeUseCommittedAssignments", iIncludeUseCommittedAssignments);
iInitiative = model.getProperties().getProperty("Data.Initiative");
iYear = model.getProperties().getProperty("Data.Year");
iTerm = model.getProperties().getProperty("Data.Term");
}
public void load() throws Exception {
Session session = Session.getSessionUsingInitiativeYearTerm(iInitiative, iYear, iTerm);
if (session==null) throw new Exception("Session "+iInitiative+" "+iTerm+iYear+" not found!");
load(session);
}
private static String getInstructorIds(Class_ clazz) {
if (!clazz.isDisplayInstructor().booleanValue()) return null;
String ret = null;
TreeSet ts = new TreeSet(clazz.getClassInstructors());
for (Iterator i=ts.iterator();i.hasNext();) {
ClassInstructor ci = (ClassInstructor)i.next();
if (!ci.isLead().booleanValue()) continue;
if (ret==null)
ret = ci.getInstructor().getUniqueId().toString();
else
ret += ":"+ci.getInstructor().getUniqueId().toString();
}
return ret;
}
private static String getInstructorNames(Class_ clazz) {
if (!clazz.isDisplayInstructor().booleanValue()) return null;
String ret = null;
TreeSet ts = new TreeSet(clazz.getClassInstructors());
for (Iterator i=ts.iterator();i.hasNext();) {
ClassInstructor ci = (ClassInstructor)i.next();
if (!ci.isLead().booleanValue()) continue;
if (ret==null)
ret = ci.getInstructor().nameShort();
else
ret += ":"+ci.getInstructor().nameShort();
}
return ret;
}
private static Offering loadOffering(InstructionalOffering io, Hashtable courseTable, Hashtable classTable) {
sLog.debug("Loading offering "+io.getCourseName());
if (!io.hasClasses()) {
sLog.debug(" -- offering "+io.getCourseName()+" has no class");
return null;
}
Offering offering = new Offering(io.getUniqueId().longValue(), io.getCourseName());
for (Iterator i=io.getCourseOfferings().iterator();i.hasNext();) {
CourseOffering co = (CourseOffering)i.next();
int projected = (co.getProjectedDemand()==null?0:co.getProjectedDemand().intValue());
int limit = co.getInstructionalOffering().getLimit().intValue();
for (Iterator j=co.getInstructionalOffering().getCourseReservations().iterator();j.hasNext();) {
CourseOfferingReservation reservation = (CourseOfferingReservation)j.next();
if (reservation.getCourseOffering().equals(co) && reservation.getReserved()!=null)
limit = reservation.getReserved().intValue();
}
Course course = new Course(co.getUniqueId().longValue(), co.getSubjectAreaAbbv(), co.getCourseNbr(), offering, limit, projected);
courseTable.put(co.getUniqueId(), course);
sLog.debug(" -- created course "+course);
}
Hashtable class2section = new Hashtable();
Hashtable ss2subpart = new Hashtable();
for (Iterator i=io.getInstrOfferingConfigs().iterator();i.hasNext();) {
InstrOfferingConfig ioc = (InstrOfferingConfig)i.next();
if (!ioc.hasClasses()) {
sLog.debug(" -- config "+ioc.getName()+" has no class");
continue;
}
Config config = new Config(ioc.getUniqueId().longValue(), ioc.getCourseName()+" ["+ioc.getName()+"]", offering);
sLog.debug(" -- created config "+config);
TreeSet subparts = new TreeSet(new SchedulingSubpartComparator());
subparts.addAll(ioc.getSchedulingSubparts());
for (Iterator j=subparts.iterator();j.hasNext();) {
SchedulingSubpart ss = (SchedulingSubpart)j.next();
String sufix = ss.getSchedulingSubpartSuffix();
Subpart parentSubpart = (ss.getParentSubpart()==null?null:(Subpart)ss2subpart.get(ss.getParentSubpart()));
if (ss.getParentSubpart()!=null && parentSubpart==null) {
sLog.error(" -- subpart "+ss.getSchedulingSubpartLabel()+" has parent "+ss.getParentSubpart().getSchedulingSubpartLabel()+", but the appropriate parent subpart is not loaded.");
}
Subpart subpart = new Subpart(ss.getUniqueId().longValue(), ss.getItype().getItype().toString()+sufix, ss.getItypeDesc().trim()+(sufix==null || sufix.length()==0?"":" ("+sufix+")"), config, parentSubpart);
ss2subpart.put(ss, subpart);
sLog.debug(" -- created subpart "+subpart);
for (Iterator k=ss.getClasses().iterator();k.hasNext();) {
Class_ c = (Class_)k.next();
Assignment a = c.getCommittedAssignment();
int limit = c.getClassLimit();
if (ioc.isUnlimitedEnrollment().booleanValue()) limit = -1;
Section parentSection = (c.getParentClass()==null?null:(Section)class2section.get(c.getParentClass()));
if (c.getParentClass()!=null && parentSection==null) {
sLog.error(" -- class "+c.getClassLabel()+" has parent "+c.getParentClass().getClassLabel()+", but the appropriate parent section is not loaded.");
}
Section section = new Section(c.getUniqueId().longValue(), limit, c.getClassLabel(), subpart, (a==null?null:a.getPlacement()), getInstructorIds(c), getInstructorNames(c), parentSection);
if (section.getTime()!=null && section.getTime().getDatePatternId().equals(c.getSession().getDefaultDatePattern().getUniqueId()))
section.getTime().setDatePattern(section.getTime().getDatePatternId(),"",section.getTime().getWeekCode());
class2section.put(c, section);
classTable.put(c.getUniqueId(), section);
sLog.debug(" -- created section "+section);
}
}
}
return offering;
}
public static Student loadStudent(org.unitime.timetable.model.Student s, Hashtable courseTable, Hashtable classTable) {
sLog.debug("Loading student "+s.getUniqueId()+" (id="+s.getExternalUniqueId()+", name="+s.getFirstName()+" "+s.getMiddleName()+" "+s.getLastName()+")");
Student student = new Student(s.getUniqueId().longValue());
loadStudentInfo(student,s);
int priority = 0;
for (Iterator i=new TreeSet(s.getCourseDemands()).iterator();i.hasNext();) {
CourseDemand cd = (CourseDemand)i.next();
if (cd.getFreeTime()!=null) {
Request request = new FreeTimeRequest(
cd.getUniqueId().longValue(),
priority++,
cd.isAlternative().booleanValue(),
student,
new TimeLocation(
cd.getFreeTime().getDayCode().intValue(),
cd.getFreeTime().getStartSlot().intValue(),
cd.getFreeTime().getLength().intValue(),
0, 0,
s.getSession().getDefaultDatePattern().getUniqueId(),
"",
s.getSession().getDefaultDatePattern().getPatternBitSet(),
0)
);
sLog.debug(" -- added request "+request);
} else if (!cd.getCourseRequests().isEmpty()) {
Vector courses = new Vector();
HashSet selChoices = new HashSet();
HashSet wlChoices = new HashSet();
HashSet assignedSections = new HashSet();
Config assignedConfig = null;
for (Iterator j=new TreeSet(cd.getCourseRequests()).iterator();j.hasNext();) {
org.unitime.timetable.model.CourseRequest cr = (org.unitime.timetable.model.CourseRequest)j.next();
Course course = (Course)courseTable.get(cr.getCourseOffering().getUniqueId());
if (course==null) {
sLog.warn(" -- course "+cr.getCourseOffering().getCourseName()+" not loaded");
continue;
}
for (Iterator k=cr.getClassWaitLists().iterator();k.hasNext();) {
ClassWaitList cwl = (ClassWaitList)k.next();
Section section = course.getOffering().getSection(cwl.getClazz().getUniqueId().longValue());
if (section!=null) {
if (cwl.getType().equals(ClassWaitList.TYPE_SELECTION))
selChoices.add(section.getChoice());
else if (cwl.getType().equals(ClassWaitList.TYPE_WAITLIST))
wlChoices.add(section.getChoice());
}
}
if (assignedConfig==null) {
for (Iterator k=cr.getClassEnrollments().iterator();k.hasNext();) {
StudentClassEnrollment sce = (StudentClassEnrollment)k.next();
Section section = course.getOffering().getSection(sce.getClazz().getUniqueId().longValue());
if (section!=null) {
assignedSections.add(section);
assignedConfig = section.getSubpart().getConfig();
}
}
}
courses.addElement(course);
}
if (courses.isEmpty()) continue;
CourseRequest request = new CourseRequest(
cd.getUniqueId().longValue(),
priority++,
cd.isAlternative().booleanValue(),
student,
courses,
cd.isWaitlist().booleanValue());
request.getSelectedChoices().addAll(selChoices);
request.getWaitlistedChoices().addAll(wlChoices);
if (assignedConfig!=null && assignedSections.size()==assignedConfig.getSubparts().size()) {
Enrollment enrollment = new Enrollment(request, 0, assignedConfig, assignedSections);
request.setInitialAssignment(enrollment);
}
sLog.debug(" -- added request "+request);
} else {
sLog.warn(" -- course demand "+cd.getUniqueId()+" has no course requests");
}
}
return student;
}
public static double getLastLikeStudentWeight(Course course, Hashtable demands) {
int projected = course.getProjected();
int limit = course.getLimit();
if (projected<=0) {
sLog.warn(" -- No projected demand for course "+course.getName()+", using course limit ("+limit+")");
projected = limit;
} else if (limit<projected) {
sLog.warn(" -- Projected number of students is over course limit for course "+course.getName()+" ("+Math.round(projected)+">"+limit+")");
projected = limit;
}
Number lastLike = (Number)demands.get(new Long(course.getId()));
if (lastLike==null) {
sLog.warn(" -- No last like info for course "+course.getName());
return 1.0;
}
double weight = ((double)projected) / lastLike.doubleValue();
sLog.debug(" -- last like student weight for "+course.getName()+" is "+weight+" (lastLike="+Math.round(lastLike.doubleValue())+", projected="+projected+")");
return weight;
}
public static void loadLastLikeStudent(org.hibernate.Session hibSession, LastLikeCourseDemand d, org.unitime.timetable.model.Student s, CourseOffering co, Hashtable studentTable, Hashtable courseTable, Hashtable classTable, Hashtable demands, Hashtable classAssignments) {
sLog.debug("Loading last like demand of student "+s.getUniqueId()+" (id="+s.getExternalUniqueId()+", name="+s.getFirstName()+" "+s.getMiddleName()+" "+s.getLastName()+") for "+co.getCourseName());
Student student = (Student)studentTable.get(s.getUniqueId());
if (student==null) {
student = new Student(s.getUniqueId().longValue(),true);
loadStudentInfo(student,s);
studentTable.put(s.getUniqueId(),student);
}
int priority = student.getRequests().size();
Vector courses = new Vector();
Course course = (Course)courseTable.get(co.getUniqueId());
if (course==null) {
sLog.warn(" -- course "+co.getCourseName()+" not loaded");
return;
}
courses.addElement(course);
CourseRequest request = new CourseRequest(
d.getUniqueId().longValue(),
priority++,
false,
student,
courses,
false);
request.setWeight(getLastLikeStudentWeight(course, demands));
sLog.debug(" -- added request "+request);
if (classAssignments!=null && !classAssignments.isEmpty()) {
HashSet assignedSections = new HashSet();
HashSet classIds = (HashSet)classAssignments.get(s.getUniqueId());
if (classIds!=null)
for (Iterator i=classIds.iterator();i.hasNext();) {
Long classId = (Long)i.next();
Section section = (Section)request.getSection(classId.longValue());
if (section!=null) assignedSections.add(section);
}
if (!assignedSections.isEmpty()) {
sLog.debug(" -- committed assignment: "+assignedSections);
for (Enumeration e=request.values().elements();e.hasMoreElements();) {
Enrollment enrollment = (Enrollment)e.nextElement();
if (enrollment.getAssignments().containsAll(assignedSections)) {
request.setInitialAssignment(enrollment);
sLog.debug(" -- found: "+enrollment);
break;
}
}
}
}
}
public static void loadStudentInfo(Student student, org.unitime.timetable.model.Student s) {
for (Iterator i=s.getAcademicAreaClassifications().iterator();i.hasNext();) {
AcademicAreaClassification aac = (AcademicAreaClassification)i.next();
student.getAcademicAreaClasiffications().add(aac.getAcademicArea().getAcademicAreaAbbreviation()+":"+aac.getAcademicClassification().getCode());
sLog.debug(" -- aac: "+aac.getAcademicArea().getAcademicAreaAbbreviation()+":"+aac.getAcademicClassification().getCode());
}
for (Iterator i=s.getPosMajors().iterator();i.hasNext();) {
PosMajor major = (PosMajor)i.next();
student.getMajors().add(major.getCode());
sLog.debug(" -- mj: "+major.getCode());
}
}
public void load(Session session) {
org.hibernate.Session hibSession = new SessionDAO().getSession();
Transaction tx = hibSession.beginTransaction();
try {
Hashtable courseTable = new Hashtable();
Hashtable classTable = new Hashtable();
List offerings = hibSession.createQuery(
"select distinct io from InstructionalOffering io " +
"left join fetch io.courseOfferings as co "+
"left join fetch io.instrOfferingConfigs as ioc "+
"left join fetch ioc.schedulingSubparts as ss "+
"left join fetch ss.classes as c "+
"where " +
"io.session.uniqueId=:sessionId and io.notOffered=false").
setLong("sessionId",session.getUniqueId().longValue()).
setFetchSize(1000).list();
for (Iterator i=offerings.iterator();i.hasNext();) {
InstructionalOffering io = (InstructionalOffering)i.next();
Offering offering = loadOffering(io, courseTable, classTable);
if (offering!=null) getModel().addOffering(offering);
}
HashSet loadedStudentIds = new HashSet();
if (iIncludeCourseDemands) {
List students = hibSession.createQuery(
"select distinct s from Student s " +
"left join fetch s.courseDemands as cd "+
"left join fetch cd.courseRequests as cr "+
"where s.session.uniqueId=:sessionId").
setLong("sessionId",session.getUniqueId().longValue()).
setFetchSize(1000).list();
for (Iterator i=students.iterator();i.hasNext();) {
org.unitime.timetable.model.Student s = (org.unitime.timetable.model.Student)i.next();
if (s.getCourseDemands().isEmpty()) continue;
Student student = loadStudent(s, courseTable, classTable);
if (student!=null)
getModel().addStudent(student);
if (s.getExternalUniqueId()!=null)
loadedStudentIds.add(s.getExternalUniqueId());
}
}
if (iIncludeLastLikeStudents) {
Hashtable demands = new Hashtable();
for (Iterator i=hibSession.createQuery("select co.uniqueId, count(d.uniqueId) from "+
"CourseOffering co left join co.demandOffering cx, LastLikeCourseDemand d where co.subjectArea.session.uniqueId=:sessionId and "+
"(( d.subjectArea=co.subjectArea and d.courseNbr=co.courseNbr ) or "+
" ( d.subjectArea=cx.subjectArea and d.courseNbr=cx.courseNbr )) "+
"group by co.uniqueId").setLong("sessionId",session.getUniqueId().longValue()).iterate();i.hasNext();) {
Object[] o = (Object[])i.next();
Long courceOfferingId = (Long)o[0];
Number demand = (Number)o[1];
demands.put(courceOfferingId, demand);
}
Hashtable classAssignments = null;
if (iIncludeUseCommittedAssignments) {
classAssignments = new Hashtable();
for (Iterator i=hibSession.createQuery("select distinct se.studentId, se.clazz.uniqueId from StudentEnrollment se where "+
"se.solution.commited=true and se.solution.owner.session.uniqueId=:sessionId").
setLong("sessionId",session.getUniqueId().longValue()).iterate();i.hasNext();) {
Object[] o = (Object[])i.next();
Long studentId = (Long)o[0];
Long classId = (Long)o[1];
HashSet classIds = (HashSet)classAssignments.get(studentId);
if (classIds==null) {
classIds = new HashSet();
classAssignments.put(studentId, classIds);
}
classIds.add(classId);
}
}
Hashtable lastLikeStudentTable = new Hashtable();
for (Iterator i=hibSession.createQuery(
"select d, s, c from LastLikeCourseDemand d inner join d.student s, CourseOffering c left join c.demandOffering cx " +
"where d.subjectArea.session.uniqueId=:sessionId and " +
"((d.subjectArea=c.subjectArea and d.courseNbr=c.courseNbr ) or "+
" (d.subjectArea=cx.subjectArea and d.courseNbr=cx.courseNbr)) "+
"order by s.uniqueId, d.priority, d.uniqueId").
setLong("sessionId",session.getUniqueId().longValue()).iterate();i.hasNext();) {
Object[] o = (Object[])i.next();
LastLikeCourseDemand d = (LastLikeCourseDemand)o[0];
org.unitime.timetable.model.Student s = (org.unitime.timetable.model.Student)o[1];
CourseOffering co = (CourseOffering)o[2];
if (s.getExternalUniqueId()!=null && loadedStudentIds.contains(s.getExternalUniqueId())) continue;
loadLastLikeStudent(hibSession, d, s, co, lastLikeStudentTable, courseTable, classTable, demands, classAssignments);
}
for (Enumeration e=lastLikeStudentTable.elements();e.hasMoreElements();) {
Student student = (Student)e.nextElement();
getModel().addStudent(student);
}
if (classAssignments!=null && !classAssignments.isEmpty()) {
for (Enumeration e=getModel().variables().elements();e.hasMoreElements();) {
Request request = (Request)e.nextElement();
if (request.getInitialAssignment()==null) continue;
Set conflicts = getModel().conflictValues(request.getInitialAssignment());
if (conflicts.isEmpty())
request.assign(0, request.getInitialAssignment());
else
sLog.debug("Unable to assign "+request.getInitialAssignment()+", conflicts: "+conflicts);
}
}
}
tx.commit();
} catch (Exception e) {
tx.rollback();
throw new RuntimeException(e);
} finally {
hibSession.close();
}
}
}
|
package com.kinancity.core.proxy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.Getter;
import lombok.Setter;
import com.kinancity.core.proxy.policies.UnlimitedUsePolicy;
/**
* Manager that holds a set of proxies
*
* TODO : implement better proxy rotation
*
* @author drallieiv
*
*/
public class ProxyManager {
private Logger logger = LoggerFactory.getLogger(getClass());
@Getter
// How much time should we retry getting a proxy if none are found. in ms
private long pollingRate = 30000;
@Getter
// List of possible proxy instances
private List<ProxyInfo> proxies = new ArrayList<>();
/**
* Move here the proxies which failed
*/
@Getter
private List<ProxyInfo> proxyBench = new ArrayList<>();
@Setter
@Getter
private ProxyRecycler recycler;
private boolean proxyRotation = true;
/**
* Add a new proxy possibility
*
* @param proxy
*/
public void addProxy(ProxyInfo proxy) {
this.proxies.add(proxy);
}
// Gives a proxy that can be used
public synchronized Optional<ProxySlot> getEligibleProxy() {
Optional<ProxyInfo> proxyInfoResult = proxies.stream().filter(pi -> pi.isAvailable()).findFirst();
ProxyInfo proxyInfo = null;
if (proxyInfoResult.isPresent()) {
proxyInfo = proxyInfoResult.get();
Optional<ProxySlot> slot = proxyInfo.getFreeSlot();
// Reorder the proxy list to start after the found one
if (proxyRotation) {
Collections.rotate(proxies, -proxies.indexOf(proxyInfo) + 1);
}
return slot;
}
return Optional.empty();
}
public void benchProxy(ProxyInfo proxy) {
if (!(proxy.getProxyPolicy() instanceof UnlimitedUsePolicy) && proxies.contains(proxy) && !proxyBench.contains(proxy)) {
proxies.remove(proxy);
proxyBench.add(proxy);
logger.warn("Proxy [{}] moved out of rotation, {} proxy left",proxy, proxies.size());
if(recycler != null && getNbProxyInRotation() == 0){
recycler.setFastMode(true);
recycler.checkAndRecycleAllBenched();
}
}
}
public int getNbProxyInRotation(){
return proxies.size();
}
public int getNbProxyBenched(){
return proxyBench.size();
}
}
|
package com.nlbhub.nlb.domain.export;
import com.nlbhub.nlb.api.Constants;
import com.nlbhub.nlb.api.Obj;
import com.nlbhub.nlb.api.TextChunk;
import com.nlbhub.nlb.api.Theme;
import com.nlbhub.nlb.domain.NonLinearBookImpl;
import com.nlbhub.nlb.exception.NLBExportException;
import com.nlbhub.nlb.util.StringHelper;
import org.jetbrains.annotations.NotNull;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The STEADExportManager class
*
* @author Anton P. Kolosov
* @version 1.0 12/10/13
*/
public class STEADExportManager extends TextExportManager {
private static final String GLOBAL_VAR_PREFIX = "_";
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
private static final Pattern STEAD_OBJ_PATTERN = Pattern.compile("\\{(.*)\\}");
/**
* Enable comments in the generated text
*/
private static final boolean ENABLE_COMMENTS = true;
private boolean m_technicalInstance = false;
private STEADExportManager m_vnsteadExportManager;
public STEADExportManager(NonLinearBookImpl nlb, String encoding) throws NLBExportException {
super(nlb, encoding);
m_vnsteadExportManager = new VNSTEADExportManager(nlb, encoding, true);
}
public STEADExportManager(NonLinearBookImpl nlb, String encoding, boolean technicalInstance) throws NLBExportException {
super(nlb, encoding);
m_technicalInstance = technicalInstance;
m_vnsteadExportManager = null;
}
protected boolean isVN(Theme theme) {
return !m_technicalInstance && theme == Theme.VN;
}
@Override
protected String generatePreambleText(NLBBuildingBlocks nlbBuildingBlocks) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(getGameFileHeader(nlbBuildingBlocks));
stringBuilder.append("--package.cpath = './?.so'").append(LINE_SEPARATOR);
stringBuilder.append("require 'luapassing'").append(LINE_SEPARATOR).append(LINE_SEPARATOR);
stringBuilder.append("require 'prefs'").append(LINE_SEPARATOR);
stringBuilder.append("require 'xact'").append(LINE_SEPARATOR);
stringBuilder.append("require 'nouse'").append(LINE_SEPARATOR);
stringBuilder.append("require 'hideinv'").append(LINE_SEPARATOR);
stringBuilder.append("--require 'para'").append(LINE_SEPARATOR);
stringBuilder.append("require 'dash'").append(LINE_SEPARATOR);
String lang = nlbBuildingBlocks.getLang();
if (Constants.RU.equalsIgnoreCase(lang)) {
// quotes module should be used only for russian language
stringBuilder.append("require 'quotes'").append(LINE_SEPARATOR);
}
stringBuilder.append("require 'theme'").append(LINE_SEPARATOR);
stringBuilder.append("require 'timer'").append(LINE_SEPARATOR);
stringBuilder.append("require 'modules/nlb'").append(LINE_SEPARATOR);
stringBuilder.append("require 'modules/fonts'").append(LINE_SEPARATOR);
stringBuilder.append("require 'modules/paginator'").append(LINE_SEPARATOR);
stringBuilder.append("require 'modules/vn'").append(LINE_SEPARATOR);
stringBuilder.append("require 'modules/gobj'").append(LINE_SEPARATOR);
stringBuilder.append("require 'dice/modules/big_pig'").append(LINE_SEPARATOR);
stringBuilder.append("game.codepage='UTF-8';").append(LINE_SEPARATOR);
stringBuilder.append("stead.scene_delim = '^';").append(LINE_SEPARATOR);
stringBuilder.append(LINE_SEPARATOR);
if (StringHelper.isEmpty(nlbBuildingBlocks.getGameActText())) {
stringBuilder.append("game.act = function() return true; end;").append(LINE_SEPARATOR);
} else {
stringBuilder.append("game.act = function() nlb:curloc().lasttext = '").append(nlbBuildingBlocks.getGameActText()).append("'; p(nlb:curloc().lasttext); nlb:curloc().wastext = true; end;").append(LINE_SEPARATOR);
}
if (StringHelper.isEmpty(nlbBuildingBlocks.getGameInvText())) {
stringBuilder.append("game.inv = function() return true; end;").append(LINE_SEPARATOR);
} else {
stringBuilder.append("game.inv = function() nlb:curloc().lasttext = '").append(nlbBuildingBlocks.getGameInvText()).append("'; p(nlb:curloc().lasttext); nlb:curloc().wastext = true; end;").append(LINE_SEPARATOR);
}
if (StringHelper.isEmpty(nlbBuildingBlocks.getGameNouseText())) {
stringBuilder.append("game.nouse = function() return true; end;").append(LINE_SEPARATOR);
} else {
stringBuilder.append("game.nouse = function() nlb:curloc().lasttext = '").append(nlbBuildingBlocks.getGameNouseText()).append("'; p(nlb:curloc().lasttext); nlb:curloc().wastext = true; end;").append(LINE_SEPARATOR);
}
stringBuilder.append("game.forcedsc = ").append(String.valueOf(nlbBuildingBlocks.isGameForcedsc())).append(";").append(LINE_SEPARATOR);
stringBuilder.append("f1 = font(nlb:theme_root() .. 'fonts/STEINEMU.ttf', 32);").append(LINE_SEPARATOR);
stringBuilder.append("fend = font(nlb:theme_root() .. 'fonts/STEINEMU.ttf', 96);").append(LINE_SEPARATOR);
stringBuilder.append("function pname(n, c)").append(LINE_SEPARATOR);
stringBuilder.append(" return function()").append(LINE_SEPARATOR);
stringBuilder.append(" pn(img 'blank:8x1',f1:txt(n, c, 1))").append(LINE_SEPARATOR);
stringBuilder.append(" end").append(LINE_SEPARATOR);
stringBuilder.append("end").append(LINE_SEPARATOR);
stringBuilder.append("paginator.delim = '\\n[ \\t]*\\n'").append(LINE_SEPARATOR);
stringBuilder.append("function exec(s)").append(LINE_SEPARATOR);
stringBuilder.append(" p('$'..s:gsub('\\n', '^')..'$^^')").append(LINE_SEPARATOR);
stringBuilder.append("end").append(LINE_SEPARATOR);
stringBuilder.append("function init()").append(LINE_SEPARATOR);
stringBuilder.append(" statsAPI.init();").append(LINE_SEPARATOR);
stringBuilder.append(" if dice then").append(LINE_SEPARATOR);
stringBuilder.append(" paginator:set_onproceed(function()").append(LINE_SEPARATOR);
stringBuilder.append(" dice:hide(true);").append(LINE_SEPARATOR);
stringBuilder.append(" -- Use code below if you want smooth rollout animation and text change on next step").append(LINE_SEPARATOR);
stringBuilder.append(" --if dice:hide() then").append(LINE_SEPARATOR);
stringBuilder.append(" -- return").append(LINE_SEPARATOR);
stringBuilder.append(" --end").append(LINE_SEPARATOR);
stringBuilder.append(" end);").append(LINE_SEPARATOR);
stringBuilder.append(" end").append(LINE_SEPARATOR);
stringBuilder.append(getThemeInit());
stringBuilder.append(" vn:scene(nil);").append(LINE_SEPARATOR);
stringBuilder.append(" vn.fading = 8").append(LINE_SEPARATOR);
stringBuilder.append(" nlbticks = stead.ticks();").append(LINE_SEPARATOR);
stringBuilder.append(generateVarsInitBlock(nlbBuildingBlocks));
stringBuilder.append("end").append(LINE_SEPARATOR);
stringBuilder.append(generateSysObjectsBlock(nlbBuildingBlocks));
return stringBuilder.toString();
}
protected String getThemeInit() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" if vn:in_vnr() then").append(getLineSeparator());
stringBuilder.append(" vn:turnoff();").append(getLineSeparator()); // Needed for dofile("theme_vn.lua"), because otherwise it will not switch the theme
stringBuilder.append(" nlb:theme_switch(\"theme_vn.lua\");").append(getLineSeparator()); // Reset theme to VN (default is non-VN)
stringBuilder.append(" else").append(getLineSeparator());
stringBuilder.append(" vn:turnon();").append(getLineSeparator()); // Needed for dofile("theme_standard.lua"), because otherwise it will not switch the theme
stringBuilder.append(" nlb:theme_switch(\"theme_standard.lua\");").append(getLineSeparator()); // Reset theme to non-VN
stringBuilder.append(" end").append(getLineSeparator());
return stringBuilder.toString();
}
protected String generateSysObjectsBlock(NLBBuildingBlocks nlbBuildingBlocks) {
String version = StringHelper.notEmpty(nlbBuildingBlocks.getVersion()) ? nlbBuildingBlocks.getVersion() : "0.1";
StringBuilder result = new StringBuilder();
result.append(LINE_SEPARATOR).append("_version_obj = gobj {").append(LINE_SEPARATOR)
.append(" nam = 'version_obj',").append(LINE_SEPARATOR)
.append(" system_type = true,").append(LINE_SEPARATOR)
.append(" pic = 'gfx/version.png',").append(LINE_SEPARATOR)
.append(" txtfn = function(s) return { [1] = {['text'] = '").append(version).append("', ['color'] = 'white' } }; end,").append(LINE_SEPARATOR)
.append(" eff = 'left-top@0,0',").append(LINE_SEPARATOR)
.append(" iarm = {[0] = {0, 16}}").append(LINE_SEPARATOR)
.append(LINE_SEPARATOR).append("}")
.append(LINE_SEPARATOR);
return result.toString();
}
protected String getGameFileHeader(NLBBuildingBlocks nlbBuildingBlocks) {
StringBuilder result = new StringBuilder();
String title = StringHelper.notEmpty(nlbBuildingBlocks.getTitle()) ? nlbBuildingBlocks.getTitle() : "NLBB_" + new Date().toString();
String version = StringHelper.notEmpty(nlbBuildingBlocks.getVersion()) ? nlbBuildingBlocks.getVersion() : "0.1";
String author = StringHelper.notEmpty(nlbBuildingBlocks.getAuthor()) ? nlbBuildingBlocks.getAuthor() : "Unknown";
result.append("--$Name:").append(title).append("$").append(LINE_SEPARATOR);
result.append("
result.append("
result.append("instead_version '2.3.0'").append(LINE_SEPARATOR).append(LINE_SEPARATOR);
return result.toString();
}
protected String generateVarsInitBlock(NLBBuildingBlocks nlbBuildingBlocks) {
StringBuilder stringBuilder = new StringBuilder();
String lang = nlbBuildingBlocks.getLang();
stringBuilder.append(" _export_lang = '").append(lang).append("';").append(LINE_SEPARATOR);
stringBuilder.append(" _syscall_showmenubtn:act();").append(LINE_SEPARATOR);
if (Constants.RU.equalsIgnoreCase(lang)) {
stringBuilder.append(" format.quotes = true;").append(LINE_SEPARATOR);
} else {
stringBuilder.append(" format.quotes = false;").append(LINE_SEPARATOR);
}
stringBuilder.append(" if not prefs.achievements then").append(LINE_SEPARATOR);
stringBuilder.append(" prefs.achievements = {};").append(LINE_SEPARATOR);
stringBuilder.append(" end").append(LINE_SEPARATOR);
stringBuilder.append(initBlockAchievements(nlbBuildingBlocks));
String perfectGame = nlbBuildingBlocks.getAchievementNamePerfectGame();
if (StringHelper.notEmpty(perfectGame)) {
String achievementItemPerfectGame = "prefs.achievements['" + perfectGame + "']";
stringBuilder.append(" if not ").append(achievementItemPerfectGame).append(" then ").append(achievementItemPerfectGame).append(" = 0; end;").append(LINE_SEPARATOR);
stringBuilder.append(" if not prefs.achievementNamePerfectGame then prefs.achievementNamePerfectGame = '").append(perfectGame).append("'; end;").append(LINE_SEPARATOR);
}
stringBuilder.append(" prefs:store();").append(LINE_SEPARATOR);
stringBuilder.append(" nlb:resendAchievements(statsAPI);").append(LINE_SEPARATOR);
return stringBuilder.toString();
}
private String initBlockAchievements(NLBBuildingBlocks nlbBuildingBlocks) {
StringBuilder stringBuilder = new StringBuilder();
for (String achievement : nlbBuildingBlocks.getAchievements()) {
String achievementItem = "prefs.achievements['" + achievement + "']";
stringBuilder.append(" if not ").append(achievementItem).append(" then ").append(achievementItem).append(" = 0; end;").append(LINE_SEPARATOR);
}
return stringBuilder.toString();
}
private String getContainerExpression(String containerRef) {
if (NO_CONTAINER.equals(containerRef)) {
return "container = " + NO_CONTAINER + ";";
} else {
return "container = " + containerRef + ";";
}
}
@Override
protected String generateObjText(ObjBuildingBlocks objBlocks) {
StringBuilder stringBuilder = new StringBuilder();
if (ENABLE_COMMENTS) {
stringBuilder.append(objBlocks.getObjComment());
}
stringBuilder.append(objBlocks.getObjLabel()).append(objBlocks.getObjStart());
stringBuilder.append(objBlocks.getObjName());
stringBuilder.append(objBlocks.getObjEffect());
stringBuilder.append(objBlocks.getMorphOver());
stringBuilder.append(objBlocks.getMorphOut());
stringBuilder.append(objBlocks.getObjArm());
stringBuilder.append(objBlocks.getObjSound());
stringBuilder.append(objBlocks.getObjDisp());
stringBuilder.append(objBlocks.getObjText());
if (objBlocks.isTakable()) {
stringBuilder.append(objBlocks.getObjTak());
stringBuilder.append(objBlocks.getObjInv());
}
stringBuilder.append(objBlocks.getObjConstraint());
stringBuilder.append(objBlocks.getObjActStart());
boolean varsOrModsPresent = (
StringHelper.notEmpty(objBlocks.getObjVariable())
|| StringHelper.notEmpty(objBlocks.getObjModifications())
);
if (varsOrModsPresent) {
stringBuilder.append(objBlocks.getObjModifications());
stringBuilder.append(objBlocks.getObjVariable());
}
stringBuilder.append(objBlocks.getObjActEnd());
List<UseBuildingBlocks> usesBuildingBlocks = objBlocks.getUseBuildingBlocks();
final boolean hasUses = usesBuildingBlocks.size() != 0;
if (!objBlocks.isTakable() && hasUses) {
// Not takable but usable => scene_use should be specified
stringBuilder.append(" scene_use = true,").append(LINE_SEPARATOR);
}
stringBuilder.append(objBlocks.getObjImage());
stringBuilder.append(objBlocks.getObjPreload());
if (hasUses) {
stringBuilder.append(objBlocks.getObjUseStart());
}
if (hasUses) {
StringBuilder usepBuilder = new StringBuilder();
usepBuilder.append(" usep = function(s, w, ww)").append(LINE_SEPARATOR);
usepBuilder.append(" local prevt = nlb:curloc().lasttext;").append(LINE_SEPARATOR);
usepBuilder.append(" local wasnouses = true;").append(LINE_SEPARATOR);
usepBuilder.append(" nlb:curloc().lasttext = \"\";").append(LINE_SEPARATOR);
for (int i = 0; i < usesBuildingBlocks.size(); i++) {
StringBuilder usesStartBuilder = new StringBuilder();
StringBuilder usesEndBuilder = new StringBuilder();
UseBuildingBlocks useBuildingBlocks = usesBuildingBlocks.get(i);
String padding = " ";
if (i == 0) {
usesStartBuilder.append(padding).append("if ");
usesStartBuilder.append(useBuildingBlocks.getUseTarget());
usesStartBuilder.append(" then").append(LINE_SEPARATOR);
} else {
usesStartBuilder.append(padding).append("end;").append(LINE_SEPARATOR);
usesStartBuilder.append(padding).append("if ").append(LINE_SEPARATOR);
usesStartBuilder.append(useBuildingBlocks.getUseTarget());
usesStartBuilder.append(" then").append(LINE_SEPARATOR);
}
final boolean constrained = !StringHelper.isEmpty(useBuildingBlocks.getUseConstraint());
String extraPadding = constrained ? " " : "";
if (constrained) {
usesStartBuilder.append(padding).append(" if ").append(useBuildingBlocks.getUseConstraint());
usesStartBuilder.append(" then").append(LINE_SEPARATOR);
}
stringBuilder.append(usesStartBuilder).append(padding).append(extraPadding);
stringBuilder.append(useBuildingBlocks.getUseModifications()).append(LINE_SEPARATOR);
//stringBuilder.append(padding).append(extraPadding);
stringBuilder.append(useBuildingBlocks.getUseVariable()).append(LINE_SEPARATOR);
/*
INSTEAD handles changes in variables automatically. Therefore it is not needed to walk to the current
room again in order to reflect changes in the variables.
*/
if (constrained) {
usesEndBuilder.append(padding).append(" end;").append(LINE_SEPARATOR);
stringBuilder.append(usesEndBuilder);
}
usepBuilder.append(usesStartBuilder);
String useSuccessText = useBuildingBlocks.getUseSuccessText();
String useFailureText = useBuildingBlocks.getUseFailureText();
if (StringHelper.notEmpty(useSuccessText)) {
usepBuilder.append("local t = \"").append(useSuccessText).append(" \"; nlb:curloc().lasttext = nlb:lasttext()..t; p(t); nlb:curloc().wastext = true; wasnouses = false;").append(LINE_SEPARATOR);
if (StringHelper.notEmpty(useFailureText)) {
usepBuilder.append(padding).append(" else").append(LINE_SEPARATOR);
usepBuilder.append("local t = \"").append(useFailureText).append(" \"; nlb:curloc().lasttext = nlb:lasttext()..t; p(t); nlb:curloc().wastext = true; wasnouses = false;").append(LINE_SEPARATOR);
}
}
usepBuilder.append(usesEndBuilder);
}
usepBuilder.append(" if wasnouses then nlb:curloc().lasttext = prevt; end;").append(LINE_SEPARATOR);
usepBuilder.append(" end;").append(LINE_SEPARATOR);
usepBuilder.append(" return not wasnouses;").append(LINE_SEPARATOR);
usepBuilder.append(objBlocks.getObjUseEnd());
stringBuilder.append(" end;").append(LINE_SEPARATOR);
stringBuilder.append(" if w.useda ~= nil then").append(LINE_SEPARATOR);
stringBuilder.append(" w.useda(w, s, s);").append(LINE_SEPARATOR);
stringBuilder.append(" end;").append(LINE_SEPARATOR);
stringBuilder.append(objBlocks.getObjUseEnd());
stringBuilder.append(usepBuilder);
}
stringBuilder.append(objBlocks.getObjNouse());
List<String> containedObjIds = objBlocks.getContainedObjIds();
if (containedObjIds.size() != 0) {
stringBuilder.append(objBlocks.getObjObjStart());
for (final String objString : containedObjIds) {
stringBuilder.append(objString);
}
stringBuilder.append(objBlocks.getObjObjEnd());
}
stringBuilder.append(objBlocks.getObjEnd());
if (StringHelper.notEmpty(objBlocks.getObjConstraint())) {
stringBuilder.append("lifeon('").append(objBlocks.getObjLabel()).append("');").append(LINE_SEPARATOR);
}
if (StringHelper.notEmpty(objBlocks.getObjAlias())) {
stringBuilder.append(objBlocks.getObjAlias()).append(" = ").append(objBlocks.getObjLabel()).append(LINE_SEPARATOR);
}
return stringBuilder.toString();
}
@Override
protected String generatePageText(PageBuildingBlocks pageBlocks) {
StringBuilder stringBuilder = new StringBuilder();
StringBuilder autosBuilder = new StringBuilder();
if (ENABLE_COMMENTS) {
stringBuilder.append(pageBlocks.getPageComment());
}
stringBuilder.append(pageBlocks.getPageLabel());
// Do not check pageBlocks.isUseCaption() here, because in INSTEAD all rooms must have name
stringBuilder.append(pageBlocks.getPageCaption());
stringBuilder.append(pageBlocks.getNotes());
stringBuilder.append(pageBlocks.getPageImage());
boolean hasAnim = pageBlocks.isHasObjectsWithAnimatedImages();
boolean hasPageAnim = pageBlocks.isHasAnimatedPageImage();
boolean hasFastAnim = hasAnim || hasPageAnim;
boolean timerSet = (hasFastAnim || pageBlocks.isHasPageTimer()) && !pageBlocks.isHasGraphicalObjects();
stringBuilder.append(" var { time = 0; wastext = false; lasttext = nil; tag = '").append(pageBlocks.getPageDefaultTag()).append("'; ");
stringBuilder.append("autowired = ").append(pageBlocks.isAutowired() ? "true" : "false").append("; ");
stringBuilder.append("},").append(LINE_SEPARATOR);
if (timerSet) {
stringBuilder.append(" timer = function(s)").append(LINE_SEPARATOR);
if (hasFastAnim) {
stringBuilder.append(" if (nlb._fps * (get_ticks() - nlbticks) <= 1000) then").append(LINE_SEPARATOR);
stringBuilder.append(" return;").append(LINE_SEPARATOR);
stringBuilder.append(" end").append(LINE_SEPARATOR);
stringBuilder.append(" nlbticks = get_ticks();").append(LINE_SEPARATOR);
}
stringBuilder.append(" if not s.wastext then").append(LINE_SEPARATOR);
stringBuilder.append(" ").append(pageBlocks.getPageTimerVariable()).append(LINE_SEPARATOR);
stringBuilder.append(" end; ").append(LINE_SEPARATOR);
if (hasPageAnim) {
stringBuilder.append(" s.add_gobj(s); ").append(LINE_SEPARATOR);
}
stringBuilder.append(" local afl = s.autos(s); ").append(LINE_SEPARATOR);
stringBuilder.append(" if (s.lasttext ~= nil) and not s.wastext then return s.lasttext; elseif afl and not s.wastext then return true; end; ").append(LINE_SEPARATOR);
stringBuilder.append(" s.wastext = false; ").append(LINE_SEPARATOR);
stringBuilder.append(" end,").append(LINE_SEPARATOR);
}
stringBuilder.append(pageBlocks.getPageTextStart());
autosBuilder.append(" autos = function(s)").append(LINE_SEPARATOR);
autosBuilder.append(" nlb:revive();").append(LINE_SEPARATOR);
autosBuilder.append(" nlb:ways_chk(s);").append(LINE_SEPARATOR);
List<LinkBuildingBlocks> linksBlocks = pageBlocks.getLinksBuildingBlocks();
for (final LinkBuildingBlocks linkBlocks : linksBlocks) {
if (linkBlocks.isAuto()) {
autosBuilder.append(generateAutoLinkCode(linkBlocks));
}
}
autosBuilder.append(" return true;").append(LINE_SEPARATOR);
autosBuilder.append(" end,").append(LINE_SEPARATOR);
boolean varsOrModsPresent = (
!StringHelper.isEmpty(pageBlocks.getPageVariable())
|| !StringHelper.isEmpty(pageBlocks.getPageModifications())
);
stringBuilder.append(generateOrdinaryLinkTextInsideRoom(pageBlocks));
stringBuilder.append(pageBlocks.getPageTextEnd());
stringBuilder.append(autosBuilder.toString());
// TODO: check that here() will not be used in modifications (for example, when automatically taking objects to the inventory)
stringBuilder.append(" nextsnd = function(s)").append(LINE_SEPARATOR);
stringBuilder.append(" local sndfile = nlb:pop('").append(pageBlocks.getPageName()).append("_snds');").append(LINE_SEPARATOR);
stringBuilder.append(" if sndfile ~= nil then").append(LINE_SEPARATOR);
stringBuilder.append(" s.sndout(s);").append(LINE_SEPARATOR);
stringBuilder.append(" add_sound(sndfile);").append(LINE_SEPARATOR);
stringBuilder.append(" end;").append(LINE_SEPARATOR);
stringBuilder.append(" end,").append(LINE_SEPARATOR);
stringBuilder.append(" enter = function(s, f)").append(LINE_SEPARATOR);
stringBuilder.append(" lifeon(s);").append(LINE_SEPARATOR);
if (hasFastAnim) {
stringBuilder.append(" nlbticks = stead.ticks();").append(LINE_SEPARATOR);
}
stringBuilder.append(" s.lasttext = nil;").append(LINE_SEPARATOR);
stringBuilder.append(" s.wastext = false;").append(LINE_SEPARATOR);
if (timerSet) {
stringBuilder.append(" ").append(pageBlocks.getPageTimerVariableInit()).append(LINE_SEPARATOR);
}
if (pageBlocks.getTheme() == Theme.STANDARD) {
stringBuilder.append(" nlb:theme_switch('theme_standard.lua');").append(LINE_SEPARATOR);
} else if (pageBlocks.getTheme() == Theme.VN) {
stringBuilder.append(" nlb:theme_switch('theme_vn.lua');").append(LINE_SEPARATOR);
} else {
stringBuilder.append(getDefaultThemeSwitchExpression());
}
stringBuilder.append(" if not (f.autowired) then").append(LINE_SEPARATOR);
if (varsOrModsPresent) {
stringBuilder.append(pageBlocks.getPageModifications());
stringBuilder.append(pageBlocks.getPageVariable());
}
stringBuilder.append(" end;").append(LINE_SEPARATOR);
stringBuilder.append(" s.snd(s);").append(LINE_SEPARATOR);
stringBuilder.append(generateDirectModeStartText(pageBlocks));
stringBuilder.append(" s.add_gobj(s);").append(LINE_SEPARATOR);
if (timerSet) {
int timerRate = (hasFastAnim ? 1 : 200);
stringBuilder.append(" ").append(pageBlocks.getPageTimerVariable()).append(LINE_SEPARATOR);
// stringBuilder.append(" s.autos(s);").append(LINE_SEPARATOR); -- will be called when timer triggers
// Timer will be triggered first time immediately after timer:set()
stringBuilder.append(" timer:set(").append(timerRate).append(");").append(LINE_SEPARATOR);
} else {
if (!isVN(pageBlocks.getTheme())) {
// if theme is VN, then autos() will be called as a callback in geom() call
stringBuilder.append(" s.autos(s);").append(LINE_SEPARATOR);
}
}
stringBuilder.append(" end,").append(LINE_SEPARATOR);
stringBuilder.append(getGraphicalObjectAppendingExpression(pageBlocks));
stringBuilder.append(" exit = function(s, t)").append(LINE_SEPARATOR);
stringBuilder.append(" s.sndout(s);").append(LINE_SEPARATOR);
if (timerSet) {
stringBuilder.append(" timer:stop();").append(LINE_SEPARATOR);
}
stringBuilder.append(" s.wastext = false;").append(LINE_SEPARATOR);
stringBuilder.append(" s.lasttext = nil;").append(LINE_SEPARATOR);
stringBuilder.append(" lifeoff(s);").append(LINE_SEPARATOR);
stringBuilder.append(generateDirectModeStopText(pageBlocks));
stringBuilder.append(" end,").append(LINE_SEPARATOR);
stringBuilder.append(" life = function(s)").append(LINE_SEPARATOR);
stringBuilder.append(" if vn.stopped then s.autos(s); end;").append(LINE_SEPARATOR);
//stringBuilder.append(" return true;").append(LINE_SEPARATOR);
stringBuilder.append(" end,").append(LINE_SEPARATOR);
stringBuilder.append(pageBlocks.getPageSound());
stringBuilder.append(generateObjsCollection(pageBlocks, linksBlocks));
stringBuilder.append(pageBlocks.getPageEnd());
return stringBuilder.toString();
}
protected String generateDirectModeStartText(PageBuildingBlocks pageBlocks) {
StringBuilder stringBuilder = new StringBuilder();
if (pageBlocks.isDirectMode() && pageBlocks.getTheme() == Theme.VN) {
stringBuilder.append(" vn:request_full_clear();").append(LINE_SEPARATOR);
stringBuilder.append(" vn:lock_direct();").append(LINE_SEPARATOR);
}
return stringBuilder.toString();
}
protected String generateDirectModeStopText(PageBuildingBlocks pageBlocks) {
StringBuilder stringBuilder = new StringBuilder();
if (pageBlocks.isDirectMode() && pageBlocks.getTheme() == Theme.VN) {
stringBuilder.append(" vn:request_full_clear();").append(LINE_SEPARATOR);
stringBuilder.append(" vn:unlock_direct();").append(LINE_SEPARATOR);
}
return stringBuilder.toString();
}
protected String getGraphicalObjectAppendingExpression(PageBuildingBlocks pageBuildingBlocks) {
if (isVN(pageBuildingBlocks.getTheme())) {
return m_vnsteadExportManager.getGraphicalObjectAppendingExpression(pageBuildingBlocks);
}
StringBuilder stringBuilder = new StringBuilder(" add_gobj = function(s)").append(LINE_SEPARATOR);
stringBuilder.append(" local bg_img = s.bgimg(s);").append(getLineSeparator());
final boolean imageBackground = pageBuildingBlocks.isImageBackground();
if (pageBuildingBlocks.isHasGraphicalObjects()) {
//stringBuilder.append(" vn:turnon();").append(LINE_SEPARATOR);
stringBuilder.append(" vn:scene(bg_img);").append(getLineSeparator());
for (String graphicalObjId : pageBuildingBlocks.getContainedGraphicalObjIds()) {
stringBuilder.append(" if " + graphicalObjId + ".preload then").append(LINE_SEPARATOR);
stringBuilder.append(" " + graphicalObjId + ":preload();").append(LINE_SEPARATOR);
stringBuilder.append(" else").append(LINE_SEPARATOR);
stringBuilder.append(" vn:gshow(" + graphicalObjId + ");").append(LINE_SEPARATOR);
stringBuilder.append(" end").append(LINE_SEPARATOR);
}
// Do not calling vn:startcb(function() s.autos(s); end), because it is NOT VN
} else if (imageBackground) {
stringBuilder.append(" theme.gfx.bg(bg_img);").append(getLineSeparator());
}
stringBuilder.append(" end,").append(LINE_SEPARATOR);
return stringBuilder.toString();
}
protected String getDefaultThemeSwitchExpression() {
return " nlb:theme_switch('theme_standard.lua');" + LINE_SEPARATOR;
}
protected String generateOrdinaryLinkTextInsideRoom(PageBuildingBlocks pageBuildingBlocks) {
if (isVN(pageBuildingBlocks.getTheme())) {
return m_vnsteadExportManager.generateOrdinaryLinkTextInsideRoom(pageBuildingBlocks);
}
/*
// Legacy version
StringBuilder linksBuilder = new StringBuilder();
for (final LinkBuildingBlocks linkBlocks : pageBuildingBlocks.getLinksBuildingBlocks()) {
if (!linkBlocks.isAuto()) {
linksBuilder.append(generateOrdinaryLinkCode(linkBlocks));
}
}
return linksBuilder.toString();
*/
StringBuilder wayBuilder = new StringBuilder(" way = {" + LINE_SEPARATOR);
StringBuilder wcnsBuilder = new StringBuilder(" wcns = {" + LINE_SEPARATOR);
StringBuilder altsBuilder = new StringBuilder(" alts = {" + LINE_SEPARATOR);
for (final LinkBuildingBlocks linkBlocks : pageBuildingBlocks.getLinksBuildingBlocks()) {
if (!linkBlocks.isAuto()) {
wayBuilder.append(" ").append(linkBlocks.getLinkLabel()).append(",").append(LINE_SEPARATOR);
final boolean constrained = !StringHelper.isEmpty(linkBlocks.getLinkConstraint());
if (constrained) {
wcnsBuilder.append(" ").append("[").append(linkBlocks.getLinkLabel()).append("] = function() return ").append(linkBlocks.getLinkConstraint()).append("; end,").append(LINE_SEPARATOR);
String altText = linkBlocks.getLinkAltText();
if (StringHelper.notEmpty(altText)) {
altsBuilder.append(" ").append("[").append(linkBlocks.getLinkLabel()).append("] = function() return \"").append(altText).append("\"; end,").append(LINE_SEPARATOR);
}
}
}
}
wayBuilder.append(" },").append(LINE_SEPARATOR);
wcnsBuilder.append(" },").append(LINE_SEPARATOR);
altsBuilder.append(" },").append(LINE_SEPARATOR);
return wayBuilder.toString() + wcnsBuilder.toString() + altsBuilder.toString();
}
@Override
protected String generatePostPageText(PageBuildingBlocks pageBlocks) {
if (isVN(pageBlocks.getTheme())) {
return m_vnsteadExportManager.generatePostPageText(pageBlocks);
}
/*
// Legacy version
return Constants.EMPTY_STRING;
*/
List<LinkBuildingBlocks> linksBuildingBlocks = pageBlocks.getLinksBuildingBlocks();
if (!hasChoicesOrLeaf(pageBlocks)) {
return Constants.EMPTY_STRING;
}
StringBuilder linksBuilder = new StringBuilder();
for (final LinkBuildingBlocks linkBlocks : linksBuildingBlocks) {
if (!linkBlocks.isAuto()) {
if (ENABLE_COMMENTS) {
linksBuilder.append(linkBlocks.getLinkComment());
}
linksBuilder.append(linkBlocks.getLinkStart());
linksBuilder.append(linkBlocks.getLinkModifications());
linksBuilder.append(linkBlocks.getLinkVariable());
linksBuilder.append(linkBlocks.getLinkVisitStateVariable());
linksBuilder.append(linkBlocks.getLinkGoTo());
linksBuilder.append(linkBlocks.getLinkEnd()).append(LINE_SEPARATOR);
}
}
return linksBuilder.toString();
}
protected String generateObjsCollection(PageBuildingBlocks pageBlocks, List<LinkBuildingBlocks> linksBlocks) {
if (isVN(pageBlocks.getTheme())) {
return m_vnsteadExportManager.generateObjsCollection(pageBlocks, linksBlocks);
}
StringBuilder result = new StringBuilder();
/*
// Legacy version
StringBuilder linksBuilder = new StringBuilder();
for (final LinkBuildingBlocks linkBlocks : linksBlocks) {
if (!linkBlocks.isAuto()) {
linksBuilder.append(linkBlocks.getLinkStart());
if (ENABLE_COMMENTS) {
linksBuilder.append(linkBlocks.getLinkComment());
}
linksBuilder.append(linkBlocks.getLinkModifications());
linksBuilder.append(linkBlocks.getLinkVariable());
linksBuilder.append(linkBlocks.getLinkVisitStateVariable());
linksBuilder.append(linkBlocks.getLinkGoTo());
linksBuilder.append(linkBlocks.getLinkEnd());
}
}
String linksText = linksBuilder.toString();
final boolean containedObjIdsIsEmpty = pageBlocks.getContainedObjIds().isEmpty();
final boolean linksTextIsEmpty = StringHelper.isEmpty(linksText);
if (!linksTextIsEmpty || !containedObjIdsIsEmpty) {
result.append(" obj = { ").append(LINE_SEPARATOR);
if (!containedObjIdsIsEmpty) {
for (String containedObjId : pageBlocks.getContainedObjIds()) {
result.append(containedObjId);
}
}
result.append(" xdsc(),").append(LINE_SEPARATOR);
if (!linksTextIsEmpty) {
result.append(linksText).append(LINE_SEPARATOR);
}
result.append(" },").append(LINE_SEPARATOR);
}
*/
final boolean containedObjIdsIsEmpty = pageBlocks.getContainedObjIds().isEmpty();
if (!containedObjIdsIsEmpty) {
result.append(" obj = { ").append(LINE_SEPARATOR);
for (String containedObjId : pageBlocks.getContainedObjIds()) {
result.append(containedObjId);
}
result.append(" },").append(LINE_SEPARATOR);
}
return result.toString();
}
protected String generateOrdinaryLinkCode(LinkBuildingBlocks linkBlocks) {
if (isVN(linkBlocks.getTheme())) {
return m_vnsteadExportManager.generateOrdinaryLinkCode(linkBlocks);
}
/*
// Legacy version
final boolean constrained = !StringHelper.isEmpty(linkBlocks.getLinkConstraint());
StringBuilder result = new StringBuilder();
result.append(" p(");
if (constrained) {
result.append("((").append(linkBlocks.getLinkConstraint()).append(") and ");
}
result.append("\"").append(linkBlocks.getLinkLabel()).append("\"");
if (constrained) {
result.append(" or ");
result.append("\"").append(linkBlocks.getLinkAltText()).append("\")");
}
result.append(");").append(LINE_SEPARATOR);
return result.toString();
*/
return Constants.EMPTY_STRING;
}
protected String generateAutoLinkCode(LinkBuildingBlocks linkBlocks) {
final boolean constrained = !StringHelper.isEmpty(linkBlocks.getLinkConstraint());
StringBuilder result = new StringBuilder();
result.append(" ");
result.append("if (").append((constrained) ? linkBlocks.getLinkConstraint() : "true").append(") then ");
result.append(linkBlocks.getLinkModifications());
result.append(linkBlocks.getLinkVariable());
result.append(linkBlocks.getLinkVisitStateVariable());
result.append(linkBlocks.getLinkGoTo());
// Should return immediately to prevent unwanted following of other auto links
result.append(LINE_SEPARATOR).append(" return false;").append(LINE_SEPARATOR);
result.append(" end;"); // matching end for if (...)
result.append(LINE_SEPARATOR);
return result.toString();
}
@Override
protected String escapeText(String text) {
return (
text
.replaceAll("\\\\", Matcher.quoteReplacement("\\\\"))
.replaceAll("\'", Matcher.quoteReplacement("\\\'"))
.replaceAll("\"", Matcher.quoteReplacement("\\\""))
.replaceAll("\\[", Matcher.quoteReplacement("\\91"))
.replaceAll("\\]", Matcher.quoteReplacement("\\93"))
);
}
@Override
protected String decorateObjLabel(String id) {
return decorateId(id);
}
@Override
protected String decorateObjComment(String name) {
return "-- " + name + LINE_SEPARATOR;
}
@Override
protected String decorateObjStart(final String id, String containerRef, ObjType objType, boolean showOnCursor, boolean preserved, boolean loadOnce, boolean clearUnderTooltip, boolean actOnKey, boolean cacheText, boolean looped, boolean noRedrawOnAct, String objDefaultTag) {
StringBuilder result = new StringBuilder();
switch (objType) {
case STAT:
result.append(" = stat {").append(LINE_SEPARATOR);
break;
case MENU:
result.append(" = menu {").append(LINE_SEPARATOR);
break;
case GOBJ:
result.append(" = gobj {").append(LINE_SEPARATOR);
if (clearUnderTooltip) {
result.append("clear_under_tooltip = true,").append(LINE_SEPARATOR);
}
if (showOnCursor) {
result.append("showoncur = true,").append(LINE_SEPARATOR);
}
if (preserved) {
result.append("preserved = true,").append(LINE_SEPARATOR);
}
if (loadOnce) {
result.append("load_once = true,").append(LINE_SEPARATOR);
}
if (cacheText) {
result.append("cache_text = true,").append(LINE_SEPARATOR);
}
if (looped) {
result.append("looped = true,").append(LINE_SEPARATOR);
}
if (noRedrawOnAct) {
result.append("noactredraw = true,").append(LINE_SEPARATOR);
}
break;
case GMENU:
result.append(" = gmenu {").append(LINE_SEPARATOR);
if (clearUnderTooltip) {
result.append("clear_under_tooltip = true,").append(LINE_SEPARATOR);
}
if (showOnCursor) {
result.append("showoncur = true,").append(LINE_SEPARATOR);
}
if (preserved) {
result.append("preserved = true,").append(LINE_SEPARATOR);
}
if (loadOnce) {
result.append("load_once = true,").append(LINE_SEPARATOR);
}
if (cacheText) {
result.append("cache_text = true,").append(LINE_SEPARATOR);
}
if (looped) {
result.append("looped = true,").append(LINE_SEPARATOR);
}
if (noRedrawOnAct) {
result.append("noactredraw = true,").append(LINE_SEPARATOR);
}
break;
default:
result.append(" = obj {").append(LINE_SEPARATOR);
}
result.append(" var { tag = '").append(objDefaultTag).append("'; ").append(getContainerExpression(containerRef));
result.append(" },").append(LINE_SEPARATOR);
result.append(" nlbid = '").append(id).append("',").append(LINE_SEPARATOR);
if (actOnKey) {
result.append(" actonkey = function(s, down, key)").append(LINE_SEPARATOR);
result.append(" if down then").append(LINE_SEPARATOR);
result.append(" s:actf();").append(LINE_SEPARATOR);
result.append(" end").append(LINE_SEPARATOR);
result.append(" return down;").append(LINE_SEPARATOR);
result.append(" end,").append(LINE_SEPARATOR);
}
result.append(" deref = function(s) return stead.deref(").append(decorateObjLabel(id)).append("); end,").append(LINE_SEPARATOR);
return result.toString();
}
@Override
protected String decorateObjName(String name, String id) {
return " nam = '" + (StringHelper.notEmpty(name) ? name : decorateId(id)) + "'," + LINE_SEPARATOR;
}
@Override
protected String decorateObjImage(List<ImagePathData> objImagePathDatas, boolean graphicalObj) {
StringBuilder resultBuilder = new StringBuilder();
boolean notFirst = false;
String ifTermination = Constants.EMPTY_STRING;
for (ImagePathData objImagePathData : objImagePathDatas) {
String objImagePath = objImagePathData.getImagePath();
StringBuilder tempBuilder = new StringBuilder();
tempBuilder.append(" ").append(notFirst ? "else" : Constants.EMPTY_STRING).append("if (");
String constraint = objImagePathData.getConstraint();
tempBuilder.append(StringHelper.notEmpty(constraint) ? "s.tag == '" + constraint + "'" : "true").append(") then");
tempBuilder.append(LINE_SEPARATOR);
if (objImagePathData.getMaxFrameNumber() == 0 || objImagePathData.isRemoveFrameNumber()) {
if (StringHelper.notEmpty(objImagePath)) {
ifTermination = " end" + LINE_SEPARATOR;
resultBuilder.append(tempBuilder).append(" ");
resultBuilder.append("return '").append(objImagePath).append("';").append(LINE_SEPARATOR);
}
} else {
ifTermination = " end" + LINE_SEPARATOR;
resultBuilder.append(tempBuilder).append(" ");
resultBuilder.append("return string.format('").append(objImagePath).append("', nlb:curloc().time % ");
resultBuilder.append(objImagePathData.getMaxFrameNumber()).append(" + 1); ").append(LINE_SEPARATOR);
}
notFirst = true;
}
String funbody = resultBuilder.toString();
if (StringHelper.isEmpty(funbody)) {
return Constants.EMPTY_STRING;
} else {
String result = " pic = function(s)" + LINE_SEPARATOR + funbody + LINE_SEPARATOR + ifTermination + "end," + LINE_SEPARATOR;
return result + " imgv = function(s) return img(s.pic(s)); end," + LINE_SEPARATOR;
}
}
protected String decorateObjEffect(String offsetString, String coordString, boolean graphicalObj, boolean hasParentObj, Obj.MovementDirection movementDirection, Obj.Effect effect, Obj.CoordsOrigin coordsOrigin, int startFrame, int curStep, int maxStep) {
boolean hasDefinedOffset = StringHelper.notEmpty(offsetString);
String offset = (hasDefinedOffset && !hasParentObj) ? offsetString : "0,0";
String pos = getPos(coordsOrigin, offset);
String steps = (effect == Obj.Effect.None) ? "" : " maxStep = " + maxStep + "," + LINE_SEPARATOR + " startFrame = " + startFrame + "," + LINE_SEPARATOR + " curStep = " + curStep + "," + LINE_SEPARATOR;
if (effect != Obj.Effect.None) {
String eff = effect.name().toLowerCase();
switch (movementDirection) {
case Top:
pos = eff + "top-" + pos;
break;
case Left:
pos = eff + "left-" + pos;
break;
case Right:
pos = eff + "right-" + pos;
break;
case Bottom:
pos = eff + "bottom-" + pos;
break;
default:
pos = eff + "-" + pos;
}
}
if (graphicalObj) {
return " eff = '" + pos + "'," + LINE_SEPARATOR + steps +
(hasDefinedOffset ? "" : " arm = { [0] = { " + coordString + " } }," + LINE_SEPARATOR);
} else {
return EMPTY_STRING;
}
}
@Override
protected String decorateObjPreload(int startFrame, int maxFrames, int preloadFrames) {
if (preloadFrames > 0) {
return " preload = function(s, room)" + LINE_SEPARATOR +
" vn.hz = vn.hz_preloaded;" + LINE_SEPARATOR +
" vn:preload_effect(s:pic(), " + startFrame + ", " + maxFrames + ", " + startFrame + ", " + preloadFrames + ", function()" + LINE_SEPARATOR +
" vn:gshow(s);" + LINE_SEPARATOR +
" if room then vn:geom(8, 864, 1904, 184, 'dissolve', 240, function() room.autos(room); vn.hz = vn.hz_onthefly; end); end;" + LINE_SEPARATOR +
" end, false, s.load_once);" + LINE_SEPARATOR +
" end," + LINE_SEPARATOR;
} else {
return EMPTY_STRING;
}
}
@NotNull
private String getPos(Obj.CoordsOrigin coordsOrigin, String offset) {
String pos = "left-top";
switch (coordsOrigin) {
case LeftTop:
pos = "left-top";
break;
case MiddleTop:
pos = "middle-top";
break;
case RightTop:
pos = "right-top";
break;
case LeftMiddle:
pos = "left-middle";
break;
case MiddleMiddle:
pos = "middle-middle";
break;
case RightMiddle:
pos = "right-middle";
break;
case LeftBottom:
pos = "left-bottom";
break;
case MiddleBottom:
pos = "middle-bottom";
break;
case RightBottom:
pos = "right-bottom";
}
return pos + "@" + offset;
}
@Override
protected String decorateMorphOver(String morphOverId, boolean graphicalObj) {
if (graphicalObj && StringHelper.notEmpty(morphOverId)) {
return " morphover = function(s) return " + decorateId(morphOverId) + ":deref(); end," + LINE_SEPARATOR;
} else {
return EMPTY_STRING;
}
}
@Override
protected String decorateMorphOut(String morphOutId, boolean graphicalObj) {
if (graphicalObj && StringHelper.notEmpty(morphOutId)) {
return " morphout = function(s) return " + decorateId(morphOutId) + ":deref(); end," + LINE_SEPARATOR;
} else {
return EMPTY_STRING;
}
}
@Override
protected String decorateObjDisp(String dispText, boolean imageEnabled, boolean isGraphicalObj) {
if (imageEnabled && !isGraphicalObj) {
return (
" disp = function(s) return s.imgv(s)..\"" +
dispText +
"\" end," + LINE_SEPARATOR
);
} else {
if (StringHelper.notEmpty(dispText)) {
return " disp = function(s) return \"" + dispText + "\" end," + LINE_SEPARATOR;
} else {
return " disp = function(s) return false; end," + LINE_SEPARATOR;
}
}
}
private String expandInteractionMarks(String objId, String objName, boolean useReference, String text, boolean withImage, boolean isGraphicalObj) {
StringBuilder result = new StringBuilder();
Matcher matcher = STEAD_OBJ_PATTERN.matcher(text);
int start = 0;
while (matcher.find()) {
result.append(text.substring(start, matcher.start())).append("{");
if (useReference) {
result.append(StringHelper.isEmpty(objName) ? decorateId(objId) : objName).append("|");
}
if (withImage && !isGraphicalObj) {
result.append("\"..s.imgv(s)..\"");
}
result.append(matcher.group(1)).append("}");
start = matcher.end();
}
result.append(text.substring(start, text.length()));
return result.toString();
}
@Override
protected String decorateObjText(String objId, String objName, boolean suppressDsc, String objText, boolean imageEnabled, boolean isGraphicalObj) {
StringBuilder stringBuilder = new StringBuilder();
if (suppressDsc) {
stringBuilder.append(" suppress_dsc = true,").append(LINE_SEPARATOR);
}
stringBuilder.append(" dscf = function(s) ");
if (StringHelper.notEmpty(objText)) {
stringBuilder.append("return \"");
stringBuilder.append(expandInteractionMarks(objId, objName, suppressDsc, objText, imageEnabled, isGraphicalObj));
stringBuilder.append("\"; ");
}
stringBuilder.append("end,").append(LINE_SEPARATOR);
stringBuilder.append(" dsc = function(s) ");
if (isGraphicalObj) {
stringBuilder.append("return s.dscf(s); ");
} else {
if (!suppressDsc) {
stringBuilder.append("p(s.dscf(s)); ");
}
}
stringBuilder.append("end,").append(LINE_SEPARATOR);
return stringBuilder.toString();
}
@Override
protected String decorateObjTak(final String objName, final String commonObjId) {
boolean hasCmn = StringHelper.notEmpty(commonObjId);
StringBuilder returnExpression = new StringBuilder();
if (hasCmn) {
returnExpression.append(" local hasCmnTak = (").append(decorateId(commonObjId)).append(".tak ~= nil").append(");").append(LINE_SEPARATOR);
returnExpression.append(" if hasCmnTak then").append(LINE_SEPARATOR);
returnExpression.append(" nlb:addf(nil, ").append(decorateId(commonObjId)).append(", false);").append(LINE_SEPARATOR); // Adding commonobj to inventory, analogous to ADDINV, and doing nothing for this object
returnExpression.append(" end").append(LINE_SEPARATOR);
returnExpression.append(" return not hasCmnTak;").append(LINE_SEPARATOR);
} else {
returnExpression.append(" return true;").append(LINE_SEPARATOR);
}
return (
" tak = function(s)" + LINE_SEPARATOR +
" s.act(s);" + LINE_SEPARATOR +
returnExpression.toString() +
" end," + LINE_SEPARATOR
);
}
@Override
protected String decorateObjInv(ObjType objType) {
switch (objType) {
case MENU:
return (
" menu = function(s)" + LINE_SEPARATOR
+ " return s.act(s);" + LINE_SEPARATOR
+ " end," + LINE_SEPARATOR
);
case OBJ:
return (
" inv = function(s)" + LINE_SEPARATOR
+ " if s.use then s.use(s, s); end;" + LINE_SEPARATOR
+ " end," + LINE_SEPARATOR
);
default:
return Constants.EMPTY_STRING;
}
}
@Override
protected String decorateObjActStart(String actTextExpanded, String commonObjId) {
final boolean actTextNotEmpty = StringHelper.notEmpty(actTextExpanded);
final String returnStatement = (actTextNotEmpty) ? "" : " return true;" + LINE_SEPARATOR;
String actText = getActText(actTextNotEmpty);
StringBuilder result = new StringBuilder();
boolean hasCmn = StringHelper.notEmpty(commonObjId);
result.append(" used = function(s, w)").append(LINE_SEPARATOR);
String id = hasCmn ? decorateId(commonObjId) : Constants.EMPTY_STRING;
if (hasCmn) {
result.append(" ").append("w:usea(").append(id).append(", s);").append(LINE_SEPARATOR);
}
result.append(" end,").append(LINE_SEPARATOR);
result.append(" act = function(s)").append(LINE_SEPARATOR);
result.append(" s:acta();").append(LINE_SEPARATOR);
result.append(returnStatement);
result.append(" end,").append(LINE_SEPARATOR);
result.append(" actt = function(s)").append(LINE_SEPARATOR);
result.append(" return \"").append(actTextExpanded).append("\";").append(LINE_SEPARATOR);
result.append(" end,").append(LINE_SEPARATOR);
result.append(" actp = function(s)").append(LINE_SEPARATOR);
result.append(actText);
result.append(" end,").append(LINE_SEPARATOR);
result.append(" acta = function(s)").append(LINE_SEPARATOR);
result.append(" s:actp();").append(LINE_SEPARATOR);
result.append(" s:actf();").append(LINE_SEPARATOR);
if (hasCmn) {
// Here we are calling actf of common object, replacing its argument by the current object
// TODO: Try to fix this, replacing s parameter with another object is not very good idea
if (actTextNotEmpty) {
result.append(" ").append(id).append(".actf(s);").append(LINE_SEPARATOR);
} else {
result.append(" ").append(id).append(":actp();").append(LINE_SEPARATOR);
result.append(" ").append(id).append(".actf(s);").append(LINE_SEPARATOR);
}
}
result.append(" end,").append(LINE_SEPARATOR);
result.append(" actf = function(s)").append(LINE_SEPARATOR);
return result.toString();
}
@Override
protected String decorateObjNouse(String nouseTextExpanded) {
final boolean nouseTextEmpty = StringHelper.isEmpty(nouseTextExpanded);
if (nouseTextEmpty) {
return Constants.EMPTY_STRING;
}
StringBuilder result = new StringBuilder();
result.append(" nouse = function(s)").append(LINE_SEPARATOR);
result.append(" nlb:curloc().lasttext = \"").append(nouseTextExpanded).append("\"; nlb:curloc().wastext = true;").append(LINE_SEPARATOR);
result.append(" return nlb:curloc().lasttext;").append(LINE_SEPARATOR);
result.append(" end,").append(LINE_SEPARATOR);
return result.toString();
}
protected String getActText(boolean actTextNotEmpty) {
return (
(actTextNotEmpty)
? " nlb:curloc().lasttext = s.actt(s); p(nlb:curloc().lasttext); nlb:curloc().wastext = true;" + LINE_SEPARATOR
: Constants.EMPTY_STRING
);
}
@Override
protected String decorateObjActEnd(boolean collapsable) {
final String prefix = (collapsable)
? (
" local v = vn:glookup(stead.deref(s));" + LINE_SEPARATOR +
" if s.is_paused then" + LINE_SEPARATOR +
" vn:vpause(v, false);" + LINE_SEPARATOR +
" else" + LINE_SEPARATOR +
" vn:set_step(v, nil, not v.forward);" + LINE_SEPARATOR +
" end" + LINE_SEPARATOR +
" vn:start();" + LINE_SEPARATOR
) : "";
return prefix + " end," + LINE_SEPARATOR;
}
@Override
protected String decorateObjUseStart(String commonObjId) {
// Before use, execute possible act commands (without printing act text) -> s.actf(s)
boolean hasCmn = StringHelper.notEmpty(commonObjId);
String cmnUse = (hasCmn) ? " if was_nonempty_usetext then " + decorateId(commonObjId) + ":usef(w, w); else " + decorateId(commonObjId) + ":usea(w, w); end;" + LINE_SEPARATOR : "";
return (
" use = function(s, w)" + LINE_SEPARATOR +
// " s:actf();" + LINE_SEPARATOR + // TODO: Possible used somewhere
" local was_nonempty_usetext = s:usea(w, w);" + LINE_SEPARATOR +
cmnUse +
" end," + LINE_SEPARATOR +
" usea = function(s, w, ww)" + LINE_SEPARATOR +
" local was_nonempty_usetext = s:usep(w, ww);" + LINE_SEPARATOR +
" s:usef(w, ww);" + LINE_SEPARATOR +
" return was_nonempty_usetext;" + LINE_SEPARATOR +
" end," + LINE_SEPARATOR +
" usef = function(s, w, ww)" + LINE_SEPARATOR
);
}
@Override
protected String decorateObjUseEnd() {
return " end," + LINE_SEPARATOR;
}
@Override
protected String decorateObjObjStart() {
return " obj = {" + LINE_SEPARATOR;
}
@Override
protected String decorateObjObjEnd() {
return " }," + LINE_SEPARATOR;
}
protected String decorateUseTarget(String targetId) {
return "w.nlbid == " + decorateId(targetId) + ".nlbid";
}
protected String decorateUseVariable(String variableName) {
String globalVar = GLOBAL_VAR_PREFIX + variableName;
return globalVar + " = true;" + LINE_SEPARATOR;
}
protected String decorateUseModifications(String modificationsText) {
return modificationsText;
}
@Override
protected String decorateObjVariable(String variableName) {
String globalVar = GLOBAL_VAR_PREFIX + variableName;
return globalVar + " = true;" + LINE_SEPARATOR;
}
@Override
protected String decorateObjConstraint(String constraintValue) {
StringBuilder result = new StringBuilder();
if (StringHelper.notEmpty(constraintValue)) {
result.append(" alive = function(s)").append(LINE_SEPARATOR);
result.append(" return ").append(constraintValue).append(";").append(LINE_SEPARATOR);
result.append(" end,").append(LINE_SEPARATOR);
result.append(" life = function(s)").append(LINE_SEPARATOR);
result.append(" if not s:alive() then").append(LINE_SEPARATOR);
result.append(" nlb._filter[").append("stead.deref(s)").append("] = true;").append(LINE_SEPARATOR);
result.append(" s:disable();").append(LINE_SEPARATOR);
result.append(" end;").append(LINE_SEPARATOR);
result.append(" end,").append(LINE_SEPARATOR);
result.append(" revive = function(s)").append(LINE_SEPARATOR);
result.append(" if ").append(constraintValue).append(" then").append(LINE_SEPARATOR);
result.append(" nlb._filter[").append("stead.deref(s)").append("] = false;").append(LINE_SEPARATOR);
result.append(" s:enable();").append(LINE_SEPARATOR);
result.append(" end;").append(LINE_SEPARATOR);
result.append(" end,").append(LINE_SEPARATOR);
}
return result.toString();
}
@Override
protected String decorateObjCommonTo(String commonObjId) {
StringBuilder result = new StringBuilder();
boolean hasCmn = StringHelper.notEmpty(commonObjId);
result.append(" used = function(s, w)").append(LINE_SEPARATOR);
String id = hasCmn ? decorateId(commonObjId) : Constants.EMPTY_STRING;
if (hasCmn) {
result.append(" ").append("w:usea(").append(id).append(", s);").append(LINE_SEPARATOR);
}
result.append(" end,").append(LINE_SEPARATOR);
result.append(" actcmn = function(s)").append(LINE_SEPARATOR);
if (hasCmn) {
// Here we are calling actf of common object, replacing its argument by the current object
result.append(" ").append(id).append(".actf(s);").append(LINE_SEPARATOR);
}
result.append(" end,").append(LINE_SEPARATOR);
return result.toString();
}
@Override
protected String decorateObjModifications(String modificationsText) {
return modificationsText;
}
@Override
protected String decorateObjEnd() {
return "};" + LINE_SEPARATOR + LINE_SEPARATOR;
}
@Override
protected String decorateContainedObjId(String containedObjId) {
return " '" + decorateId(containedObjId) + "'," + LINE_SEPARATOR;
}
@Override
protected String generateTrailingText() {
return "";
}
@Override
protected String decorateAssignment(String variableName, String variableValue) {
return variableName + " = " + variableValue + ";" + LINE_SEPARATOR;
}
@Override
protected String decorateTag(final String variable, final String objId, final String tag) {
StringBuilder result = new StringBuilder();
if (StringHelper.isEmpty(variable) && objId == null) {
result.append("s.tag = ");
} else {
if (objId != null) {
result.append(decorateId(objId)).append(".tag = ");
} else {
result.append(variable).append(".tag = ");
}
}
result.append("'").append(tag).append("';").append(LINE_SEPARATOR);
return result.toString();
}
@Override
protected String decorateGetTagOperation(String resultingVariable, String objId, String objVariableName) {
StringBuilder result = new StringBuilder();
if (StringHelper.notEmpty(resultingVariable)) {
result.append(resultingVariable).append(" = ");
if (StringHelper.notEmpty(objVariableName)) {
result.append(objVariableName);
} else if (objId != null) {
result.append(decorateId(objId));
} else {
result.append("s");
}
result.append(".tag;").append(LINE_SEPARATOR);
}
return result.toString();
}
@Override
protected String decorateWhile(final String constraint) {
return "while (" + constraint + ") do" + LINE_SEPARATOR;
}
@Override
protected String decorateIf(final String constraint) {
return "if (" + constraint + ") then" + LINE_SEPARATOR;
}
@Override
protected String decorateIfHave(String objId, String objVar) {
if (objId != null) {
return "if have(" + decorateId(objId) + ") then" + LINE_SEPARATOR;
} else {
return "if have(stead.deref(" + objVar + ")) then" + LINE_SEPARATOR;
}
}
@Override
protected String decorateElse() {
return "else" + LINE_SEPARATOR;
}
@Override
protected String decorateElseIf(final String constraint) {
return "elseif (" + constraint + ") then" + LINE_SEPARATOR;
}
@Override
protected String decorateEnd() {
return "end;" + LINE_SEPARATOR;
}
@Override
protected String decorateReturn() {
return "return;" + LINE_SEPARATOR;
}
@Override
protected String decorateHaveOperation(String variableName, String objId, String objVar) {
if (objId != null) {
return variableName + " = have(" + decorateId(objId) + ");" + LINE_SEPARATOR;
} else {
return variableName + " = have(stead.deref(" + objVar + "));" + LINE_SEPARATOR;
}
}
@Override
protected String decorateCloneOperation(final String variableName, final String objId, final String objVar) {
if (objId != null) {
return variableName + " = nlb:clone(" + decorateId(objId) + ");" + LINE_SEPARATOR;
} else if (objVar != null) {
return variableName + " = nlb:clone(" + objVar + ");" + LINE_SEPARATOR;
} else {
return variableName + " = nlb:clone(s);" + LINE_SEPARATOR;
}
}
@Override
protected String decorateContainerOperation(String variableName, String objId, String objVar) {
if (objId != null) {
return variableName + " = " + decorateId(objId) + ".container();" + LINE_SEPARATOR;
} else if (objVar != null) {
return variableName + " = " + objVar + ".container();" + LINE_SEPARATOR;
} else {
return variableName + " = s.container();" + LINE_SEPARATOR;
}
}
@Override
protected String decorateGetIdOperation(final String variableName, final String objId, final String objVar) {
if (objId != null) {
return variableName + " = '" + objId + "';" + LINE_SEPARATOR;
} else if (objVar != null) {
return variableName + " = " + objVar + ".nlbid;" + LINE_SEPARATOR;
} else {
return variableName + " = s.nlbid;" + LINE_SEPARATOR;
}
}
@Override
protected String decorateDelObj(String destinationId, final String destinationName, String objectId, String objectVar, String objectName, String objectDisplayName) {
String objToDel = (objectId != null) ? decorateId(objectId) : objectVar;
if (destinationId == null) {
if (destinationName != null) {
return " nlb:rmv(\"" + destinationName + "\", " + objToDel + "); " + getClearContainerStatement(objToDel) + LINE_SEPARATOR;
} else {
return " objs():del(" + objToDel + "); " + getClearContainerStatement(objToDel) + LINE_SEPARATOR;
}
} else {
return " objs(" + decorateId(destinationId) + "):del(" + objToDel + "); " + getClearContainerStatement(objToDel) + LINE_SEPARATOR;
}
}
private String getClearContainerStatement(String objVar) {
return objVar + ".container = " + NO_CONTAINER + "; ";
}
@Override
protected String decorateDelInvObj(String objectId, String objectVar, String objectName, String objectDisplayName) {
return (
" if have(stead.deref(" + objectVar + ")) then remove(stead.deref("
+ objectVar + "), " + "inv()); end;" + LINE_SEPARATOR
);
}
@Override
protected String decorateAddObj(String destinationId, String objectId, String objectVar, String objectName, String objectDisplayName, boolean unique) {
return (
" nlb:addf(" + ((destinationId != null) ? decorateId(destinationId) : "s") +
", " + ((objectId != null) ? decorateId(objectId) : objectVar) +
(unique ? ", true" : ", false") +
");" + LINE_SEPARATOR
);
}
@Override
protected String decorateAddInvObj(String objectId, String objectVar, String objectName, String objectDisplayName) {
return (
" nlb:addf(nil, " + ((objectId != null) ? decorateId(objectId) : objectVar) + ", false);" + LINE_SEPARATOR
);
}
@Override
protected String decorateAddAllOperation(String destinationId, String destinationListVariableName, String sourceListVariableName, boolean unique) {
return (
createListObj(destinationListVariableName) +
createListObj(sourceListVariableName) +
" nlb:addAll(s, " + ((destinationId != null) ? decorateId(destinationId) : "nil") +
", " + ((destinationListVariableName != null) ? "(" + destinationListVariableName + " ~= nil) and " + destinationListVariableName + ".listnam or \"\"" : "nil") +
", " + "(" + sourceListVariableName + " ~= nil) and " + sourceListVariableName + ".listnam or \"\"" +
(unique ? ", true" : ", false") +
");" + LINE_SEPARATOR
);
}
@Override
protected String decorateObjsOperation(String listVariableName, String srcObjId, String objectVar) {
return (
createListObj(listVariableName) +
" nlb:pushObjs(" +
listVariableName + ".listnam, " + ((srcObjId != null) ? decorateId(srcObjId) : objectVar) +
");" + LINE_SEPARATOR
);
}
@Override
protected String decorateSSndOperation() {
return " s:snd();" + LINE_SEPARATOR;
}
@Override
protected String decorateWSndOperation() {
return " ww:snd();" + LINE_SEPARATOR;
}
@Override
protected String decorateSndOperation(String objectId, String objectVar) {
if (objectId != null) {
return " " + decorateId(objectId) + ":snd();" + LINE_SEPARATOR;
} else if (objectVar != null) {
return " " + objectVar + ":snd();" + LINE_SEPARATOR;
} else {
return decorateSSndOperation();
}
}
@Override
protected String decorateSPushOperation(String listVariableName) {
return createListObj(listVariableName) + " nlb:push(" + listVariableName + ".listnam, s);" + LINE_SEPARATOR;
}
@Override
protected String decorateWPushOperation(String listVariableName) {
return createListObj(listVariableName) + " nlb:push(" + listVariableName + ".listnam, ww); -- will push nil if undef" + LINE_SEPARATOR;
}
@Override
protected String decoratePushOperation(String listVariableName, String objectId, String objectVar) {
return (
createListObj(listVariableName) +
" nlb:push(" +
listVariableName + ".listnam, " + ((objectId != null) ? decorateId(objectId) : objectVar) +
");" + LINE_SEPARATOR
);
}
private String createListObj(String listVariableName) {
if (listVariableName != null) {
return (
" if " + listVariableName + " == nil then" + LINE_SEPARATOR +
" stead.add_var { " + listVariableName + " = nlb:clonelst(listobj, \"" + listVariableName + "\"); }" + LINE_SEPARATOR +
" end;" + LINE_SEPARATOR
);
} else {
return Constants.EMPTY_STRING;
}
}
@Override
protected String decoratePopOperation(String variableName, String listVariableName) {
// TODO: handle pops from nonexistent lists
return variableName + " = nlb:pop(" + listVariableName + ".listnam);" + LINE_SEPARATOR;
}
@Override
protected String decorateSInjectOperation(String listVariableName) {
return createListObj(listVariableName) + " nlb:inject(" + listVariableName + ".listnam, s);" + LINE_SEPARATOR;
}
@Override
protected String decorateInjectOperation(String listVariableName, String objectId, String objectVar) {
return (
createListObj(listVariableName) +
" nlb:inject(" +
listVariableName + ".listnam, " + ((objectId != null) ? decorateId(objectId) : objectVar) +
");" + LINE_SEPARATOR
);
}
@Override
protected String decorateEjectOperation(String variableName, String listVariableName) {
// TODO: handle ejects from nonexistent lists
return variableName + " = nlb:eject(" + listVariableName + ".listnam);" + LINE_SEPARATOR;
}
@Override
protected String decorateClearOperation(String destinationId, String destinationVar) {
if (destinationId != null) {
return "nlb:clrcntnr(objs(" + decorateId(destinationId) + ")); " + "objs(" + decorateId(destinationId) + "):zap();" + LINE_SEPARATOR;
} else if (destinationVar != null) {
return "nlb:clear(" + destinationVar + ");" + LINE_SEPARATOR;
} else {
return "nlb:clrcntnr(objs()); objs():zap();" + LINE_SEPARATOR;
}
}
@Override
protected String decorateClearInvOperation() {
return "inv():zap();" + LINE_SEPARATOR;
}
@Override
protected String decorateSizeOperation(String variableName, String listVariableName) {
return "if " + listVariableName + " ~= nil then " + variableName + " = nlb:size(" + listVariableName + ".listnam) else " + variableName + " = 0 end;" + LINE_SEPARATOR;
}
@Override
protected String decorateRndOperation(String variableName, String maxValue) {
return variableName + " = rnd(" + maxValue + ");" + LINE_SEPARATOR;
}
@Override
protected String decorateAchieveOperation(String achievementName) {
// TODO: implement
return "nlb:setAchievement(statsAPI, '" + achievementName + "');" + LINE_SEPARATOR;
}
@Override
protected String decorateAchievedOperation(String variableName, String achievementName) {
return variableName + " = nlb:getAchievement(statsAPI, '" + achievementName + "');" + LINE_SEPARATOR;
}
@Override
protected String decorateGoToOperation(String locationId) {
return "nlb:nlbwalk(nil, " + decorateId(locationId) + ");" + LINE_SEPARATOR;
}
@Override
protected String decorateShuffleOperation(String listVariableName) {
return (
" if (" + listVariableName + " ~= nil) then" + LINE_SEPARATOR +
" nlb:shuffle(" + listVariableName + ".listnam);" + LINE_SEPARATOR +
" end;" + LINE_SEPARATOR
);
}
@Override
protected String decoratePRNOperation(String variableName) {
return "nlb:curloc().lasttext = nlb:lasttext().." + variableName + "; p(" + variableName + "); nlb:curloc().wastext = true;" + LINE_SEPARATOR;
}
@Override
protected String decorateDSCOperation(String resultVariableName, String dscObjVariable, String dscObjId) {
return resultVariableName + " = " + ((dscObjId != null) ? decorateId(dscObjId) : dscObjVariable) + ":dscf();" + LINE_SEPARATOR;
}
@Override
protected String decoratePDscOperation(String objVariableName) {
return "nlb:pdscf(" + objVariableName + ");" + LINE_SEPARATOR;
}
@Override
protected String decoratePDscsOperation(String objId, String objVar) {
if (objId != null) {
return "nlb:pdscs(" + decorateId(objId) + ");" + LINE_SEPARATOR;
} else if (objVar != null) {
return "nlb:pdscs(" + objVar + ");" + LINE_SEPARATOR;
} else {
return "nlb:pdscs(s);" + LINE_SEPARATOR;
}
}
@Override
protected String decorateActOperation(String actingObjVariable, String actingObjId) {
String source = (actingObjId != null) ? decorateId(actingObjId) : actingObjVariable;
return "nlb:acta(" + source + ");" + LINE_SEPARATOR;
}
@Override
protected String decorateActtOperation(String resultVariableName, String actObjVariable, String actObjId) {
return resultVariableName + " = " + ((actObjId != null) ? decorateId(actObjId) : actObjVariable) + ":actt();" + LINE_SEPARATOR;
}
@Override
protected String decorateActfOperation(String actingObjVariable, String actingObjId) {
String source = (actingObjId != null) ? decorateId(actingObjId) : actingObjVariable;
return "nlb:actf(" + source + ");" + LINE_SEPARATOR;
}
@Override
protected String decorateUseOperation(String sourceVariable, String sourceId, String targetVariable, String targetId) {
String source = (sourceId != null) ? decorateId(sourceId) : sourceVariable;
String target = (targetId != null) ? decorateId(targetId) : targetVariable;
return "nlb:usea(" + source + ", " + target + ");" + LINE_SEPARATOR;
}
@Override
protected String decorateTrue() {
return "true";
}
@Override
protected String decorateFalse() {
return "false";
}
@Override
protected String decorateEq() {
return "==";
}
@Override
protected String decorateNEq() {
return "~=";
}
@Override
protected String decorateGt() {
return ">";
}
@Override
protected String decorateGte() {
return ">=";
}
@Override
protected String decorateLt() {
return "<";
}
@Override
protected String decorateLte() {
return "<=";
}
@Override
protected String decorateNot() {
return "not ";
}
@Override
protected String decorateOr() {
return "or";
}
@Override
protected String decorateAnd() {
return "and";
}
@Override
protected String decorateExistence(final String decoratedVariable) {
return "(" + decoratedVariable + " ~= nil)";
}
@Override
protected String decorateBooleanVar(String constraintVar) {
return GLOBAL_VAR_PREFIX + constraintVar;
}
@Override
protected String decorateStringVar(String constraintVar) {
return GLOBAL_VAR_PREFIX + constraintVar;
}
@Override
protected String decorateNumberVar(String constraintVar) {
return GLOBAL_VAR_PREFIX + constraintVar;
}
@Override
protected String decorateLinkAltText(String text) {
if (StringHelper.isEmpty(text)) {
return Constants.EMPTY_STRING;
} else {
return text;
}
}
@Override
protected String decorateLinkLabel(String linkId, String linkText, Theme theme) {
if (isVN(theme)) {
return m_vnsteadExportManager.decorateLinkLabel(linkId, linkText, theme);
}
/*
// Legacy version
return "{" + decorateId(linkId) + "|" + linkText + "}^";
*/
return "'" + decorateId(linkId) + "'";
}
@Override
protected String decorateLinkComment(String comment) {
/*
// Legacy version
return " --" + comment + LINE_SEPARATOR;
*/
return "--" + comment + LINE_SEPARATOR;
}
@Override
protected String decorateLinkStart(String linkId, String linkText, boolean isAuto, boolean isTrivial, int pageNumber, Theme theme) {
if (isVN(theme)) {
return m_vnsteadExportManager.decorateLinkStart(linkId, linkText, isAuto, isTrivial, pageNumber, theme);
}
/*
// Legacy version
return (
" xact(" + LINE_SEPARATOR
+ " '" + decorateId(linkId) + "'," + LINE_SEPARATOR
+ " function(s) " + LINE_SEPARATOR
);
*/
String id = decorateId(linkId);
return (
id + " = room {" + LINE_SEPARATOR
+ " nam = '" + id + "'," + LINE_SEPARATOR
+ " disp = function(s)" + LINE_SEPARATOR
+ " return \"" + linkText + "\";" + LINE_SEPARATOR
+ " end," + LINE_SEPARATOR
+ " enter = function(s, f)" + LINE_SEPARATOR
);
}
@Override
protected String decorateLinkGoTo(
String linkId,
String linkText,
String linkTarget,
int targetPageNumber,
Theme theme
) {
if (isVN(theme)) {
return m_vnsteadExportManager.decorateLinkGoTo(linkId, linkText, linkTarget, targetPageNumber, theme);
}
return " nlb:nlbwalk(s, " + decoratePageName(linkTarget, targetPageNumber) + "); ";
}
@Override
protected String decorateLinkEnd(Theme theme) {
if (isVN(theme)) {
return m_vnsteadExportManager.decorateLinkEnd(theme);
}
/*
// Legacy version
return (
LINE_SEPARATOR
+ " end" + LINE_SEPARATOR
+ " )," + LINE_SEPARATOR
);
*/
return (
LINE_SEPARATOR
+ " end" + LINE_SEPARATOR
+ "}" + LINE_SEPARATOR
);
}
@Override
protected String decoratePageEnd(boolean isFinish) {
return "};" + LINE_SEPARATOR + LINE_SEPARATOR;
}
@Override
protected String decorateLinkVariable(String variableName) {
String globalVar = GLOBAL_VAR_PREFIX + variableName;
return globalVar + " = true;" + LINE_SEPARATOR;
}
@Override
protected String decorateLinkVisitStateVariable(String linkVisitStateVariable) {
String globalVar = GLOBAL_VAR_PREFIX + linkVisitStateVariable;
return globalVar + " = true;" + LINE_SEPARATOR;
}
@Override
protected String decoratePageVariable(String variableName) {
String globalVar = GLOBAL_VAR_PREFIX + variableName;
return globalVar + " = true;" + LINE_SEPARATOR;
}
@Override
protected String decoratePageTimerVariableInit(final String variableName) {
if (StringHelper.isEmpty(variableName)) {
return "s.time = 0; ";
} else {
String timerVar = decorateNumberVar(variableName);
return timerVar + " = 0; s.time = " + timerVar + "; ";
}
}
@Override
protected String decoratePageTimerVariable(final String variableName) {
if (StringHelper.isEmpty(variableName)) {
return "s.time = s.time + 1; ";
} else {
String timerVar = decorateNumberVar(variableName);
return timerVar + " = " + timerVar + " + 1; s.time = " + timerVar + "; ";
}
}
@Override
protected String decoratePageModifications(String modificationsText) {
return modificationsText;
}
@Override
protected String decorateLinkModifications(String modificationsText) {
return modificationsText;
}
@Override
protected String decoratePageCaption(String caption, boolean useCaption, String moduleTitle, boolean noSave) {
StringBuilder result = new StringBuilder();
String title = getNonEmptyTitle(moduleTitle);
if (StringHelper.notEmpty(caption) && useCaption) {
result.append(" nam = \"").append(caption).append("\",").append(LINE_SEPARATOR);
} else {
result.append(" nam = '").append(title).append("',").append(LINE_SEPARATOR);
}
if (noSave) {
result.append(" nosave = true,").append(LINE_SEPARATOR);
}
return result.toString();
}
@Override
protected String decoratePageNotes(String notes) {
return " notes = '" + notes + "'," + LINE_SEPARATOR;
}
@Override
protected String decoratePageImage(List<ImagePathData> pageImagePathDatas, final boolean imageBackground, Theme theme) {
if (isVN(theme)) {
return m_vnsteadExportManager.decoratePageImage(pageImagePathDatas, imageBackground, theme);
}
StringBuilder bgimgBuilder = new StringBuilder(" bgimg = function(s)" + LINE_SEPARATOR);
StringBuilder picBuilder = new StringBuilder(" pic = function(s)" + LINE_SEPARATOR);
boolean notFirst = false;
String bgimgIfTermination = Constants.EMPTY_STRING;
String picIfTermination = Constants.EMPTY_STRING;
for (ImagePathData pageImagePathData : pageImagePathDatas) {
String pageImagePath = pageImagePathData.getImagePath();
if (StringHelper.notEmpty(pageImagePath)) {
StringBuilder tempBuilder = new StringBuilder();
tempBuilder.append(" ").append(notFirst ? "else" : Constants.EMPTY_STRING).append("if (");
String constraint = pageImagePathData.getConstraint();
tempBuilder.append(StringHelper.notEmpty(constraint) ? "s.tag == '" + constraint + "'" : "true").append(") then");
tempBuilder.append(LINE_SEPARATOR);
final String img = decorateImagePath(pageImagePath, pageImagePathData.getMaxFrameNumber());
if (imageBackground) {
bgimgIfTermination = " end" + LINE_SEPARATOR;
bgimgBuilder.append(tempBuilder).append(" ");
bgimgBuilder.append("return ").append(img).append(";").append(LINE_SEPARATOR);
} else {
picIfTermination = " end" + LINE_SEPARATOR;
picBuilder.append(tempBuilder).append(" ");
picBuilder.append("return ").append(img).append(";").append(LINE_SEPARATOR);
}
}
notFirst = true;
}
bgimgBuilder.append(bgimgIfTermination).append(" end,").append(LINE_SEPARATOR);
picBuilder.append(picIfTermination).append(" end,").append(LINE_SEPARATOR);
return bgimgBuilder.toString() + picBuilder.toString();
}
private String decorateImagePath(String imagePath, int maxFrameNumber) {
if (maxFrameNumber > 0) {
return "string.format('" + imagePath + "', nlb:curloc().time % " + maxFrameNumber + " + 1)";
} else {
return "'" + imagePath + "'";
}
}
@Override
protected String decorateObjSound(List<SoundPathData> objSoundPathDatas, boolean soundSFX) {
// TODO: Code duplication with decoratePageSound()
StringBuilder result = new StringBuilder(" snd = function(s) " + LINE_SEPARATOR);
boolean notFirst = false;
String ifTermination = Constants.EMPTY_STRING;
for (SoundPathData objSoundPathData : objSoundPathDatas) {
String objSoundPath = objSoundPathData.getSoundPath();
if (StringHelper.notEmpty(objSoundPath)) {
String constraint = objSoundPathData.getConstraint();
final boolean hasConstraint = StringHelper.notEmpty(constraint);
if (hasConstraint) {
ifTermination = " end" + LINE_SEPARATOR;
result.append(" ").append(notFirst ? "else" : Constants.EMPTY_STRING).append("if (");
result.append("s.tag == '").append(constraint).append("'").append(") then");
result.append(LINE_SEPARATOR);
} else {
result.append(ifTermination);
}
if (Constants.VOID.equals(objSoundPath)) {
result.append(" stop_music();").append(LINE_SEPARATOR);
} else {
if (soundSFX || objSoundPathData.isSfx()) {
result.append(" add_sound('").append(objSoundPath).append("');").append(LINE_SEPARATOR);
} else {
result.append(" set_music('").append(objSoundPath).append("', 0);").append(LINE_SEPARATOR);
}
}
}
notFirst = true;
}
result.append(ifTermination);
result.append(" end,").append(LINE_SEPARATOR);
return result.toString();
}
@Override
protected String decorateObjArm(float left, float top) {
return " iarm = { [0] = { " + left + ", " + top + " } };" + LINE_SEPARATOR;
}
@Override
protected String decoratePageSound(String pageName, List<SoundPathData> pageSoundPathDatas, boolean soundSFX, Theme theme) {
StringBuilder result = new StringBuilder(" snd = function(s) " + LINE_SEPARATOR);
boolean notFirst = false;
boolean hasSFX = false;
String ifTermination = Constants.EMPTY_STRING;
for (SoundPathData pageSoundPathData : pageSoundPathDatas) {
String pageSoundPath = pageSoundPathData.getSoundPath();
if (StringHelper.notEmpty(pageSoundPath)) {
String constraint = pageSoundPathData.getConstraint();
final boolean hasConstraint = StringHelper.notEmpty(constraint);
if (hasConstraint) {
ifTermination = " end" + LINE_SEPARATOR;
result.append(" ").append(notFirst ? "else" : Constants.EMPTY_STRING).append("if (");
result.append("s.tag == '").append(constraint).append("'").append(") then");
result.append(LINE_SEPARATOR);
} else {
result.append(ifTermination);
}
if (Constants.VOID.equals(pageSoundPath)) {
result.append(" stop_music();").append(LINE_SEPARATOR);
} else {
if (soundSFX || pageSoundPathData.isSfx()) {
hasSFX = true;
result.append(" nlb:push('").append(pageName).append("_snds").append("', '").append(pageSoundPath).append("');").append(LINE_SEPARATOR);
} else {
result.append(" set_music('").append(pageSoundPath).append("', 0);").append(LINE_SEPARATOR);
}
}
}
notFirst = true;
}
result.append(ifTermination);
if (!isVN(theme)) {
result.append(" s.nextsnd(s);").append(LINE_SEPARATOR);
}
result.append(" end,").append(LINE_SEPARATOR);
result.append(" sndout = function(s) ");
if (hasSFX) {
result.append("stop_sound(); ");
}
result.append("end,").append(LINE_SEPARATOR);
return result.toString();
}
/**
* Expands variables from text chunks.
*
* @param textChunks
* @return
*/
protected String expandVariables(List<TextChunk> textChunks) {
StringBuilder result = new StringBuilder();
for (final TextChunk textChunk : textChunks) {
switch (textChunk.getType()) {
case TEXT:
result.append(textChunk.getText());
break;
case ACTION_TEXT:
result.append("\"..nlb:lasttext()..\"");
break;
case VARIABLE:
result.append("\"..");
result.append("tostring(").append(GLOBAL_VAR_PREFIX).append(textChunk.getText()).append(")");
result.append("..\"");
break;
case NEWLINE:
result.append("^\"..").append(getLineSeparator()).append("\"");
break;
}
}
return result.toString();
}
/**
* Expands variables from text chunks.
*
* @param textChunks
* @param theme
* @return
*/
protected String expandVariables(List<TextChunk> textChunks, Theme theme) {
if (isVN(theme)) {
return m_vnsteadExportManager.expandVariables(textChunks, theme);
}
return expandVariables(textChunks);
}
@Override
protected String expandVariablesForLinks(List<TextChunk> textChunks, Theme theme) {
// Expand variables for links should not use VN-related logic at all, even for VN case we should use plain INSTEAD approach
return expandVariables(textChunks);
}
protected String getGlobalVarPrefix() {
return GLOBAL_VAR_PREFIX;
}
protected String decoratePageTextStart(String labelText, int pageNumber, List<TextChunk> pageTextChunks, Theme theme) {
if (isVN(theme)) {
return m_vnsteadExportManager.decoratePageTextStart(labelText, pageNumber, pageTextChunks, theme);
}
StringBuilder pageText = new StringBuilder();
pageText.append(" dsc = function(s)").append(LINE_SEPARATOR);
if (pageTextChunks.size() > 0) {
pageText.append("p(\"");
pageText.append(expandVariables(pageTextChunks, theme));
pageText.append("\");").append(LINE_SEPARATOR);
}
pageText.append("p(nlb:alts_txt(s));").append(LINE_SEPARATOR);
pageText.append(" end,").append(LINE_SEPARATOR);
/*
// Legacy version
pageText.append(" xdsc = function(s)").append(LINE_SEPARATOR);
pageText.append(" p \"^\";").append(LINE_SEPARATOR);
*/
return pageText.toString();
}
@Override
protected String getLineSeparator() {
return LINE_SEPARATOR;
}
@Override
protected String decoratePageTextEnd(String labelText, int pageNumber, Theme theme, boolean hasChoicesOrLeaf) {
if (isVN(theme)) {
return m_vnsteadExportManager.decoratePageTextEnd(labelText, pageNumber, theme, hasChoicesOrLeaf);
}
/*
// Legacy version
return " end," + LINE_SEPARATOR;
*/
return Constants.EMPTY_STRING;
}
@Override
protected String decoratePageLabel(String labelText, int pageNumber, Theme theme) {
if (isVN(theme)) {
return m_vnsteadExportManager.decoratePageLabel(labelText, pageNumber, theme);
}
return generatePageBeginningCode(labelText, pageNumber) + "room {" + LINE_SEPARATOR;
}
protected String generatePageBeginningCode(String labelText, int pageNumber) {
StringBuilder roomBeginning = new StringBuilder();
String roomName = decoratePageName(labelText, pageNumber);
if (pageNumber == 1) {
roomBeginning.append("main, ").append(roomName);
roomBeginning.append(" = room { nam = 'main', enter = function(s) nlb:nlbwalk(s, ").append(roomName).append("); end }, ");
} else {
roomBeginning.append(roomName).append(" = ");
}
return roomBeginning.toString();
}
@Override
protected String decoratePageNumber(int pageNumber) {
return "-- PageNo. " + String.valueOf(pageNumber);
}
@Override
protected String decoratePageComment(String comment) {
return "-- " + comment + LINE_SEPARATOR;
}
}
|
package com.lothrazar.powerinventory.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.ContainerPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.inventory.Slot;
import net.minecraft.inventory.SlotCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.logging.log4j.Level;
import com.google.common.collect.Lists;
import com.lothrazar.powerinventory.Const;
import com.lothrazar.powerinventory.ModInv;
import com.lothrazar.powerinventory.inventory.client.GuiBigInventory;
public class BigContainerPlayer extends ContainerPlayer
{
private final int craftSize = 3;//did not exist before, was magic'd as 2 everywhere
private final EntityPlayer thePlayer;
public BigInventoryPlayer invo;
public boolean isLocalWorld;
final int padding = 6;
//these get used here for actual slot, and in GUI for texture
//ender pearl is in the far bottom right corner, and the others move left relative to this
public final int pearlX = 80;
public final int pearlY = 8;
public final int compassX = pearlX;
public final int compassY = pearlY + Const.square;
public final int clockX = pearlX;
public final int clockY = pearlY + 2*Const.square;
public final int echestX = pearlX;
public final int echestY = pearlY + 3*Const.square;
public final int bottleX = GuiBigInventory.texture_width - Const.square - padding - 1;
public final int bottleY = 20 + 2 * Const.square;
//store slot numbers (not indexes) as we go. so that transferStack.. is actually readable
static int S_RESULT;
static int S_CRAFT_START;
static int S_CRAFT_END;
static int S_ARMOR_START;
static int S_ARMOR_END;
static int S_BAR_START;
static int S_BAR_END;
static int S_MAIN_START;
static int S_MAIN_END;
static int S_ECHEST;
static int S_PEARL;
static int S_CLOCK;
static int S_COMPASS;
static int S_BOTTLE;
public BigContainerPlayer(BigInventoryPlayer playerInventory, boolean isLocal, EntityPlayer player)
{
super(playerInventory, isLocal, player);
this.thePlayer = player;
inventorySlots = Lists.newArrayList();//undo everything done by super()
craftMatrix = new InventoryCrafting(this, craftSize, craftSize);
int i,j,cx,cy;//rows and cols of vanilla, not extra
S_RESULT = this.inventorySlots.size();
this.addSlotToContainer(new SlotCrafting(playerInventory.player, this.craftMatrix, this.craftResult, 0,
200,
40));
S_CRAFT_START = this.inventorySlots.size();
for (i = 0; i < craftSize; ++i)
{
for (j = 0; j < craftSize; ++j)
{
cx = 114 + j * Const.square ;
cy = 20 + i * Const.square ;
this.addSlotToContainer(new Slot(this.craftMatrix, j + i * this.craftSize, cx , cy));
}
}
S_CRAFT_END = this.inventorySlots.size() - 1;
S_ARMOR_START = this.inventorySlots.size();
for (i = 0; i < Const.armorSize; ++i)
{
cx = 8;
cy = 8 + i * Const.square;
final int k = i;
this.addSlotToContainer(new Slot(playerInventory, playerInventory.getSizeInventory() - 1 - i, cx, cy)
{
public int getSlotStackLimit()
{
return 1;
}
public boolean isItemValid(ItemStack stack)
{
if (stack == null) return false;
return stack.getItem().isValidArmor(stack, k, thePlayer);
}
@SideOnly(Side.CLIENT)
public String getSlotTexture()
{
return ItemArmor.EMPTY_SLOT_NAMES[k];
}
});
}
S_ARMOR_END = this.inventorySlots.size() - 1;
S_BAR_START = this.inventorySlots.size();
for (i = 0; i < Const.hotbarSize; ++i)
{
cx = 8 + i * Const.square;
cy = 142 + (Const.square * Const.MORE_ROWS);
this.addSlotToContainer(new Slot(playerInventory, i, cx, cy));
}
S_BAR_END = this.inventorySlots.size() - 1;
S_MAIN_START = this.inventorySlots.size();
int slotIndex = Const.hotbarSize;
for( i = 0; i < Const.ALL_ROWS; i++)
{
for ( j = 0; j < Const.ALL_COLS; ++j)
{
cx = 8 + j * Const.square;
cy = 84 + i * Const.square;
this.addSlotToContainer(new Slot(playerInventory, slotIndex, cx, cy));
slotIndex++;
}
}
S_MAIN_END = this.inventorySlots.size() - 1;
S_PEARL = this.inventorySlots.size() ;
this.addSlotToContainer(new SlotEnderPearl(playerInventory, Const.enderPearlSlot, pearlX, pearlY));
S_ECHEST = this.inventorySlots.size() ;
this.addSlotToContainer(new SlotEnderChest(playerInventory, Const.enderChestSlot, echestX, echestY));
S_CLOCK = this.inventorySlots.size() ;
this.addSlotToContainer(new SlotClock(playerInventory, Const.clockSlot, clockX, clockY));
S_COMPASS = this.inventorySlots.size() ;
this.addSlotToContainer(new SlotCompass(playerInventory, Const.compassSlot, compassX, compassY));
S_BOTTLE = this.inventorySlots.size() ;
this.addSlotToContainer(new SlotBottle(playerInventory, Const.bottleSlot, bottleX, bottleY));
this.onCraftMatrixChanged(this.craftMatrix);
this.invo = playerInventory;
}
@Override
public Slot getSlotFromInventory(IInventory invo, int id)
{
Slot slot = super.getSlotFromInventory(invo, id);
if(slot == null)
{
Exception e = new NullPointerException();
ModInv.logger.log(Level.FATAL, e.getStackTrace()[1].getClassName() + "." + e.getStackTrace()[1].getMethodName() + ":" + e.getStackTrace()[1].getLineNumber() + " is requesting slot " + id + " from inventory " + invo.getName() + " (" + invo.getClass().getName() + ") and got NULL!", e);
}
return slot;
}
@Override
public void onContainerClosed(EntityPlayer playerIn)
{
super.onContainerClosed(playerIn);
for (int i = 0; i < craftSize*craftSize; ++i) // was 4
{
ItemStack itemstack = this.craftMatrix.getStackInSlotOnClosing(i);
if (itemstack != null)
{
playerIn.dropPlayerItemWithRandomChoice(itemstack, false);
}
}
this.craftResult.setInventorySlotContents(0, (ItemStack)null);
}
/**
* Called when a player shift-clicks on a slot. You must override this or you will crash when someone does that.
*/
@Override
public ItemStack transferStackInSlot(EntityPlayer p, int slotNumber)
{
if(p.capabilities.isCreativeMode)
{
return super.transferStackInSlot(p, slotNumber);
}
//Thanks to coolAlias on the forums :
//above is from 2013 but still relevant
ItemStack stackCopy = null;
Slot slot = (Slot)this.inventorySlots.get(slotNumber);
if (slot != null && slot.getHasStack())
{
ItemStack stackOrig = slot.getStack();
stackCopy = stackOrig.copy();
if (slotNumber == S_RESULT)
{
if (!this.mergeItemStack(stackOrig, S_BAR_START, S_MAIN_END, true))
{
return null;
}
slot.onSlotChange(stackOrig, stackCopy);
}
else if (slotNumber >= S_CRAFT_START && slotNumber <= S_CRAFT_END)
{
if (!this.mergeItemStack(stackOrig, S_BAR_START, S_MAIN_END, false))//was 9,45
{
return null;
}
}
else if (slotNumber >= S_ARMOR_START && slotNumber <= S_ARMOR_END)
{
if (!this.mergeItemStack(stackOrig, S_MAIN_START, S_MAIN_END, false))
{
return null;
}
}
else if (stackCopy.getItem() instanceof ItemArmor
&& !((Slot)this.inventorySlots.get(S_ARMOR_START + ((ItemArmor)stackCopy.getItem()).armorType)).getHasStack()) // Inventory to armor
{
int j = S_ARMOR_START + ((ItemArmor)stackCopy.getItem()).armorType;
if (!this.mergeItemStack(stackOrig, j, j+1, false))
{
return null;
}
}
else if (slotNumber >= S_MAIN_START && slotNumber <= S_MAIN_END) // main inv grid
{
//only from here are we doing the special items
if(stackCopy.getItem() == Items.ender_pearl &&
(
p.inventory.getStackInSlot(Const.enderPearlSlot) == null ||
p.inventory.getStackInSlot(Const.enderPearlSlot).stackSize < Items.ender_pearl.getItemStackLimit(stackCopy))
)
{
if (!this.mergeItemStack(stackOrig, S_PEARL, S_PEARL+1, false))
{
return null;
}
}
else if(stackCopy.getItem() == Item.getItemFromBlock(Blocks.ender_chest) &&
(
p.inventory.getStackInSlot(Const.enderChestSlot) == null ||
p.inventory.getStackInSlot(Const.enderChestSlot).stackSize < 1)
)
{
if (!this.mergeItemStack(stackOrig, S_ECHEST, S_ECHEST+1, false))
{
return null;
}
}
else if(stackCopy.getItem() == Items.compass &&
(
p.inventory.getStackInSlot(Const.compassSlot) == null ||
p.inventory.getStackInSlot(Const.compassSlot).stackSize < 1)
)
{
if (!this.mergeItemStack(stackOrig, S_COMPASS, S_COMPASS+1, false))
{
return null;
}
}
else if(stackCopy.getItem() == Items.clock &&
(
p.inventory.getStackInSlot(Const.clockSlot) == null ||
p.inventory.getStackInSlot(Const.clockSlot).stackSize < 1)
)
{
if (!this.mergeItemStack(stackOrig, S_CLOCK, S_CLOCK+1, false))
{
return null;
}
}
else if(stackCopy.getItem() == Items.glass_bottle )
{
if (!this.mergeItemStack(stackOrig, S_BOTTLE, S_BOTTLE+1, false))
{
return null;
}
}
else if (!this.mergeItemStack(stackOrig, S_BAR_START, S_BAR_END+1, false) )
{
return null;
}
}
else if (slotNumber >= S_BAR_START && slotNumber <= S_BAR_END) // Hotbar
{
if (!this.mergeItemStack(stackOrig, S_MAIN_START, S_MAIN_END, false))
{
return null;
}
}
else if(slotNumber == S_PEARL || slotNumber == S_ECHEST || slotNumber == S_COMPASS || slotNumber == S_CLOCK || slotNumber == S_BOTTLE)
{
if (!this.mergeItemStack(stackOrig, S_MAIN_START, S_MAIN_END, false))
{
return null;
}
}
else if (!this.mergeItemStack(stackOrig, 9, invo.getSlotsNotArmor() + 9, false)) // Full range
{
return null;
}
if (stackOrig.stackSize == 0)
{
slot.putStack((ItemStack)null);
}
else
{
slot.onSlotChanged();
}
if (stackOrig.stackSize == stackCopy.stackSize)
{
return null;
}
slot.onPickupFromSlot(p, stackOrig);
}
return stackCopy;
}
}
|
package owltools.graph;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.obolibrary.obo2owl.Obo2OWLConstants.Obo2OWLVocabulary;
import org.obolibrary.obo2owl.Obo2Owl;
import org.obolibrary.obo2owl.Owl2Obo;
import org.obolibrary.oboformat.model.OBODoc;
import org.obolibrary.oboformat.parser.OBOFormatConstants.OboFormatTag;
import org.semanticweb.owlapi.model.AxiomType;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom;
import org.semanticweb.owlapi.model.OWLAnnotationProperty;
import org.semanticweb.owlapi.model.OWLAnnotationSubject;
import org.semanticweb.owlapi.model.OWLAnnotationValue;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLDeclarationAxiom;
import org.semanticweb.owlapi.model.OWLEntity;
import org.semanticweb.owlapi.model.OWLFunctionalObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLInverseFunctionalObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLNamedObject;
import org.semanticweb.owlapi.model.OWLObject;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLReflexiveObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLSymmetricObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLTransitiveObjectPropertyAxiom;
import org.semanticweb.owlapi.model.UnknownOWLOntologyException;
import org.semanticweb.owlapi.vocab.OWLRDFVocabulary;
/**
* Methods to extract values from entities in the graph with potential multiple
* {@link OWLOntology} objects. This includes methods, to extract OBO-style
* information from the OWL representation.
*
* @see OWLGraphWrapper
* @see OWLGraphWrapperBasic
*/
public class OWLGraphWrapperExtended extends OWLGraphWrapperBasic {
protected OWLGraphWrapperExtended(OWLOntology ontology) throws UnknownOWLOntologyException, OWLOntologyCreationException {
super(ontology);
}
protected OWLGraphWrapperExtended(String iri) throws OWLOntologyCreationException {
super(iri);
}
/**
* fetches the rdfs:label for an OWLObject
* <p>
* assumes zero or one rdfs:label
*
* @param c
* @return label
*/
public String getLabel(OWLObject c) {
return getAnnotationValue(c, getDataFactory().getRDFSLabel());
}
/**
* fetches the rdfs:label for an OWLObject
* <p>
* This is a curried FlexLoader s-expression version of {@link #getLabel(OWLObject)}.
*
* @param c
* @param sargs
* @return label
*
* @see #getLabel(OWLObject)
*/
public String getLabel(OWLObject c, ArrayList<String> sargs) {
return getLabel(c);
}
public String getLabelOrDisplayId(OWLObject c) {
String label = getLabel(c);
if (label == null) {
if (c instanceof OWLNamedObject) {
OWLNamedObject nc = (OWLNamedObject)c;
label = nc.getIRI().getFragment();
}
else {
label = c.toString();
}
}
return label;
}
/**
* tests if an OWLObject has been declared obsolete in the graph.
*
* @param c
* @return boolean
*/
public boolean isObsolete(OWLObject c) {
for (OWLOntology ont : getAllOntologies()) {
for (OWLAnnotation ann : ((OWLEntity)c).getAnnotations(ont)) {
if (ann.isDeprecatedIRIAnnotation()) {
return true;
}
}
}
return false;
}
/**
* gets the value of rdfs:comment for an OWLObject
*
* @param c
* @return comment of null
*/
public String getComment(OWLObject c) {
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(OWLRDFVocabulary.RDFS_COMMENT.getIRI());
return getAnnotationValue(c, lap);
}
/**
* gets the value of rdfs:comment for an OWLObject
* <p>
* This is a curried FlexLoader s-expression version of {@link #getComment(OWLObject)}.
*
* @param c
* @param sargs
* @return comment of null
* @see #getComment(OWLObject)
*/
public String getComment(OWLObject c, ArrayList<String> sargs) {
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(OWLRDFVocabulary.RDFS_COMMENT.getIRI());
return getAnnotationValue(c, lap);
}
/**
* fetches the value of a single-valued annotation property for an OWLObject
* <p>
* TODO: provide a flag that determines behavior in the case of >1 value
*
* @param c
* @param lap
* @return value
*/
public String getAnnotationValue(OWLObject c, OWLAnnotationProperty lap) {
Set<OWLAnnotation>anns = new HashSet<OWLAnnotation>();
if (c instanceof OWLEntity) {
for (OWLOntology ont : getAllOntologies()) {
// TODO : import closure
anns.addAll(((OWLEntity) c).getAnnotations(ont,lap));
}
}
else {
return null;
}
for (OWLAnnotation a : anns) {
if (a.getValue() instanceof OWLLiteral) {
OWLLiteral val = (OWLLiteral) a.getValue();
return val.getLiteral(); // return first - TODO - check zero or one
}
}
return null;
}
/**
* gets the values of all annotation assertions to an OWLObject for a particular annotation property
*
* @param c
* @param lap
* @return list of values or null
*/
public List<String> getAnnotationValues(OWLObject c, OWLAnnotationProperty lap) {
Set<OWLAnnotation>anns = new HashSet<OWLAnnotation>();
if (c instanceof OWLEntity) {
for (OWLOntology ont : getAllOntologies()) {
anns.addAll(((OWLEntity) c).getAnnotations(ont,lap));
}
}
else {
return null;
}
ArrayList<String> list = new ArrayList<String>();
for (OWLAnnotation a : anns) {
if (a.getValue() instanceof OWLLiteral) {
OWLLiteral val = (OWLLiteral) a.getValue();
list.add( val.getLiteral());
}
else if (a.getValue() instanceof IRI) {
IRI val = (IRI)a.getValue();
list.add( getIdentifier(val) );
}
}
return list;
}
/**
* Gets the textual definition of an OWLObject
* <p>
* assumes zero or one def
* <p>
* It returns the definition text (encoded as def in obo format and IAO_0000115 annotation property in OWL format) of a class
*
* @param c
* @return definition
*/
public String getDef(OWLObject c) {
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(Obo2OWLVocabulary.IRI_IAO_0000115.getIRI());
return getAnnotationValue(c, lap);
}
/**
* Gets the textual definition of an OWLObject
* <p>
* This is a curried FlexLoader s-expression version of {@link #getDef(OWLObject)}.
*
* @param c
* @param sargs
* @return definition
*
* @see #getDef(OWLObject)
*/
public String getDef(OWLObject c, ArrayList<String> sargs) {
return getDef(c);
}
/**
* It returns the value of the is_metadata_tag tag.
*
* @param c could OWLClass or OWLObjectProperty
* @return boolean
*/
public boolean getIsMetaTag(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_IS_METADATA_TAG.getTag());
String val = getAnnotationValue(c, lap);
return val == null ? false: Boolean.valueOf(val);
}
/**
* Returns the values of the subset tag for a given OWLObject
*
* @param c could OWLClass or OWLObjectProperty
* @return subsets to which the OWLObject belongs
*/
// TODO - return set
public List<String> getSubsets(OWLObject c) {
//OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_SUBSET.getTag());
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(Obo2OWLVocabulary.IRI_OIO_inSubset.getIRI());
return getAnnotationValues(c, lap);
}
/**
* It returns the value of the subset tag.
* <p>
* This is a curried FlexLoader s-expression version of {@link #getSubsets(OWLObject)}.
*
* @param c could OWLClass or OWLObjectProperty
* @param sargs
* @return values
* @see #getSubsets(OWLObject)
*/
public List<String> getSubsets(OWLObject c, ArrayList<String> sargs) {
return getSubsets(c);
}
/**
* fetches all subset names that are used
*
* @return all subsets used in source ontology
*/
public Set<String> getAllUsedSubsets() {
Set<String> subsets = new HashSet<String>();
for (OWLObject x : getAllOWLObjects()) {
subsets.addAll(getSubsets(x));
}
return subsets;
}
/**
* given a subset name, find all OWLObjects (typically OWLClasses) assigned to that subset
*
* @param subset
* @return set of {@link OWLObject}
*/
public Set<OWLObject> getOWLObjectsInSubset(String subset) {
Set<OWLObject> objs = new HashSet<OWLObject>();
for (OWLObject x : getAllOWLObjects()) {
if (getSubsets(x).contains(subset))
objs.add(x);
}
return objs;
}
/**
* given a subset name, find all OWLClasses assigned to that subset
*
* @param subset
* @return set of {@link OWLClass}
*/
public Set<OWLClass> getOWLClassesInSubset(String subset) {
Set<OWLClass> objs = new HashSet<OWLClass>();
for (OWLObject x : getAllOWLObjects()) {
if (getSubsets(x).contains(subset) && x instanceof OWLClass)
objs.add((OWLClass) x);
}
return objs;
}
/**
* It returns the value of the domain tag
*
* @param prop
* @return domain string or null
*/
public String getDomain(OWLObjectProperty prop){
Set<OWLClassExpression> domains = prop.getDomains(sourceOntology);
for(OWLClassExpression ce: domains){
return getIdentifier(ce);
}
return null;
}
/**
* It returns the value of the range tag
*
* @param prop
* @return range or null
*/
public String getRange(OWLObjectProperty prop){
Set<OWLClassExpression> domains = prop.getRanges(sourceOntology);
for(OWLClassExpression ce: domains){
return getIdentifier(ce);
}
return null;
}
/**
* It returns the values of the replaced_by tag or IAO_0100001 annotation.
*
* @param c could OWLClass or OWLObjectProperty
* @return list of values
*/
public List<String> getReplacedBy(OWLObject c) {
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(Obo2OWLVocabulary.IRI_IAO_0100001.getIRI());
return getAnnotationValues(c, lap);
}
/**
* It returns the values of the consider tag.
*
* @param c could OWLClass or OWLObjectProperty
* @return list of values
*/
public List<String> getConsider(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_CONSIDER.getTag());
return getAnnotationValues(c, lap);
}
/**
* It returns the value of the is-obsolete tag.
*
* @param c could OWLClass or OWLObjectProperty
* @return boolean
*/
public boolean getIsObsolete(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_IS_OBSELETE.getTag());
String val = getAnnotationValue(c, lap);
return val == null ? false: Boolean.valueOf(val);
}
/**
* It returns the value of the is-obsolete tag.
* <p>
* The odd signature is for use with FlexLoader.
*
* @param c could OWLClass or OWLObjectProperty
* @param sargs (unsused)
*
* @return String
*/
public String getIsObsoleteBinaryString(OWLObject c, ArrayList<String> sargs) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_IS_OBSELETE.getTag());
String val = getAnnotationValue(c, lap);
return val == null ? "false": "true";
//return val;
}
/**
* Get the annotation property value for a tag.
*
* @see #getAnnotationPropertyValues(OWLObject c, String tag)
* @param c
* @param tag
* @return String
*/
public String getAnnotationPropertyValue(OWLObject c, String tag) {
OWLAnnotationProperty lap = getAnnotationProperty(tag);
return getAnnotationValue(c, lap);
}
/**
* Get the annotation property value for a tag.
* <p>
* This is a curried FlexLoader s-expression version of {@link #getAnnotationPropertyValue(OWLObject, String)}.
* <p>
* Currently, this function will only accept an argument of length 1.
*
* @param c
* @param tags
* @return String
* @see #getAnnotationPropertyValues(OWLObject c, String tag)
*/
public String getAnnotationPropertyValue(OWLObject c, ArrayList<String> tags) {
String retval = null;
if( tags != null && tags.size() == 1 ){
String tag = tags.get(0);
retval = getAnnotationPropertyValue(c, tag);
}
return retval;
}
/**
* Get the annotation property values for a tag.
*
* @see #getAnnotationPropertyValue(OWLObject c, String tag)
* @param c
* @param tag
* @return String List
*/
public List<String> getAnnotationPropertyValues(OWLObject c, String tag) {
OWLAnnotationProperty lap = getAnnotationProperty(tag);
return getAnnotationValues(c, lap);
}
/**
* Get the annotation property values for a tag.
* <p>
* This is a curried FlexLoader s-expression version of {@link #getAnnotationPropertyValues(OWLObject, String)}.
* <p>
* Currently, this function will only accept an argument of length 1.
*
* @see #getAnnotationPropertyValues(OWLObject c, String tag)
* @param c
* @param tags
* @return String List
*/
public List<String> getAnnotationPropertyValues(OWLObject c, ArrayList<String> tags) {
List<String> retvals = new ArrayList<String>();
if( tags != null && tags.size() == 1 ){
String tag = tags.get(0);
retvals = getAnnotationPropertyValues(c, tag);
}
return retvals;
}
/**
* It returns the values of the alt_id tag
*
* @param c
* @return list of identifiers
*/
public List<String> getAltIds(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_ALT_ID.getTag());
return getAnnotationValues(c, lap);
}
/**
* It returns the value of the builtin tag
*
* @param c
* @return boolean
*/
@Deprecated
public boolean getBuiltin(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_BUILTIN.getTag());
String val = getAnnotationValue(c, lap);
return val == null ? false: Boolean.valueOf(val);
}
/**
* It returns the value of the is_anonymous tag
*
* @param c
* @return boolean
*/
@Deprecated
public boolean getIsAnonymous(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_IS_ANONYMOUS.getTag());
String val = getAnnotationValue(c, lap);
return val == null ? false: Boolean.valueOf(val);
}
/**
* It translates a oboformat tag into an OWL annotation property
*
* @param tag
* @return {@link OWLAnnotationProperty}
*/
public OWLAnnotationProperty getAnnotationProperty(String tag){
return getDataFactory().getOWLAnnotationProperty(Obo2Owl.trTagToIRI(tag));
}
/**
* It returns the value of the OBO-namespace tag
* <p>
* Example: if the OWLObject is the GO class GO:0008150, this would return "biological_process"
*
* @param c
* @return namespace
*/
public String getNamespace(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_NAMESPACE.getTag());
return getAnnotationValue(c, lap);
}
/**
* It returns the value of the OBO-namespace tag.
* <p>
* This is a curried FlexLoader s-expression version of {@link #getNamespace(OWLObject)}.
*
* @param c
* @param sargs
* @return namespace
*
* @see #getNamespace(OWLObject)
*/
public String getNamespace(OWLObject c, ArrayList<String> sargs) {
return getNamespace(c);
}
/**
* It returns the value of the created_by tag
*
* @param c
* @return value or null
*/
public String getCreatedBy(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_CREATED_BY.getTag());
return getAnnotationValue(c, lap);
}
/**
* It returns the value of the is_anti_symmetric tag or IAO_0000427 annotation
*
* @param c
* @return boolean
*/
public boolean getIsAntiSymmetric(OWLObject c) {
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(Obo2OWLVocabulary.IRI_IAO_0000427.getIRI());
String val = getAnnotationValue(c, lap);
return val == null ? false: Boolean.valueOf(val);
}
/**
* It returns the value of the is_cyclic tag
*
* @param c
* @return boolean
*/
public boolean getIsCyclic(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_IS_CYCLIC.getTag());
String val = getAnnotationValue(c, lap);
return val == null ? false: Boolean.valueOf(val);
}
// TODO - fix for multiple ontologies
/**
* true if c is transitive in the source ontology
*
* @param c
* @return boolean
*/
public boolean getIsTransitive(OWLObjectProperty c) {
Set<OWLTransitiveObjectPropertyAxiom> ax = sourceOntology.getTransitiveObjectPropertyAxioms(c);
return ax.size()>0;
}
// TODO - fix for multiple ontologies
/**
* true if c is functional in the source ontology
*
* @param c
* @return boolean
*/
public boolean getIsFunctional(OWLObjectProperty c) {
Set<OWLFunctionalObjectPropertyAxiom> ax = sourceOntology.getFunctionalObjectPropertyAxioms(c);
return ax.size()>0;
}
// TODO - fix for multiple ontologies
public boolean getIsInverseFunctional(OWLObjectProperty c) {
Set<OWLInverseFunctionalObjectPropertyAxiom> ax = sourceOntology.getInverseFunctionalObjectPropertyAxioms(c);
return ax.size()>0;
}
// TODO - fix for multiple ontologies
public boolean getIsReflexive(OWLObjectProperty c) {
Set<OWLReflexiveObjectPropertyAxiom> ax = sourceOntology.getReflexiveObjectPropertyAxioms(c);
return ax.size()>0;
}
// TODO - fix for multiple ontologies
public boolean getIsSymmetric(OWLObjectProperty c) {
Set<OWLSymmetricObjectPropertyAxiom> ax = sourceOntology.getSymmetricObjectPropertyAxioms(c);
return ax.size()>0;
}
/**
* get the values of of the obo xref tag
*
* @param c
* @return It returns null if no xref annotation is found.
*/
public List<String> getXref(OWLObject c){
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_XREF.getTag());
Set<OWLAnnotation>anns = null;
if (c instanceof OWLEntity) {
anns = ((OWLEntity) c).getAnnotations(sourceOntology,lap);
}
else {
return null;
}
List<String> list = new ArrayList<String>();
for (OWLAnnotation a : anns) {
if (a.getValue() instanceof OWLLiteral) {
OWLLiteral val = (OWLLiteral) a.getValue();
list.add( val.getLiteral()) ;
}
}
return list;
}
/**
* get the values of of the obo xref tag
* <p>
* This is a curried FlexLoader s-expression version of {@link #getXref(OWLObject)}.
*
* @param c
* @param sargs
* @return It returns null if no xref annotation is found.
* @see #getXref(OWLObject)
*/
public List<String> getXref(OWLObject c, ArrayList<String> sargs){
return getXref(c);
}
/**
* Get the definition xrefs (IAO_0000115)
*
* @param c
* @return list of definition xrefs
*/
public List<String> getDefXref(OWLObject c){
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(Obo2OWLVocabulary.IRI_IAO_0000115.getIRI());
OWLAnnotationProperty xap = getAnnotationProperty(OboFormatTag.TAG_XREF.getTag());
List<String> list = new ArrayList<String>();
if(c instanceof OWLEntity){
for (OWLAnnotationAssertionAxiom oaax :((OWLEntity) c).getAnnotationAssertionAxioms(sourceOntology)){
if(lap.equals(oaax.getProperty())){
for(OWLAnnotation a: oaax.getAnnotations(xap)){
if(a.getValue() instanceof OWLLiteral){
list.add( ((OWLLiteral)a.getValue()).getLiteral() );
}
}
}
}
}
return list;
}
/**
* Get the definition xrefs (IAO_0000115)
* <p>
* This is a curried FlexLoader s-expression version of {@link #getDefXref(OWLObject)}.
*
* @param c
* @param sargs
* @return list of definition xrefs
* @see #getDefXref(OWLObject)
*/
public List<String> getDefXref(OWLObject c, ArrayList<String> sargs){
return getDefXref(c);
}
/**
* gets the OBO-style ID of the specified object. E.g. "GO:0008150"
*
* @param owlObject
* @return OBO-style identifier, using obo2owl mapping
*/
public String getIdentifier(OWLObject owlObject) {
return Owl2Obo.getIdentifierFromObject(owlObject, this.sourceOntology, null);
}
/**
* Same as {@link #getIdentifier(OWLObject)} but a different profile to support the FlexLoader.
* <p>
* The s-expressions arguments go unused.
*
* @param owlObject
* @param sargs (unused)
* @return OBO-style identifier, using obo2owl mapping
*
* @see #getIdentifier(OWLObject)
*/
public String getIdentifier(OWLObject owlObject, ArrayList<String> sargs) {
return getIdentifier(owlObject);
}
/**
* gets the OBO-style ID of the specified object. E.g. "GO:0008150"
*
* @param iriId
* @return OBO-style identifier, using obo2owl mapping
*/
public String getIdentifier(IRI iriId) {
return Owl2Obo.getIdentifier(iriId);
}
public IRI getIRIByIdentifier(String id) {
// special magic for finding IRIs from a non-standard identifier
// This is the case for relations (OWLObject properties) with a short hand
// or for relations with a non identifiers with-out a colon, e.g. negative_regulation
if (!id.contains(":")) {
final OWLAnnotationProperty shortHand = getDataFactory().getOWLAnnotationProperty(Obo2OWLVocabulary.IRI_OIO_shorthand.getIRI());
final OWLAnnotationProperty oboIdInOwl = getDataFactory().getOWLAnnotationProperty(Obo2Owl.trTagToIRI(OboFormatTag.TAG_ID.getTag()));
for (OWLOntology o : getAllOntologies()) {
for(OWLObjectProperty p : o.getObjectPropertiesInSignature()) {
// check for short hand or obo ID in owl
Set<OWLAnnotation> annotations = p.getAnnotations(o);
if (annotations != null) {
for (OWLAnnotation owlAnnotation : annotations) {
OWLAnnotationProperty property = owlAnnotation.getProperty();
if ((shortHand != null && shortHand.equals(property))
|| (oboIdInOwl != null && oboIdInOwl.equals(property)))
{
OWLAnnotationValue value = owlAnnotation.getValue();
if (value != null && value instanceof OWLLiteral) {
OWLLiteral literal = (OWLLiteral) value;
String shortHandLabel = literal.getLiteral();
if (id.equals(shortHandLabel)) {
return p.getIRI();
}
}
}
}
}
}
}
}
// otherwise use the obo2owl method
Obo2Owl b = new Obo2Owl();
b.setObodoc(new OBODoc());
return b.oboIdToIRI(id);
}
/**
* Given an OBO-style ID, return the corresponding OWLObject, if it is declared - otherwise null
*
* @param id - e.g. GO:0008150
* @return object with id or null
*/
public OWLObject getOWLObjectByIdentifier(String id) {
IRI iri = getIRIByIdentifier(id);
if (iri != null)
return getOWLObject(iri);
return null;
}
/**
* Given an OBO-style ID, return the corresponding OWLObjectProperty, if it is declared - otherwise null
*
* @param id - e.g. GO:0008150
* @return OWLObjectProperty with id or null
*/
public OWLObjectProperty getOWLObjectPropertyByIdentifier(String id) {
IRI iri = getIRIByIdentifier(id);
if (iri != null)
return getOWLObjectProperty(iri);
return null;
}
/**
* Given an OBO-style ID, return the corresponding OWLNamedIndividual, if it is declared - otherwise null
*
* @param id - e.g. GO:0008150
* @return OWLNamedIndividual with id or null
*/
public OWLNamedIndividual getOWLIndividualByIdentifier(String id) {
IRI iri = getIRIByIdentifier(id);
if (iri != null)
return getOWLIndividual(iri);
return null;
}
/**
* Given an OBO-style ID, return the corresponding OWLClass, if it is declared - otherwise null
*
* @param id - e.g. GO:0008150
* @return OWLClass with id or null
*/
public OWLClass getOWLClassByIdentifier(String id) {
IRI iri = getIRIByIdentifier(id);
if (iri != null)
return getOWLClass(iri);
return null;
}
/**
* fetches an OWL Object by rdfs:label
* <p>
* if there is >1 match, return the first one encountered
*
* @param label
* @return object or null
*/
public OWLObject getOWLObjectByLabel(String label) {
IRI iri = getIRIByLabel(label);
if (iri != null)
return getOWLObject(iri);
return null;
}
/**
* fetches an OWL IRI by rdfs:label
*
* @param label
* @return IRI or null
*/
public IRI getIRIByLabel(String label) {
try {
return getIRIByLabel(label, false);
} catch (SharedLabelException e) {
// note that it should be impossible to reach this point
// if getIRIByLabel is called with isEnforceUnivocal = false
e.printStackTrace();
return null;
}
}
/**
* fetches an OWL IRI by rdfs:label, optionally testing for uniqueness
* <p>
* TODO: index labels. This currently scans all labels in the ontology, which is expensive
*
* @param label
* @param isEnforceUnivocal
* @return IRI or null
* @throws SharedLabelException if >1 IRI shares input label
*/
public IRI getIRIByLabel(String label, boolean isEnforceUnivocal) throws SharedLabelException {
IRI iri = null;
for (OWLOntology o : getAllOntologies()) {
Set<OWLAnnotationAssertionAxiom> aas = o.getAxioms(AxiomType.ANNOTATION_ASSERTION);
for (OWLAnnotationAssertionAxiom aa : aas) {
OWLAnnotationValue v = aa.getValue();
OWLAnnotationProperty property = aa.getProperty();
if (property.isLabel() && v instanceof OWLLiteral) {
if (label.equals( ((OWLLiteral)v).getLiteral())) {
OWLAnnotationSubject subject = aa.getSubject();
if (subject instanceof IRI) {
if (isEnforceUnivocal) {
if (iri != null && !iri.equals((IRI)subject)) {
throw new SharedLabelException(label,iri,(IRI)subject);
}
iri = (IRI)subject;
}
else {
return (IRI)subject;
}
}
else {
//return null;
}
}
}
}
}
return iri;
}
/**
* Find the corresponding {@link OWLObject} for a given OBO-style alternate identifier.
* <p>
* WARNING: This methods scans all object annotations in all ontologies.
* This is an expensive method.
* <p>
* If there are multiple altIds use {@link #getOWLObjectsByAltId(Set)} for more efficient retrieval.
* Also consider loading all altId-mappings using {@link #getAllOWLObjectsByAltId()}.
*
* @param altIds
* @return {@link OWLObject} or null
*
* @see #getOWLObjectsByAltId(Set)
* @see #getAllOWLObjectsByAltId()
*/
public OWLObject getOWLObjectByAltId(String altIds) {
Map<String, OWLObject> map = getOWLObjectsByAltId(Collections.singleton(altIds));
return map.get(altIds);
}
/**
* Find the corresponding {@link OWLObject}s for a given set of OBO-style alternate identifiers.
* <p>
* WARNING: This methods scans all object annotations in all ontologies.
* This is an expensive method.
* <p>
* Consider loading all altId-mappings using {@link #getAllOWLObjectsByAltId()}.
*
* @param altIds
* @return map of altId to OWLObject (never null)
* @see #getAllOWLObjectsByAltId()
*/
public Map<String, OWLObject> getOWLObjectsByAltId(Set<String> altIds) {
final Map<String, OWLObject> results = new HashMap<String, OWLObject>();
final OWLAnnotationProperty altIdProperty = getAnnotationProperty(OboFormatTag.TAG_ALT_ID.getTag());
if (altIdProperty == null) {
return Collections.emptyMap();
}
for (OWLOntology o : getAllOntologies()) {
Set<OWLAnnotationAssertionAxiom> aas = o.getAxioms(AxiomType.ANNOTATION_ASSERTION);
for (OWLAnnotationAssertionAxiom aa : aas) {
OWLAnnotationValue v = aa.getValue();
OWLAnnotationProperty property = aa.getProperty();
if (altIdProperty.equals(property) && v instanceof OWLLiteral) {
String altId = ((OWLLiteral)v).getLiteral();
if (altIds.contains(altId)) {
OWLAnnotationSubject subject = aa.getSubject();
if (subject instanceof IRI) {
OWLObject obj = getOWLObject((IRI) subject);
if (obj != null) {
results.put(altId, obj);
}
}
}
}
}
}
return results;
}
/**
* Find all corresponding {@link OWLObject}s with an OBO-style alternate identifier.
* <p>
* WARNING: This methods scans all object annotations in all ontologies.
* This is an expensive method.
*
* @return map of altId to OWLObject (never null)
*/
public Map<String, OWLObject> getAllOWLObjectsByAltId() {
final Map<String, OWLObject> results = new HashMap<String, OWLObject>();
final OWLAnnotationProperty altIdProperty = getAnnotationProperty(OboFormatTag.TAG_ALT_ID.getTag());
if (altIdProperty == null) {
return Collections.emptyMap();
}
for (OWLOntology o : getAllOntologies()) {
Set<OWLAnnotationAssertionAxiom> aas = o.getAxioms(AxiomType.ANNOTATION_ASSERTION);
for (OWLAnnotationAssertionAxiom aa : aas) {
OWLAnnotationValue v = aa.getValue();
OWLAnnotationProperty property = aa.getProperty();
if (altIdProperty.equals(property) && v instanceof OWLLiteral) {
String altId = ((OWLLiteral)v).getLiteral();
OWLAnnotationSubject subject = aa.getSubject();
if (subject instanceof IRI) {
OWLObject obj = getOWLObject((IRI) subject);
if (obj != null) {
results.put(altId, obj);
}
}
}
}
}
return results;
}
/**
* Returns an OWLClass given an IRI string
* <p>
* the class must be declared in either the source ontology, or in a support ontology,
* otherwise null is returned
*
* @param s IRI string
* @return {@link OWLClass}
*/
public OWLClass getOWLClass(String s) {
IRI iri = IRI.create(s);
return getOWLClass(iri);
}
/**
* Returns an OWLClass given an IRI
* <p>
* the class must be declared in either the source ontology, or in a support ontology,
* otherwise null is returned
*
* @param iri
* @return {@link OWLClass}
*/
public OWLClass getOWLClass(IRI iri) {
OWLClass c = getDataFactory().getOWLClass(iri);
for (OWLOntology o : getAllOntologies()) {
if (o.getDeclarationAxioms(c).size() > 0) {
return c;
}
}
return null;
}
/**
* @param x
* @return {@link OWLClass}
*/
public OWLClass getOWLClass(OWLObject x) {
IRI iri;
if (x instanceof IRI) {
iri = (IRI)x;
}
else if (x instanceof OWLNamedObject) {
iri = ((OWLNamedObject)x).getIRI();
}
else {
return null;
}
return getDataFactory().getOWLClass(iri);
}
/**
* Returns an OWLNamedIndividual with this IRI <b>if it has been declared</b>
* in the source or support ontologies. Returns null otherwise.
*
* @param iri
* @return {@link OWLNamedIndividual}
*/
public OWLNamedIndividual getOWLIndividual(IRI iri) {
OWLNamedIndividual c = getDataFactory().getOWLNamedIndividual(iri);
for (OWLOntology o : getAllOntologies()) {
for (OWLDeclarationAxiom da : o.getDeclarationAxioms(c)) {
if (da.getEntity() instanceof OWLNamedIndividual) {
return (OWLNamedIndividual) da.getEntity();
}
}
}
return null;
}
/**
* @see #getOWLIndividual(IRI)
* @param s
* @return {@link OWLNamedIndividual}
*/
public OWLNamedIndividual getOWLIndividual(String s) {
IRI iri = IRI.create(s);
return getOWLIndividual(iri);
}
/**
* Returns the OWLObjectProperty with this IRI
* <p>
* Must have been declared in one of the ontologies
*
* @param iri
* @return {@link OWLObjectProperty}
*/
public OWLObjectProperty getOWLObjectProperty(String iri) {
return getOWLObjectProperty(IRI.create(iri));
}
public OWLObjectProperty getOWLObjectProperty(IRI iri) {
OWLObjectProperty p = getDataFactory().getOWLObjectProperty(iri);
for (OWLOntology o : getAllOntologies()) {
if (o.getDeclarationAxioms(p).size() > 0) {
return p;
}
}
return null;
}
public OWLAnnotationProperty getOWLAnnotationProperty(IRI iri) {
OWLAnnotationProperty p = getDataFactory().getOWLAnnotationProperty(iri);
for (OWLOntology o : getAllOntologies()) {
if (o.getDeclarationAxioms(p).size() > 0) {
return p;
}
}
return null;
}
public OWLObject getOWLObject(String s) {
return getOWLObject(IRI.create(s));
}
/**
* Returns the OWLObject with this IRI
* <p>
* Must have been declared in one of the ontologies
* <p>
* Currently OWLObject must be one of OWLClass, OWLObjectProperty or OWLNamedIndividual
* <p>
* If the ontology employs punning and there different entities with the same IRI, then
* the order of precedence is OWLClass then OWLObjectProperty then OWLNamedIndividual
*
* @param s entity IRI
* @return {@link OWLObject}
*/
public OWLObject getOWLObject(IRI s) {
OWLObject o;
o = getOWLClass(s);
if (o == null) {
o = getOWLIndividual(s);
}
if (o == null) {
o = getOWLObjectProperty(s);
}
if (o == null) {
o = getOWLAnnotationProperty(s);
}
return o;
}
/**
* gets the OBO-style ID of the source ontology IRI. E.g. "go"
*
* @return id of source ontology
*/
public String getOntologyId(){
return Owl2Obo.getOntologyId(this.getSourceOntology());
}
/**
* Retrieve the version information of all ontologies. The value is null, if
* not available.<br>
* First, checks the version IRI, than the ontology annotations for the date
* and data version.
*
* @return map of ontology identifiers and versions
*/
public Map<String, String> getVersions() {
Map<String, String> versions = new HashMap<String, String>();
for (OWLOntology o : getAllOntologies()) {
String oid = Owl2Obo.getOntologyId(o);
if (oid != null) {
String dataVersion = Owl2Obo.getDataVersion(o);
if (dataVersion != null) {
versions.put(oid, dataVersion);
}
else {
// check ontology annotations as fallback
String dateValue = getOntologyAnnotationValue(o, OboFormatTag.TAG_DATE);
if (dateValue != null) {
versions.put(oid, dateValue);
}
else {
String dataVersionValue = getOntologyAnnotationValue(o, OboFormatTag.TAG_DATA_VERSION);
if (dataVersionValue != null) {
versions.put(oid, dataVersionValue);
}
else {
versions.put(oid, null); // use null value to denote ontologies without a version
}
}
}
}
}
return versions;
}
private String getOntologyAnnotationValue(OWLOntology o, OboFormatTag tag) {
IRI dateTagIRI = Obo2Owl.trTagToIRI(tag.getTag());
Set<OWLAnnotation> annotations = o.getAnnotations();
for (OWLAnnotation annotation : annotations) {
OWLAnnotationProperty property = annotation.getProperty();
if(dateTagIRI.equals(property.getIRI())) {
OWLAnnotationValue value = annotation.getValue();
if (value != null) {
if (value instanceof IRI) {
return ((IRI) value).toString();
}
else if (value instanceof OWLLiteral) {
return ((OWLLiteral) value).getLiteral();
}
}
}
}
return null;
}
}
|
package course.labs.notificationslab;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
public class DownloaderTaskFragment extends Fragment {
private DownloadFinishedListener mCallback;
private Context mContext;
private final int MY_NOTIFICATION_ID = 11151990;
@SuppressWarnings("unused")
private static final String TAG = "Lab-Notifications";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Preserve across reconfigurations
setRetainInstance(true);
// TODO: Create new DownloaderTask that "downloads" data
DownloaderTask downloaderTask = new DownloaderTask();
Log.d(TAG, "DownloaderTask created.");
// TODO: Retrieve arguments from DownloaderTaskFragment
// Prepare them for use with DownloaderTask.
Bundle args = getArguments();
ArrayList<Integer> sRawTextFeedIds = null;
if (args != null) {
sRawTextFeedIds = args.getIntegerArrayList(MainActivity.TAG_FRIEND_RES_IDS);
Log.d(TAG, "sRawTextFeedIds = " + sRawTextFeedIds);
}
// TODO: Start the DownloaderTask
if (sRawTextFeedIds != null) {
Integer resourceIDS[] = sRawTextFeedIds.toArray(new Integer[sRawTextFeedIds.size()]);
Log.d(TAG, "resourceIDS = " + resourceIDS);
downloaderTask.execute(resourceIDS);
}
}
// Assign current hosting Activity to mCallback
// Store application context for use by downloadTweets()
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity.getApplicationContext();
// Make sure that the hosting activity has implemented
// the correct callback interface.
try {
mCallback = (DownloadFinishedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement DownloadFinishedListener");
}
}
// Null out mCallback
@Override
public void onDetach() {
super.onDetach();
mCallback = null;
}
// TODO: Implement an AsyncTask subclass called DownLoaderTask.
// This class must use the downloadTweets method (currently commented
// out). Ultimately, it must also pass newly available data back to
// the hosting Activity using the DownloadFinishedListener interface.
public class DownloaderTask extends AsyncTask<Integer, Integer, String[]> {
public DownloadFinishedListener delegate = null;
@Override
protected String[] doInBackground(Integer... resourceIDS) {
Log.d(TAG, "DownloaderTask doInBackground() resourceIDS = " + resourceIDS);
String[] result = downloadTweets(resourceIDS);
return result;
}
@Override
protected void onPostExecute(String[] strings) {
Log.d(TAG, "DownloaderTask onPostExecute() strings = " + strings);
if (mCallback != null) {
mCallback.notifyDataRefreshed(strings);
}
// super.onPostExecute(strings);
}
}
// TODO: Uncomment this helper method
// Simulates downloading Twitter data from the network
private String[] downloadTweets(Integer resourceIDS[]) {
final int simulatedDelay = 2000;
String[] feeds = new String[resourceIDS.length];
boolean downLoadCompleted = false;
try {
for (int idx = 0; idx < resourceIDS.length; idx++) {
InputStream inputStream;
BufferedReader in;
try {
// Pretend downloading takes a long time
Thread.sleep(simulatedDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
inputStream = mContext.getResources().openRawResource(
resourceIDS[idx]);
in = new BufferedReader(new InputStreamReader(inputStream));
String readLine;
StringBuffer buf = new StringBuffer();
while ((readLine = in.readLine()) != null) {
buf.append(readLine);
}
feeds[idx] = buf.toString();
if (null != in) {
in.close();
}
}
downLoadCompleted = true;
saveTweetsToFile(feeds);
} catch (IOException e) {
e.printStackTrace();
}
// Notify user that downloading has finished
notify(downLoadCompleted);
return feeds;
}
// Uncomment this helper method.
// If necessary, notifies the user that the tweet downloads are
// complete. Sends an ordered broadcast back to the BroadcastReceiver in
// MainActivity to determine whether the notification is necessary.
private void notify(final boolean success) {
final Intent restartMainActivityIntent = new Intent(mContext,
MainActivity.class);
restartMainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Sends an ordered broadcast to determine whether MainActivity is
// active and in the foreground. Creates a new BroadcastReceiver
// to receive a result indicating the state of MainActivity
// The Action for this broadcast Intent is
// MainActivity.DATA_REFRESHED_ACTION
// The result, MainActivity.IS_ALIVE, indicates that MainActivity is
// active and in the foreground.
mContext.sendOrderedBroadcast(new Intent(
MainActivity.DATA_REFRESHED_ACTION), null,
new BroadcastReceiver() {
final String failMsg = mContext
.getString(R.string.download_failed_string);
final String successMsg = mContext
.getString(R.string.download_succes_string);
final String notificationSentMsg = mContext
.getString(R.string.notification_sent_string);
@Override
public void onReceive(Context context, Intent intent) {
// TODO: Check whether or not the MainActivity
// received the broadcast
if (getResultCode() != MainActivity.IS_ALIVE) {
// TODO: If not, create a PendingIntent using
// the
// restartMainActivityIntent and set its flags
// to FLAG_UPDATE_CURRENT
PendingIntent pendingIntent = PendingIntent.getActivity(mContext.getApplicationContext(), 0, restartMainActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// Uses R.layout.custom_notification for the
// layout of the notification View. The xml
// file is in res/layout/custom_notification.xml
RemoteViews mContentView = new RemoteViews(
mContext.getPackageName(),
R.layout.custom_notification);
// TODO: Set the notification View's text to
// reflect whether the download completed
// successfully
mContentView.setTextViewText(R.id.text, "Download completed successfully.");
// TODO: Use the Notification.Builder class to
// create the Notification. You will have to set
// several pieces of information. You can use
// android.R.drawable.stat_sys_warning
// for the small icon. You should also
// setAutoCancel(true).
Notification.Builder notificationBuilder = null;
notificationBuilder = new Notification.Builder(mContext.getApplicationContext())
.setSmallIcon(android.R.drawable.stat_sys_warning)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setContent(mContentView);
// TODO: Send the notification
NotificationManager notificationManager= (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, notificationBuilder.build());
Toast.makeText(mContext, notificationSentMsg,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext,
success ? successMsg : failMsg,
Toast.LENGTH_LONG).show();
}
}
}, null, 0, null, null);
}
// Uncomment this helper method
// Saves the tweets to a file
private void saveTweetsToFile(String[] result) {
PrintWriter writer = null;
try {
FileOutputStream fos = mContext.openFileOutput(
MainActivity.TWEET_FILENAME, Context.MODE_PRIVATE);
writer = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(fos)));
for (String s : result) {
writer.println(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != writer) {
writer.close();
}
}
}
}
|
package com.pennapps.labs.pennmobile;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import com.crashlytics.android.Crashlytics;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.pennapps.labs.pennmobile.api.Labs;
import com.pennapps.labs.pennmobile.api.Serializer;
import com.pennapps.labs.pennmobile.classes.Building;
import com.pennapps.labs.pennmobile.classes.BusRoute;
import com.pennapps.labs.pennmobile.classes.BusStop;
import com.pennapps.labs.pennmobile.classes.Course;
import com.pennapps.labs.pennmobile.classes.NewDiningHall;
import com.pennapps.labs.pennmobile.classes.Person;
import com.pennapps.labs.pennmobile.classes.Venue;
import java.util.List;
import io.fabric.sdk.android.Fabric;
import retrofit.RestAdapter;
import retrofit.converter.GsonConverter;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private NavigationView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private Toolbar toolbar;
private static Labs mLabs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList = (NavigationView) findViewById(R.id.navigation);
mDrawerList.setNavigationItemSelectedListener(new DrawerItemClickListener());
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
// Set default fragment to MainFragment
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.content_frame, new MainFragment());
tx.commit();
}
@Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
return;
}
try {
WebView webView = NewsTab.currentWebView;
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
} catch (NullPointerException ignored) {
// No webview exists currently
super.onBackPressed();
}
}
@Override
public void onResume() {
super.onResume();
setTitle(R.string.main_title);
}
public void closeKeyboard() {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View view = getCurrentFocus();
if (view != null) {
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
closeKeyboard();
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements NavigationView.OnNavigationItemSelectedListener {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
item.setChecked(true);
switch (id) {
case R.id.navHome:
selectItem(0);
break;
case R.id.navRegistrar:
selectItem(1);
break;
case R.id.navDirectory:
selectItem(2);
break;
case R.id.navDining:
selectItem(3);
break;
case R.id.navTransit:
selectItem(4);
break;
case R.id.navNews:
selectItem(5);
break;
case R.id.navMap:
selectItem(6);
break;
case R.id.navSupport:
selectItem(7);
break;
case R.id.navAbout:
selectItem(8);
break;
}
return false;
}
}
private void selectItem(int position) {
Fragment fragment = null;
if (position == 0) {
fragment = new MainFragment();
} if (position == 1) {
fragment = new RegistrarSearchFragment();
} else if (position == 2) {
fragment = new DirectorySearchFragment();
} else if (position == 3) {
fragment = new DiningFragment();
} else if (position == 4) {
fragment = new TransitFragment();
} else if (position == 5) {
fragment = new NewsFragment();
} else if (position == 6) {
fragment = new MapFragment();
} else if (position == 7) {
fragment = new SupportFragment();
} else if (position == 8) {
fragment = new AboutFragment();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack(null)
.commit();
mDrawerLayout.closeDrawer(mDrawerList);
}
public void onHomeButtonClick(View v) {
if (v.getId() == R.id.registrar_img || v.getId() == R.id.registrar_cont || v.getId() == R.id.registrar_button) {
selectItem(1);
} else if (v.getId() == R.id.directory_img || v.getId() == R.id.directory_cont || v.getId() == R.id.directory_button) {
selectItem(2);
} else if (v.getId() == R.id.dining_img || v.getId() == R.id.dining_cont || v.getId() == R.id.dining_button) {
selectItem(3);
} else if (v.getId() == R.id.transit_img || v.getId() == R.id.transit_cont || v.getId() == R.id.transit_button) {
selectItem(4);
} else if (v.getId() == R.id.news_img || v.getId() == R.id.news_cont || v.getId() == R.id.news_button) {
selectItem(5);
} else if (v.getId() == R.id.map_img || v.getId() == R.id.map_cont || v.getId() == R.id.map_button) {
selectItem(6);
}
}
public static Labs getLabsInstance() {
if (mLabs == null) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(new TypeToken<List<Course>>(){}.getType(), new Serializer.CourseSerializer());
gsonBuilder.registerTypeAdapter(new TypeToken<List<Building>>(){}.getType(), new Serializer.BuildingSerializer());
gsonBuilder.registerTypeAdapter(new TypeToken<List<Person>>(){}.getType(), new Serializer.DataSerializer());
gsonBuilder.registerTypeAdapter(new TypeToken<List<Venue>>(){}.getType(), new Serializer.VenueSerializer());
gsonBuilder.registerTypeAdapter(new TypeToken<List<BusStop>>(){}.getType(), new Serializer.BusStopSerializer());
gsonBuilder.registerTypeAdapter(NewDiningHall.class, new Serializer.MenuSerializer());
gsonBuilder.registerTypeAdapter(BusRoute.class, new Serializer.BusRouteSerializer());
gsonBuilder.registerTypeAdapter(new TypeToken<List<BusRoute>>(){}.getType(), new Serializer.BusRouteListSerializer());
Gson gson = gsonBuilder.create();
RestAdapter restAdapter = new RestAdapter.Builder()
.setConverter(new GsonConverter(gson))
.setEndpoint("http://api.pennlabs.org")
.build();
mLabs = restAdapter.create(Labs.class);
}
return mLabs;
}
}
|
package io.kamax.hboxc.controller;
import io.kamax.hbox.Configuration;
import io.kamax.hbox.HyperboxAPI;
import io.kamax.hbox.comm.Answer;
import io.kamax.hbox.comm.Request;
import io.kamax.hbox.comm._AnswerReceiver;
import io.kamax.hbox.comm._RequestReceiver;
import io.kamax.hbox.comm.in.MachineIn;
import io.kamax.hbox.comm.in.ServerIn;
import io.kamax.hbox.exception.HyperboxException;
import io.kamax.hboxc.Hyperbox;
import io.kamax.hboxc.HyperboxClient;
import io.kamax.hboxc.PreferencesManager;
import io.kamax.hboxc.controller.action._ClientControllerAction;
import io.kamax.hboxc.core.ClientCore;
import io.kamax.hboxc.core.CoreReader;
import io.kamax.hboxc.event.EventManager;
import io.kamax.hboxc.exception.ServerDisconnectedException;
import io.kamax.hboxc.front._Front;
import io.kamax.hboxc.front.minimal.MiniUI;
import io.kamax.tool.logging.LogLevel;
import io.kamax.tool.logging.Logger;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public final class Controller implements _ClientMessageReceiver, _RequestReceiver {
private ClientCore core;
private _Front front = new MiniUI();
private RequestWorker msgWorker;
private Map<String, _ClientControllerAction> actionsMap;
static {
try {
PreferencesManager.init();
String defaultLogFilePath = PreferencesManager.getUserPrefPath() + File.separator + "log" + File.separator + "hbox.log";
String logFile = Configuration.getSetting("log.file", defaultLogFilePath);
if (!logFile.toLowerCase().contentEquals("none")) {
Logger.log(logFile, 4);
}
String logLevel = Configuration.getSetting("log.level", LogLevel.Info.toString());
Logger.setLevel(LogLevel.valueOf(logLevel));
Logger.raw(getHeader());
if (new File(Hyperbox.getConfigFilePath()).exists()) {
Configuration.init(Hyperbox.getConfigFilePath());
} else {
Logger.debug("Default config file does not exist, skipping: " + Hyperbox.getConfigFilePath());
}
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
}
private void loadActions() throws HyperboxException {
actionsMap = new HashMap<String, _ClientControllerAction>();
ShutdownAction.c = this;
for (_ClientControllerAction ac : HyperboxClient.getAllOrFail(_ClientControllerAction.class)) {
actionsMap.put(ac.getRegistration().toString(), ac);
}
}
public static String getHeader() {
return HyperboxAPI.getLogHeader(Hyperbox.getVersion().toString());
}
private void loadFront() throws HyperboxException {
String classToLoad = Configuration.getSetting("view.class", "io.kamax.hboxc.gui.Gui");
Logger.info("Loading frontend class: " + classToLoad);
front = HyperboxClient.loadClass(_Front.class, classToLoad);
}
public void start() throws HyperboxException {
try {
loadFront();
Logger.verbose("
for (String name : System.getenv().keySet()) {
if (name.startsWith(Configuration.CFG_ENV_PREFIX + Configuration.CFG_ENV_SEPERATOR)) {
Logger.verbose(name + " | " + System.getenv(name));
} else {
Logger.debug(name + " | " + System.getenv(name));
}
}
Logger.verbose("
Logger.verbose("
for (URL classPathEntry : ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs()) {
Logger.verbose(classPathEntry);
}
Logger.verbose("
EventManager.get().start();
loadActions();
msgWorker = new RequestWorker();
msgWorker.start();
front.start();
front.setRequestReceiver(this);
core = new ClientCore();
core.init();
front.setCoreReader(new CoreReader(core));
core.start();
HyperboxClient.initView(front);
} catch (Throwable t) {
Logger.exception(t);
front.postError(t, "Fatal error when starting: " + t.getMessage());
stop();
}
}
public void stop() {
try {
if (core != null) {
core.stop();
core.destroy();
}
if (front != null) {
front.stop();
}
if (msgWorker != null) {
msgWorker.stop();
}
EventManager.get().stop();
System.exit(0);
} catch (Throwable t) {
System.exit(1);
}
}
@Override
public void post(MessageInput mIn) {
msgWorker.post(mIn);
}
@Override
public void putRequest(Request request) {
msgWorker.post(new MessageInput(request));
}
private class RequestWorker implements _ClientMessageReceiver, Runnable {
private boolean running;
private Thread thread;
private BlockingQueue<MessageInput> queue;
@Override
public void post(MessageInput mIn) {
if (!queue.offer(mIn)) {
throw new HyperboxException("Couldn't queue the request : queue is full (" + queue.size() + " messages)");
}
}
public void start() throws HyperboxException {
running = true;
queue = new LinkedBlockingQueue<MessageInput>();
thread = new Thread(this, "FRQMGR");
thread.setDaemon(true);
thread.start();
}
public void stop() {
running = false;
thread.interrupt();
try {
thread.join(5000);
} catch (InterruptedException e) {
Logger.debug("Worker thread didn't stop on request after 5 sec");
}
}
@Override
public void run() {
Logger.verbose("RequestWorker Thread started");
while (running) {
try {
MessageInput mIn = queue.take();
Request req = mIn.getRequest();
_AnswerReceiver recv = mIn.getReceiver();
try {
if (actionsMap.containsKey(mIn.getRequest().getName())) {
_ClientControllerAction action = actionsMap.get(mIn.getRequest().getName());
recv.putAnswer(new Answer(mIn.getRequest(), action.getStartReturn()));
action.run(core, front, req, recv);
recv.putAnswer(new Answer(mIn.getRequest(), action.getFinishReturn()));
} else {
if (req.has(ServerIn.class)) {
core.getServer(req.get(ServerIn.class).getId()).sendRequest(req);
} else if (req.has(MachineIn.class)) {
core.getServer(req.get(MachineIn.class).getServerId()).sendRequest(req);
} else {
throw new HyperboxException("Server ID or Machine ID is required for generic requests");
}
}
} catch (ServerDisconnectedException e) {
Logger.error(e);
} catch (HyperboxException e) {
Logger.error("Unable to perform the request [ " + req.getName() + " ] : " + e.getMessage());
front.postError(e);
}
} catch (InterruptedException e) {
Logger.debug("Got interupted, halting");
running = false;
} catch (Throwable e) {
Logger.error("Unknown error : " + e.getMessage());
Logger.exception(e);
front.postError(e, "Unexpected error occured: " + e.getMessage());
}
}
Logger.verbose("RequestWorker Thread halted");
}
}
}
|
package com.facebook.react.views.progressbar;
import android.content.Context;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.uimanager.BaseViewManager;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.ViewManagerDelegate;
import com.facebook.react.uimanager.ViewProps;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.viewmanagers.AndroidProgressBarManagerDelegate;
import com.facebook.react.viewmanagers.AndroidProgressBarManagerInterface;
import com.facebook.yoga.YogaMeasureMode;
import com.facebook.yoga.YogaMeasureOutput;
import java.util.WeakHashMap;
/**
* Manages instances of ProgressBar. ProgressBar is wrapped in a ProgressBarContainerView because
* the style of the ProgressBar can only be set in the constructor; whenever the style of a
* ProgressBar changes, we have to drop the existing ProgressBar (if there is one) and create a new
* one with the style given.
*/
@ReactModule(name = ReactProgressBarViewManager.REACT_CLASS)
public class ReactProgressBarViewManager
extends BaseViewManager<ProgressBarContainerView, ProgressBarShadowNode>
implements AndroidProgressBarManagerInterface<ProgressBarContainerView> {
public static final String REACT_CLASS = "AndroidProgressBar";
private final WeakHashMap<Integer, Pair<Integer, Integer>> mMeasuredStyles = new WeakHashMap<>();
/* package */ static final String PROP_STYLE = "styleAttr";
/* package */ static final String PROP_ATTR = "typeAttr";
/* package */ static final String PROP_INDETERMINATE = "indeterminate";
/* package */ static final String PROP_PROGRESS = "progress";
/* package */ static final String PROP_ANIMATING = "animating";
/* package */ static final String DEFAULT_STYLE = "Normal";
private static Object sProgressBarCtorLock = new Object();
private final ViewManagerDelegate<ProgressBarContainerView> mDelegate;
/**
* We create ProgressBars on both the UI and shadow threads. There is a race condition in the
* ProgressBar constructor that may cause crashes when two ProgressBars are constructed at the
* same time on two different threads. This static ctor wrapper protects against that.
*/
public static ProgressBar createProgressBar(Context context, int style) {
synchronized (sProgressBarCtorLock) {
return new ProgressBar(context, null, style);
}
}
public ReactProgressBarViewManager() {
mDelegate = new AndroidProgressBarManagerDelegate<>(this);
}
@Override
public String getName() {
return REACT_CLASS;
}
@Override
protected ProgressBarContainerView createViewInstance(ThemedReactContext context) {
return new ProgressBarContainerView(context);
}
@Override
@ReactProp(name = PROP_STYLE)
public void setStyleAttr(ProgressBarContainerView view, @Nullable String styleName) {
view.setStyle(styleName);
}
@Override
@ReactProp(name = ViewProps.COLOR, customType = "Color")
public void setColor(ProgressBarContainerView view, @Nullable Integer color) {
view.setColor(color);
}
@Override
@ReactProp(name = PROP_INDETERMINATE)
public void setIndeterminate(ProgressBarContainerView view, boolean indeterminate) {
view.setIndeterminate(indeterminate);
}
@Override
@ReactProp(name = PROP_PROGRESS)
public void setProgress(ProgressBarContainerView view, double progress) {
view.setProgress(progress);
}
@Override
@ReactProp(name = PROP_ANIMATING)
public void setAnimating(ProgressBarContainerView view, boolean animating) {
view.setAnimating(animating);
}
@Override
public void setTestID(ProgressBarContainerView view, @Nullable String value) {
super.setTestId(view, value);
}
@Override
@ReactProp(name = PROP_ATTR)
public void setTypeAttr(ProgressBarContainerView view, @Nullable String value) {}
@Override
public ProgressBarShadowNode createShadowNodeInstance() {
return new ProgressBarShadowNode();
}
@Override
public Class<ProgressBarShadowNode> getShadowNodeClass() {
return ProgressBarShadowNode.class;
}
@Override
public void updateExtraData(ProgressBarContainerView root, Object extraData) {
// do nothing
}
@Override
protected void onAfterUpdateTransaction(ProgressBarContainerView view) {
view.apply();
}
@Override
protected ViewManagerDelegate<ProgressBarContainerView> getDelegate() {
return mDelegate;
}
/* package */ static int getStyleFromString(@Nullable String styleStr) {
if (styleStr == null) {
throw new JSApplicationIllegalArgumentException(
"ProgressBar needs to have a style, null received");
} else if (styleStr.equals("Horizontal")) {
return android.R.attr.progressBarStyleHorizontal;
} else if (styleStr.equals("Small")) {
return android.R.attr.progressBarStyleSmall;
} else if (styleStr.equals("Large")) {
return android.R.attr.progressBarStyleLarge;
} else if (styleStr.equals("Inverse")) {
return android.R.attr.progressBarStyleInverse;
} else if (styleStr.equals("SmallInverse")) {
return android.R.attr.progressBarStyleSmallInverse;
} else if (styleStr.equals("LargeInverse")) {
return android.R.attr.progressBarStyleLargeInverse;
} else if (styleStr.equals("Normal")) {
return android.R.attr.progressBarStyle;
} else {
throw new JSApplicationIllegalArgumentException("Unknown ProgressBar style: " + styleStr);
}
}
@Override
public long measure(
Context context,
ReadableMap localData,
ReadableMap props,
ReadableMap state,
float width,
YogaMeasureMode widthMode,
float height,
YogaMeasureMode heightMode,
@Nullable float[] attachmentsPositions) {
final Integer style =
ReactProgressBarViewManager.getStyleFromString(props.getString(PROP_STYLE));
Pair<Integer, Integer> value = mMeasuredStyles.get(style);
if (value == null) {
ProgressBar progressBar = ReactProgressBarViewManager.createProgressBar(context, style);
final int spec =
View.MeasureSpec.makeMeasureSpec(
ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED);
progressBar.measure(spec, spec);
value = Pair.create(progressBar.getMeasuredWidth(), progressBar.getMeasuredHeight());
mMeasuredStyles.put(style, value);
}
return YogaMeasureOutput.make(
PixelUtil.toDIPFromPixel(value.first), PixelUtil.toDIPFromPixel(value.second));
}
}
|
package org.eclipse.birt.report.designer.ui;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.preference.IPreferences;
import org.eclipse.birt.report.designer.core.CorePlugin;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.internal.ui.dnd.DNDService;
import org.eclipse.birt.report.designer.internal.ui.resourcelocator.ResourceFilter;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.preferences.PreferenceFactory;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.elements.ReportDesignConstants;
import org.eclipse.birt.report.model.api.metadata.IElementDefn;
import org.eclipse.birt.report.model.api.metadata.MetaDataConstants;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.core.runtime.content.IContentTypeManager;
import org.eclipse.gef.ui.views.palette.PaletteView;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import com.ibm.icu.util.StringTokenizer;
/**
* The main plugin class to be used in the desktop.
*
*/
public class ReportPlugin extends AbstractUIPlugin
{
protected static Logger logger = Logger.getLogger( ReportPlugin.class.getName( ) );
// Add the static String list, remeber thr ignore view for the selection
private List ignore = new ArrayList( );
/**
* The Report UI plugin ID.
*/
public static final String REPORT_UI = "org.eclipse.birt.report.designer.ui"; //$NON-NLS-1$
/**
* The shared instance.
*/
private static ReportPlugin plugin;
/**
* The cursor for selecting cells
*/
private Cursor cellLeftCursor, cellRightCursor;
// The entry delimiter
public static final String PREFERENCE_DELIMITER = ";"; //$NON-NLS-1$
public static final String SPACE = " "; //$NON-NLS-1$
public static final String DEFAULT_NAME_PREFERENCE = "designer.preview.preference.elementname.defaultname.preferencestore"; //$NON-NLS-1$
public static final String CUSTOM_NAME_PREFERENCE = "designer.preview.preference.elementname.customname.preferencestore"; //$NON-NLS-1$
public static final String DESCRIPTION_PREFERENCE = "designer.preview.preference.elementname.description.preferencestore"; //$NON-NLS-1$
public static final String LIBRARY_PREFERENCE = "designer.library.preference.libraries.description.preferencestore"; //$NON-NLS-1$
public static final String LIBRARY_WARNING_PREFERENCE = "designer.library.preference.libraries.warning.preferencestore"; //$NON-NLS-1$
public static final String TEMPLATE_PREFERENCE = "designer.preview.preference.template.description.preferencestore"; //$NON-NLS-1$
public static final String RESOURCE_PREFERENCE = "org.eclipse.birt.report.designer.ui.preferences.resourcestore"; //$NON-NLS-1$
public static final String COMMENT_PREFERENCE = "org.eclipse.birt.report.designer.ui.preference.comment.description.preferencestore"; //$NON-NLS-1$
public static final String ENABLE_COMMENT_PREFERENCE = "org.eclipse.birt.report.designer.ui.preference.enable.comment.description.preferencestore"; //$NON-NLS-1$
public static final String BIRT_RESOURCE = "resources"; //$NON-NLS-1$
private int nameCount = 0;
private static final List elementToFilte = Arrays.asList( new String[]{
ReportDesignConstants.AUTOTEXT_ITEM,
ReportDesignConstants.DATA_SET_ELEMENT,
ReportDesignConstants.DATA_SOURCE_ELEMENT,
ReportDesignConstants.EXTENDED_ITEM,
ReportDesignConstants.FREE_FORM_ITEM,
ReportDesignConstants.GRAPHIC_MASTER_PAGE_ELEMENT,
ReportDesignConstants.JOINT_DATA_SET,
ReportDesignConstants.LINE_ITEM,
ReportDesignConstants.MASTER_PAGE_ELEMENT,
ReportDesignConstants.ODA_DATA_SET,
ReportDesignConstants.ODA_DATA_SOURCE,
"Parameter", //$NON-NLS-1$
ReportDesignConstants.RECTANGLE_ITEM,
ReportDesignConstants.REPORT_ITEM,
ReportDesignConstants.SCRIPT_DATA_SET,
ReportDesignConstants.SCRIPT_DATA_SOURCE,
ReportDesignConstants.SIMPLE_DATA_SET_ELEMENT,
ReportDesignConstants.TEMPLATE_DATA_SET,
ReportDesignConstants.TEMPLATE_ELEMENT,
ReportDesignConstants.TEMPLATE_PARAMETER_DEFINITION,
// fix bug 192781
ReportDesignConstants.ODA_HIERARCHY_ELEMENT,
ReportDesignConstants.TABULAR_HIERARCHY_ELEMENT,
ReportDesignConstants.DIMENSION_ELEMENT,
ReportDesignConstants.ODA_CUBE_ELEMENT,
ReportDesignConstants.TABULAR_LEVEL_ELEMENT,
ReportDesignConstants.HIERARCHY_ELEMENT,
ReportDesignConstants.TABULAR_MEASURE_GROUP_ELEMENT,
ReportDesignConstants.ODA_DIMENSION_ELEMENT,
ReportDesignConstants.MEASURE_GROUP_ELEMENT,
ReportDesignConstants.MEASURE_ELEMENT,
ReportDesignConstants.TABULAR_CUBE_ELEMENT,
ReportDesignConstants.CUBE_ELEMENT,
ReportDesignConstants.ODA_MEASURE_ELEMENT,
ReportDesignConstants.ODA_LEVEL_ELEMENT,
ReportDesignConstants.ODA_MEASURE_GROUP_ELEMENT,
ReportDesignConstants.TABULAR_MEASURE_ELEMENT,
ReportDesignConstants.LEVEL_ELEMENT,
ReportDesignConstants.TABULAR_DIMENSION_ELEMENT,
// filter some extension items;
"CrosstabView", //$NON-NLS-1$
"DimensionView", //$NON-NLS-1$
"LevelView", //$NON-NLS-1$
"MeasureView" //$NON-NLS-1$
} );
private List reportExtensionNames;
/**
* The constructor.
*/
public ReportPlugin( )
{
super( );
plugin = this;
}
/**
* Called upon plug-in activation
*
* @param context
* the context
*/
public void start( BundleContext context ) throws Exception
{
super.start( context );
// set preference default value
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( IPreferenceConstants.PALETTE_DOCK_LOCATION,
IPreferenceConstants.DEFAULT_PALETTE_SIZE );
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( IPreferenceConstants.PALETTE_STATE,
IPreferenceConstants.DEFAULT_PALETTE_STATE );
initCellCursor( );
// set default Element names
setDefaultElementNamePreference( PreferenceFactory.getInstance( )
.getPreferences( this ) );
// set default library
setDefaultLibraryPreference( );
// set default Template
setDefaultTemplatePreference( );
// set default Resource
setDefaultResourcePreference( );
// set default Preference
setDefaultCommentPreference( );
// set default enable comment preference
setDefaultEnableCommentPreference( );
// Biding default short cut services
// Using 3.0 compatible api
PlatformUI.getWorkbench( )
.getContextSupport( )
.setKeyFilterEnabled( true );
addIgnoreViewID( "org.eclipse.birt.report.designer.ui.editors.ReportEditor" ); //$NON-NLS-1$
addIgnoreViewID( "org.eclipse.birt.report.designer.ui.editors.TemplateEditor" ); //$NON-NLS-1$
addIgnoreViewID( IPageLayout.ID_OUTLINE );
// addIgnoreViewID( AttributeView.ID );
addIgnoreViewID( PaletteView.ID );
// addIgnoreViewID( DataView.ID );
// set resource folder in DesignerConstants for use in Core plugin
CorePlugin.RESOURCE_FOLDER = getResourcePreference( );
SessionHandleAdapter.getInstance( )
.getSessionHandle( )
.setBirtResourcePath( getResourcePreference( ) );
SessionHandleAdapter.getInstance( )
.getSessionHandle( )
.setResourceFolder( getResourcePreference( ) );
Platform.getExtensionRegistry( )
.addRegistryChangeListener( DNDService.getInstance( ) );
}
/**
* Returns the version info for this plugin.
*
* @return Version string.
*/
public static String getVersion( )
{
return (String) getDefault( ).getBundle( )
.getHeaders( )
.get( org.osgi.framework.Constants.BUNDLE_VERSION );
}
/**
* Returns the infomation about the Build
*
*/
public static String getBuildInfo( )
{
return getResourceString( "Build" ); //$NON-NLS-1$
}
/**
* Returns the string from the plugin's resource bundle, or 'key' if not
* found.
*/
public static String getResourceString( String key )
{
ResourceBundle bundle = Platform.getResourceBundle( getDefault( ).getBundle( ) );
try
{
return ( bundle != null ) ? bundle.getString( key ) : key;
}
catch ( MissingResourceException e )
{
return key;
}
}
/**
* Initialize the cell Cursor instance
*/
private void initCellCursor( )
{
ImageData source = ReportPlugin.getImageDescriptor( "icons/point/cellcursor.bmp" ) //$NON-NLS-1$
.getImageData( );
ImageData mask = ReportPlugin.getImageDescriptor( "icons/point/cellcursormask.bmp" ) //$NON-NLS-1$
.getImageData( );
cellLeftCursor = new Cursor( null, source, mask, 16, 16 );
source = ReportPlugin.getImageDescriptor( "icons/point/cellrightcursor.bmp" ) //$NON-NLS-1$
.getImageData( );
mask = ReportPlugin.getImageDescriptor( "icons/point/cellrightcursormask.bmp" ) //$NON-NLS-1$
.getImageData( );
cellRightCursor = new Cursor( null, source, mask, 16, 16 );
}
/**
*
* @return the cursor used to select cells in the table
*/
public Cursor getLeftCellCursor( )
{
return cellLeftCursor;
}
/**
*
* @return the cursor used to select cells in the table
*/
public Cursor getRightCellCursor( )
{
return cellRightCursor;
}
/**
* This method is called when the plug-in is stopped
*/
public void stop( BundleContext context ) throws Exception
{
super.stop( context );
cellLeftCursor.dispose( );
Platform.getExtensionRegistry( )
.removeRegistryChangeListener( DNDService.getInstance( ) );
}
/**
* Returns the shared instance.
*/
public static ReportPlugin getDefault( )
{
return plugin;
}
/**
* Relative to UI plugin directory, example: "icons/usertableicon.gif".
*
* @param key
* @return an Image descriptor, this is useful to preserve the original
* color depth for instance.
*/
public static ImageDescriptor getImageDescriptor( String key )
{
ImageRegistry imageRegistry = ReportPlugin.getDefault( )
.getImageRegistry( );
ImageDescriptor imageDescriptor = imageRegistry.getDescriptor( key );
if ( imageDescriptor == null )
{
URL url = ReportPlugin.getDefault( ).find( new Path( key ) );
if ( null != url )
{
imageDescriptor = ImageDescriptor.createFromURL( url );
}
if ( imageDescriptor == null )
{
imageDescriptor = ImageDescriptor.getMissingImageDescriptor( );
}
imageRegistry.put( key, imageDescriptor );
}
return imageDescriptor;
}
/**
* Relative to UI plugin directory, example: "icons/usertableicon.gif".
*
* @param key
* @return an Image, do not dispose
*/
public static Image getImage( String key )
{
ImageRegistry imageRegistry = ReportPlugin.getDefault( )
.getImageRegistry( );
Image image = imageRegistry.get( key );
if ( image == null )
{
URL url = ReportPlugin.getDefault( ).find( new Path( key ) );
if ( url == null )
{
try
{
url = new URL( "file:///" + key ); //$NON-NLS-1$
}
catch ( MalformedURLException e )
{
}
}
if ( null != url )
{
image = ImageDescriptor.createFromURL( url ).createImage( );
}
if ( image == null )
{
image = ImageDescriptor.getMissingImageDescriptor( )
.createImage( );
}
imageRegistry.put( key, image );
}
return image;
}
/**
* @return the cheat sheet property preference, stored in the workbench root
*/
public static boolean readCheatSheetPreference( )
{
IWorkspace workspace = ResourcesPlugin.getWorkspace( );
try
{
String property = workspace.getRoot( )
.getPersistentProperty( new QualifiedName( "org.eclipse.birt.property", //$NON-NLS-1$
"showCheatSheet" ) ); //$NON-NLS-1$
if ( property != null )
return Boolean.valueOf( property ).booleanValue( );
}
catch ( CoreException e )
{
logger.log( Level.SEVERE, e.getMessage( ), e );
}
return true;
}
/**
* Set the show cheatsheet preference in workspace root. Used by wizards
*/
public static void writeCheatSheetPreference( boolean value )
{
IWorkspace workspace = ResourcesPlugin.getWorkspace( );
try
{
workspace.getRoot( )
.setPersistentProperty( new QualifiedName( "org.eclipse.birt.property", //$NON-NLS-1$
"showCheatSheet" ), //$NON-NLS-1$
String.valueOf( value ) );
}
catch ( CoreException e )
{
logger.log( Level.SEVERE, e.getMessage( ), e );
}
}
/**
* Returns the workspace instance.
*/
public static IWorkspace getWorkspace( )
{
return ResourcesPlugin.getWorkspace( );
}
/**
* Set default element names for preference
*
* @param store
* The preference for store
*/
private void setDefaultElementNamePreference( IPreferences store )
{
List tmpList = DEUtil.getMetaDataDictionary( ).getElements( );
List tmpList2 = DEUtil.getMetaDataDictionary( ).getExtensions( );
tmpList.addAll( tmpList2 );
int i;
StringBuffer bufferDefaultName = new StringBuffer( );
StringBuffer bufferCustomName = new StringBuffer( );
StringBuffer bufferPreference = new StringBuffer( );
int nameOption;
IElementDefn elementDefn;
for ( i = 0; i < tmpList.size( ); i++ )
{
elementDefn = (IElementDefn) ( tmpList.get( i ) );
nameOption = elementDefn.getNameOption( );
// only set names for the elements when the element can have a name
if ( nameOption == MetaDataConstants.NO_NAME
|| filteName( elementDefn ) )
{
continue;
}
nameCount++;
bufferDefaultName.append( elementDefn.getName( ) );
bufferDefaultName.append( PREFERENCE_DELIMITER );
bufferCustomName.append( "" ); //$NON-NLS-1$
bufferCustomName.append( PREFERENCE_DELIMITER );
appendDefaultPreference( elementDefn.getName( ), bufferPreference );
}
store.setDefault( DEFAULT_NAME_PREFERENCE, bufferDefaultName.toString( ) );
store.setDefault( CUSTOM_NAME_PREFERENCE, bufferCustomName.toString( ) );
store.setDefault( DESCRIPTION_PREFERENCE, bufferPreference.toString( ) );
initFilterMap( store, ResourceFilter.generateCVSFilter( ) );
initFilterMap( store, ResourceFilter.generateDotResourceFilter( ) );
initFilterMap( store, ResourceFilter.generateEmptyFolderFilter( ) );
// initFilterMap( store,
// ResourceFilter.generateNoResourceInFolderFilter( ) );
}
private boolean filteName( IElementDefn elementDefn )
{
return elementToFilte.indexOf( elementDefn.getName( ) ) != -1;
}
/**
* Append default description to the Stringbuffer according to each
* defaultName
*
* @param defaultName
* The default Name preference The Stringbuffer which string
* added to
*/
private void appendDefaultPreference( String defaultName,
StringBuffer preference )
{
if ( defaultName.equals( ReportDesignConstants.DATA_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.dataReportItem" ) ); //$NON-NLS-1$
}
else if ( defaultName.equals( ReportDesignConstants.GRID_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.gridReportItem" ) ); //$NON-NLS-1$
}
else if ( defaultName.equals( ReportDesignConstants.IMAGE_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.imageReportItem" ) ); //$NON-NLS-1$
}
else if ( defaultName.equals( ReportDesignConstants.LABEL_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.labelReportItem" ) ); //$NON-NLS-1$
}
else if ( defaultName.equals( ReportDesignConstants.LIST_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.listReportItem" ) ); //$NON-NLS-1$
}
else if ( defaultName.equals( ReportDesignConstants.TABLE_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.tableReportItem" ) ); //$NON-NLS-1$
}
else if ( defaultName.equals( ReportDesignConstants.TEXT_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.textReportItem" ) ); //$NON-NLS-1$
}
else
{
preference.append( "" ); //$NON-NLS-1$
}
preference.append( PREFERENCE_DELIMITER );
}
/**
* Get default element name preference
*
* @return String[] the array of Strings of default element name preference
*/
public String[] getDefaultDefaultNamePreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( DEFAULT_NAME_PREFERENCE ) );
}
/**
* Get default custom name preference
*
* @return String[] the array of Strings of custom element name preference
*/
public String[] getDefaultCustomNamePreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( CUSTOM_NAME_PREFERENCE ) );
}
/**
* Get default description preference
*
* @return String[] the array of Strings of default description preference
*/
public String[] getDefaultDescriptionPreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( DESCRIPTION_PREFERENCE ) );
}
/**
* Get element name preference
*
* @return String[] the array of Strings of element name preference
*/
public String[] getDefaultNamePreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.getString( DEFAULT_NAME_PREFERENCE ) );
}
/**
* Get custom element preference
*
* @return String[] the array of Strings of custom name preference
*/
public String[] getCustomNamePreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.getString( CUSTOM_NAME_PREFERENCE ) );
}
/**
* Get description preference
*
* @return String[] the array of Strings of description preference
*/
public String[] getDescriptionPreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.getString( DESCRIPTION_PREFERENCE ) );
}
/**
* Get the custom name preference of specified element name
*
* @param defaultName
* The specified element name
* @return String The custom name gotten
*/
public String getCustomName( String defaultName )
{
int i;
String[] defaultNameArray = getDefaultNamePreference( );
String[] customNameArray = getCustomNamePreference( );
// if the length of elememnts is not equal,it means error
if ( defaultNameArray.length != customNameArray.length )
{
return null;
}
for ( i = 0; i < defaultNameArray.length; i++ )
{
if ( defaultNameArray[i].trim( ).equals( defaultName ) )
{
if ( customNameArray[i].equals( "" ) ) //$NON-NLS-1$
{
return null;
}
return new String( customNameArray[i] );
}
}
return null;
}
/**
* Convert the single string of preference into string array
*
* @param preferenceValue
* The specified element name
* @return String[] The array of strings
*/
public static String[] convert( String preferenceValue )
{
String preferenceValueCopy = new String( );
preferenceValueCopy = new String( PREFERENCE_DELIMITER )
+ preferenceValue;
String replaceString = new String( PREFERENCE_DELIMITER )
+ new String( PREFERENCE_DELIMITER );
String regrex = new String( PREFERENCE_DELIMITER )
+ SPACE
+ new String( PREFERENCE_DELIMITER );
while ( preferenceValueCopy.indexOf( replaceString ) != -1 )
{
preferenceValueCopy = preferenceValueCopy.replaceFirst( replaceString,
regrex );
}
StringTokenizer tokenizer = new StringTokenizer( preferenceValueCopy,
PREFERENCE_DELIMITER );
int tokenCount = tokenizer.countTokens( );
String[] elements = new String[tokenCount];
int i;
for ( i = 0; i < tokenCount; i++ )
{
elements[i] = tokenizer.nextToken( ).trim( );
}
return elements;
}
/**
* Convert Sting[] to String
*
* @param elements []
* elements - the Strings to be converted to the preference value
*/
public String convertStrArray2Str( String[] elements )
{
StringBuffer buffer = new StringBuffer( );
for ( int i = 0; i < elements.length; i++ )
{
buffer.append( elements[i] );
buffer.append( PREFERENCE_DELIMITER );
}
return buffer.toString( );
}
/**
* Set element names from string[]
*
* @param elements
* the array of element names
*/
public void setDefaultNamePreference( String[] elements )
{
PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.setValue( DEFAULT_NAME_PREFERENCE,
convertStrArray2Str( elements ) );
}
/**
* Set element names from string
*
* @param element
* the string of element names
*/
public void setDefaultNamePreference( String element )
{
PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.setValue( DEFAULT_NAME_PREFERENCE, element );
}
/**
* Set default names for the element names from String[]
*
* @param elements
* the array of default names
*/
public void setCustomNamePreference( String[] elements )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( CUSTOM_NAME_PREFERENCE,
convertStrArray2Str( elements ) );
}
/**
* Set default names for the element names from String
*
* @param element
* the string of default names
*/
public void setCustomNamePreference( String element )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( CUSTOM_NAME_PREFERENCE,
element );
}
/**
* Set descriptions for the element names from String[]
*
* @param elements
* the array of descriptions
*/
public void setDescriptionPreference( String[] elements )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( DESCRIPTION_PREFERENCE,
convertStrArray2Str( elements ) );
}
/**
* Set descriptions for the element names from String
*
* @param element
* the string of descriptions
*/
public void setDescriptionPreference( String element )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( DESCRIPTION_PREFERENCE,
element );
}
/**
* Get the count of the element names
*
*/
public int getCount( )
{
return nameCount;
}
/**
* Set the bad words preference
*
* @param elements []
* elements - the Strings to be converted to the preference value
*/
public void setLibraryPreference( String[] elements )
{
StringBuffer buffer = new StringBuffer( );
for ( int i = 0; i < elements.length; i++ )
{
buffer.append( elements[i] );
buffer.append( PREFERENCE_DELIMITER );
}
PreferenceFactory.getInstance( )
.getPreferences( this )
.setValue( LIBRARY_PREFERENCE, buffer.toString( ) );
}
/**
* Return the library preference as an array of Strings.
*
* @return String[] The array of strings of library preference
*/
public String[] getLibraryPreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this )
.getString( LIBRARY_PREFERENCE ) );
}
/**
* Set default library preference
*/
public void setDefaultLibraryPreference( )
{
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( LIBRARY_PREFERENCE, "" ); //$NON-NLS-1$
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( LIBRARY_WARNING_PREFERENCE,
MessageDialogWithToggle.PROMPT ); //$NON-NLS-1$
}
/**
* Return default library preference as an array of Strings.
*
* @return String[] The array of strings of default library preference
*/
public String[] getDefaultLibraryPreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( LIBRARY_PREFERENCE ) );
}
/**
* Return default template preference
*
* @return String The String of default template preference
*/
public String getDefaultTemplatePreference( )
{
return PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( TEMPLATE_PREFERENCE );
}
/**
* set default template preference
*
*/
public void setDefaultTemplatePreference( )
{
String defaultDir = new String( UIUtil.getHomeDirectory( ) );
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( TEMPLATE_PREFERENCE, defaultDir );
}
/**
* Return default template preference
*
* @return String The string of default template preference
*/
public String getTemplatePreference( )
{
return PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).getString( TEMPLATE_PREFERENCE );
}
/**
* set default template preference
*
*/
public void setTemplatePreference( String preference )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( TEMPLATE_PREFERENCE,
preference );
}
/**
* set default resource preference
*
*/
public void setDefaultResourcePreference( )
{
// String metaPath = Platform.getStateLocation( ReportPlugin.getDefault(
// .getBundle( ) ).toOSString( );
// if ( !metaPath.endsWith( File.separator ) )
// metaPath = metaPath + File.separator;
// metaPath = metaPath + BIRT_RESOURCE;
// File targetFolder = new File( metaPath );
// if ( !targetFolder.exists( ) )
// targetFolder.mkdirs( );
// PreferenceFactory.getInstance( ).getPreferences( this ).setDefault(
// RESOURCE_PREFERENCE, metaPath );
// //$NON-NLS-1$
// String defaultDir = new String( UIUtil.getHomeDirectory( ) );
// defaultDir = defaultDir.replace( '\\', '/' ); //$NON-NLS-1$
// //$NON-NLS-2$
// if ( !defaultDir.endsWith( "/" ) ) //$NON-NLS-1$
// defaultDir = defaultDir + "/"; //$NON-NLS-1$
// defaultDir = defaultDir + BIRT_RESOURCE;
// if ( !defaultDir.endsWith( "/" ) ) //$NON-NLS-1$
// defaultDir = defaultDir + "/"; //$NON-NLS-1$
// File targetFolder = new File( defaultDir );
// if ( !targetFolder.exists( ) )
// targetFolder.mkdirs( );
// bug 151361, set default resource folder empty
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( RESOURCE_PREFERENCE, "" ); //$NON-NLS-1$
}
/**
* Return default resouce preference
*
* @return String The String of default resource preference
*/
public String getDefaultResourcePreference( )
{
return PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( RESOURCE_PREFERENCE );
}
/**
* Return resource preference
*
* @return String The string of resource preference
*/
public String getResourcePreference( )
{
return PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).getString( RESOURCE_PREFERENCE );
}
/**
* Return specified project's resource preference
*
* @param project
*
* @return String The string of resource preference
*/
public String getResourcePreference( IProject project )
{
return PreferenceFactory.getInstance( )
.getPreferences( this, project )
.getString( RESOURCE_PREFERENCE );
}
/**
* set resource preference
*
*/
public void setResourcePreference( String preference )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( RESOURCE_PREFERENCE,
preference );
CorePlugin.RESOURCE_FOLDER = preference;
}
/**
* Add View ID into ignore view list.
*
* @param str
*/
public void addIgnoreViewID( String str )
{
ignore.add( str );
}
/**
* Remove View ID from ignore view list.
*
* @param str
*/
public void removeIgnoreViewID( String str )
{
ignore.remove( str );
}
/**
* Test whether the View ID is in the ignore view list.
*
* @param str
* @return
*/
public boolean containIgnoreViewID( String str )
{
return ignore.contains( str );
}
/**
* set default comment preference
*
*/
public void setDefaultCommentPreference( )
{
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( COMMENT_PREFERENCE,
Messages.getString( "org.eclipse.birt.report.designer.ui.preference.commenttemplates.defaultcomment" ) ); //$NON-NLS-1$
}
/**
* Return default comment preference
*
* @return String The string of default comment preference
*/
public String getDefaultCommentPreference( )
{
return PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( COMMENT_PREFERENCE );
}
/**
* Return comment preference
*
* @return String The string of comment preference
*/
public String getCommentPreference( )
{
return PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).getString( COMMENT_PREFERENCE );
}
/**
* set comment preference
*
*/
public void setCommentPreference( String preference )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( COMMENT_PREFERENCE,
preference );
}
/**
* set enable default comment preference
*
*/
public void setDefaultEnableCommentPreference( )
{
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( ENABLE_COMMENT_PREFERENCE, true );
}
/**
* Return default enable comment preference
*
* @return boolean The bool value of default enable comment preference
*/
public boolean getDefaultEnabelCommentPreference( )
{
return PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultBoolean( ENABLE_COMMENT_PREFERENCE );
}
/**
* Return enable comment preference
*
* @return boolean The bool value of enable comment preference
*/
public boolean getEnableCommentPreference( )
{
return PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.getBoolean( ENABLE_COMMENT_PREFERENCE );
}
/**
* set enable comment preference
*
*/
public void setEnableCommentPreference( boolean preference )
{
PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.setValue( ENABLE_COMMENT_PREFERENCE, preference );
}
/**
* Returns all available extension names for report design files.
*
* @return the extension name lisr
*/
public List getReportExtensionNameList( )
{
if ( reportExtensionNames == null )
{
reportExtensionNames = new ArrayList( );
IExtensionRegistry extensionRegistry = Platform.getExtensionRegistry( );
IConfigurationElement[] elements = extensionRegistry.getConfigurationElementsFor( "org.eclipse.ui.editors" ); //$NON-NLS-1$
for ( int i = 0; i < elements.length; i++ )
{
String id = elements[i].getAttribute( "id" ); //$NON-NLS-1$
if ( "org.eclipse.birt.report.designer.ui.editors.ReportEditor".equals( id ) ) //$NON-NLS-1$
{
if ( elements[i].getAttribute( "extensions" ) != null ) //$NON-NLS-1$
{
String[] extensionNames = elements[i].getAttribute( "extensions" ) //$NON-NLS-1$
//$NON-NLS-1$
.split( "," ); //$NON-NLS-1$
for ( int j = 0; j < extensionNames.length; j++ )
{
extensionNames[j] = extensionNames[j].trim( );
if ( !reportExtensionNames.contains( extensionNames[j] ) )
{
reportExtensionNames.add( extensionNames[j] );
}
}
}
}
}
IContentTypeManager contentTypeManager = Platform.getContentTypeManager( );
IContentType contentType = contentTypeManager.getContentType( "org.eclipse.birt.report.designer.ui.editors.reportdesign" ); //$NON-NLS-1$
String[] fileSpecs = contentType.getFileSpecs( IContentType.FILE_EXTENSION_SPEC );
for ( int i = 0; i < fileSpecs.length; i++ )
{
reportExtensionNames.add( fileSpecs[i] );
}
}
return reportExtensionNames;
}
/**
* Checks if the file is a report design file by its file name
*
* @return true if the extension name of the file can be recognized as a
* report design file, or false otherwise.
*/
public boolean isReportDesignFile( String filename )
{
if ( filename != null )
{
for ( Iterator iter = ReportPlugin.getDefault( )
.getReportExtensionNameList( )
.iterator( ); iter.hasNext( ); )
{
if ( filename.endsWith( "." + (String) iter.next( ) ) ) //$NON-NLS-1$
{
return true;
}
}
}
return false;
}
public String getResourceFolder( IProject project )
{
SessionHandleAdapter.getInstance( )
.getSessionHandle( )
.setBirtResourcePath( ReportPlugin.getDefault( )
.getResourcePreference( project ) );
SessionHandleAdapter.getInstance( )
.getSessionHandle( )
.setResourceFolder( ReportPlugin.getDefault( )
.getResourcePreference( project ) );
String resourceFolder = SessionHandleAdapter.getInstance( )
.getSessionHandle( )
.getResourceFolder( );
ModuleHandle module = SessionHandleAdapter.getInstance( )
.getReportDesignHandle( );
if ( ( resourceFolder == null || resourceFolder.equals( "" ) ) //$NON-NLS-1$
&& module != null
&& module.getResourceFolder( ) != null )
{
resourceFolder = module.getResourceFolder( );
}
return resourceFolder;
}
public String getResourceFolder( )
{
return getResourceFolder( UIUtil.getCurrentProject( ) );
}
private static LinkedHashMap filterMap = new LinkedHashMap( );
private static void initFilterMap( IPreferences store, ResourceFilter filter )
{
if ( store.contains( filter.getType( ) ) )
filter.setEnabled( store.getBoolean( filter.getType( ) ) );
filterMap.put( filter.getType( ), filter );
}
public static LinkedHashMap getFilterMap( )
{
return filterMap;
}
}
|
package com.alorma.github.ui.fragment.pullrequest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alorma.github.GitskariosSettings;
import com.alorma.github.R;
import com.alorma.github.StoreCredentials;
import com.alorma.github.sdk.bean.dto.request.EditIssueBodyRequestDTO;
import com.alorma.github.sdk.bean.dto.request.EditIssueRequestDTO;
import com.alorma.github.sdk.bean.dto.request.EditIssueTitleRequestDTO;
import com.alorma.github.sdk.bean.dto.request.MergeButtonRequest;
import com.alorma.github.sdk.bean.dto.response.Head;
import com.alorma.github.sdk.bean.dto.response.Issue;
import com.alorma.github.sdk.bean.dto.response.IssueState;
import com.alorma.github.sdk.bean.dto.response.MergeButtonResponse;
import com.alorma.github.sdk.bean.dto.response.Repo;
import com.alorma.github.sdk.bean.info.IssueInfo;
import com.alorma.github.sdk.bean.info.RepoInfo;
import com.alorma.github.sdk.bean.issue.PullRequestStory;
import com.alorma.github.sdk.services.issues.EditIssueClient;
import com.alorma.github.sdk.services.pullrequest.MergePullRequestClient;
import com.alorma.github.sdk.services.pullrequest.story.PullRequestStoryLoader;
import com.alorma.github.sdk.services.repo.GetRepoClient;
import com.alorma.github.ui.ErrorHandler;
import com.alorma.github.ui.actions.AddIssueCommentAction;
import com.alorma.github.ui.activity.ContentEditorActivity;
import com.alorma.github.ui.adapter.issues.PullRequestDetailAdapter;
import com.alorma.github.ui.fragment.base.BaseFragment;
import com.alorma.github.ui.listeners.IssueDetailRequestListener;
import com.alorma.github.ui.view.pullrequest.PullRequestDetailView;
import com.alorma.github.utils.IssueUtils;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.octicons_typeface_library.Octicons;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class PullRequestConversationFragment extends BaseFragment
implements PullRequestDetailView.PullRequestActionsListener, IssueDetailRequestListener, SwipeRefreshLayout.OnRefreshListener {
public static final String ISSUE_INFO = "ISSUE_INFO";
public static final String ISSUE_INFO_REPO_NAME = "ISSUE_INFO_REPO_NAME";
public static final String ISSUE_INFO_REPO_OWNER = "ISSUE_INFO_REPO_OWNER";
public static final String ISSUE_INFO_NUMBER = "ISSUE_INFO_NUMBER";
private static final int NEW_COMMENT_REQUEST = 1243;
private static final int ISSUE_BODY_EDIT = 4252;
private IssueInfo issueInfo;
private SwipeRefreshLayout swipe;
private RecyclerView recyclerView;
private PullRequestStory pullRequestStory;
private Repo repository;
private PullRequestStoryLoaderInterface pullRequestStoryLoaderInterfaceNull = story -> {
};
private PullRequestStoryLoaderInterface pullRequestStoryLoaderInterface = pullRequestStoryLoaderInterfaceNull;
private PullRequestDetailAdapter adapter;
public static PullRequestConversationFragment newInstance(IssueInfo issueInfo) {
Bundle bundle = new Bundle();
bundle.putParcelable(ISSUE_INFO, issueInfo);
PullRequestConversationFragment fragment = new PullRequestConversationFragment();
fragment.setArguments(bundle);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.pullrequest_detail_fragment, null, false);
}
@Override
protected int getLightTheme() {
return R.style.AppTheme_Repository;
}
@Override
protected int getDarkTheme() {
return R.style.AppTheme_Dark_Repository;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
findViews(view);
if (getArguments() != null) {
issueInfo = getArguments().getParcelable(ISSUE_INFO);
if (issueInfo == null && getArguments().containsKey(ISSUE_INFO_NUMBER)) {
String name = getArguments().getString(ISSUE_INFO_REPO_NAME);
String owner = getArguments().getString(ISSUE_INFO_REPO_OWNER);
RepoInfo repoInfo = new RepoInfo();
repoInfo.name = name;
repoInfo.owner = owner;
int num = getArguments().getInt(ISSUE_INFO_NUMBER);
issueInfo = new IssueInfo();
issueInfo.repoInfo = repoInfo;
issueInfo.num = num;
}
setHasOptionsMenu(true);
getContent();
}
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (pullRequestStory != null && new IssueUtils().canComment(pullRequestStory.item)) {
getActivity().getMenuInflater().inflate(R.menu.pullrequest_detail_overview, menu);
MenuItem item = menu.findItem(R.id.action_pull_request_add_comment);
if (item != null) {
item.setIcon(new IconicsDrawable(getActivity()).icon(Octicons.Icon.oct_comment_add).actionBar().color(Color.WHITE));
}
} else {
menu.removeItem(R.id.action_pull_request_add_comment);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_pull_request_add_comment) {
onAddComment();
}
return super.onOptionsItemSelected(item);
}
private void onAddComment() {
String hint = getString(R.string.add_comment);
Intent intent = ContentEditorActivity.createLauncherIntent(getActivity(), issueInfo.repoInfo, issueInfo.num, hint, null, false, false);
startActivityForResult(intent, NEW_COMMENT_REQUEST);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
if (requestCode == NEW_COMMENT_REQUEST) {
final String body = data.getStringExtra(ContentEditorActivity.CONTENT);
AddIssueCommentAction addIssueCommentAction = getAddIssueCommentAction(body);
addIssueCommentAction.setAddCommentCallback(new CommentCallback());
addIssueCommentAction.execute();
} else if (requestCode == ISSUE_BODY_EDIT) {
EditIssueBodyRequestDTO bodyRequestDTO = new EditIssueBodyRequestDTO();
bodyRequestDTO.body = data.getStringExtra(ContentEditorActivity.CONTENT);
executeEditIssue(bodyRequestDTO);
}
}
}
public void setPullRequestStoryLoaderInterface(PullRequestStoryLoaderInterface pullRequestStoryLoaderInterface) {
this.pullRequestStoryLoaderInterface = pullRequestStoryLoaderInterface;
}
@NonNull
private AddIssueCommentAction getAddIssueCommentAction(String body) {
return new AddIssueCommentAction(issueInfo, body);
}
private void checkEditTitle() {
if (getActivity() != null) {
if (issueInfo != null && pullRequestStory != null && pullRequestStory.item != null) {
StoreCredentials credentials = new StoreCredentials(getActivity());
GitskariosSettings settings = new GitskariosSettings(getActivity());
if (settings.shouldShowDialogEditIssue()) {
if (issueInfo.repoInfo.permissions != null && issueInfo.repoInfo.permissions.push) {
showEditDialog(R.string.dialog_edit_issue_edit_title_and_body_by_owner);
} else if (pullRequestStory.item.user.login.equals(credentials.getUserName())) {
showEditDialog(R.string.dialog_edit_issue_edit_title_and_body_by_author);
}
}
}
}
}
private void showEditDialog(int content) {
new MaterialDialog.Builder(getActivity()).title(R.string.dialog_edit_issue).content(content).positiveText(R.string.ok).show();
}
private void findViews(View rootView) {
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
swipe = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe);
if (swipe != null) {
swipe.setColorSchemeResources(R.color.accent);
}
}
private void getContent() {
if (pullRequestStory == null) {
GetRepoClient repoClient = new GetRepoClient(issueInfo.repoInfo);
repoClient.observable().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Repo>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Repo repo) {
issueInfo.repoInfo.permissions = repo.permissions;
repository = repo;
loadPullRequest();
}
});
} else {
onResponseOk(pullRequestStory);
}
}
private void loadPullRequest() {
PullRequestStoryLoader pullRequestStoryLoader = new PullRequestStoryLoader(issueInfo);
pullRequestStoryLoader.observable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<PullRequestStory>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
showError();
}
@Override
public void onNext(PullRequestStory pullRequestStory) {
onResponseOk(pullRequestStory);
}
});
}
private void showError() {
MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity());
builder.title(R.string.ups);
builder.content(getString(R.string.issue_detail_error, issueInfo.toString()));
builder.positiveText(R.string.retry);
builder.negativeText(R.string.accept);
builder.onPositive((dialog, which) -> getContent());
builder.onNegative((dialog, which) -> getActivity().finish());
builder.show();
}
public void onResponseOk(final PullRequestStory pullRequestStory) {
if (getActivity() != null) {
getActivity().invalidateOptionsMenu();
this.pullRequestStory = pullRequestStory;
this.pullRequestStory.item.repository = repository;
if (pullRequestStoryLoaderInterface != null) {
pullRequestStoryLoaderInterface.onStoryLoaded(pullRequestStory);
}
swipe.setRefreshing(false);
swipe.setOnRefreshListener(this);
applyIssue();
}
}
private void applyIssue() {
checkEditTitle();
// TODO changeColor(pullRequestStory.item);
String status = getString(R.string.issue_status_open);
if (IssueState.closed == pullRequestStory.item.state) {
status = getString(R.string.issue_status_close);
} else if (pullRequestStory.item.merged) {
status = getString(R.string.pullrequest_status_merged);
}
getActivity().setTitle("#" + pullRequestStory.item.number + " " + status);
adapter = new PullRequestDetailAdapter(getActivity(), getActivity().getLayoutInflater(), pullRequestStory, issueInfo.repoInfo, this);
recyclerView.setAdapter(adapter);
getActivity().invalidateOptionsMenu();
}
@Override
public void onRefresh() {
getContent();
swipe.setOnRefreshListener(null);
}
@Override
public void onTitleEditRequest() {
new MaterialDialog.Builder(getActivity()).title(R.string.edit_issue_title)
.input(null, pullRequestStory.item.title, false, (materialDialog, charSequence) -> {
EditIssueTitleRequestDTO editIssueTitleRequestDTO = new EditIssueTitleRequestDTO();
editIssueTitleRequestDTO.title = charSequence.toString();
executeEditIssue(editIssueTitleRequestDTO);
})
.positiveText(R.string.edit_issue_button_ok)
.neutralText(R.string.edit_issue_button_neutral)
.show();
}
@Override
public void onContentEditRequest() {
String body = pullRequestStory.item.body != null ? pullRequestStory.item.body.replace("\n", "<br />") : "";
Intent launcherIntent = ContentEditorActivity.createLauncherIntent(getActivity(), issueInfo.repoInfo, issueInfo.num,
getString(R.string.edit_issue_body_hint), body, true, false);
startActivityForResult(launcherIntent, ISSUE_BODY_EDIT);
}
private void executeEditIssue(EditIssueRequestDTO editIssueRequestDTO) {
EditIssueClient client = new EditIssueClient(issueInfo, editIssueRequestDTO);
client.observable().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Issue>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
ErrorHandler.onError(getActivity(), "Issue detail", e);
}
@Override
public void onNext(Issue issue) {
getContent();
}
});
}
@Override
public void mergeRequest(Head head, Head base) {
MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity());
builder.title(R.string.merge_title);
builder.content(head.label);
builder.input(getString(R.string.merge_message), pullRequestStory.item.title, false, (materialDialog, charSequence) -> {
merge(charSequence.toString(), head.sha, issueInfo);
});
builder.inputType(InputType.TYPE_CLASS_TEXT);
dialog = builder.show();
}
private void merge(String message, String sha, IssueInfo issueInfo) {
MergeButtonRequest mergeButtonRequest = new MergeButtonRequest();
mergeButtonRequest.commit_message = message;
mergeButtonRequest.sha = sha;
MergePullRequestClient mergePullRequestClient = new MergePullRequestClient(issueInfo, mergeButtonRequest);
mergePullRequestClient.observable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<MergeButtonResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(MergeButtonResponse mergeButtonResponse) {
restartActivity();
}
});
}
private void restartActivity() {
startActivity(getActivity().getIntent());
getActivity().finish();
}
public interface PullRequestStoryLoaderInterface {
void onStoryLoaded(PullRequestStory story);
}
private class CommentCallback implements AddIssueCommentAction.AddCommentCallback {
private ProgressDialog progressDialog;
private CommentCallback() {
}
@Override
public void onCommentAdded() {
if (progressDialog != null) {
progressDialog.dismiss();
}
pullRequestStory = null;
getContent();
}
@Override
public void onCommentError() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
@Override
public void onCommentAddStarted() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage(getString(R.string.adding_comment));
progressDialog.setCancelable(true);
progressDialog.show();
}
}
}
|
package org.csstudio.swt.chart;
/** A simple <code>Sample</code> container.
* <p>
* Users can use this to store samples, or implement the Sample interface
* otherwise.
*
* @see ChartSample
* @see ChartSampleSequence
*
* @author Kay Kasemir
*/
public class ChartSampleContainer implements ChartSample
{
final private Type type;
final private double x;
final private double y;
final private double y_min, y_max;
final private String info;
/** Construct new sample from values.
* @see #ChartSampleContainer(Type, double, double, String)
*/
public ChartSampleContainer(double x, double y)
{
this(Type.Normal, x, y);
}
/** Construct new sample from values.
* @see #ChartSampleContainer(Type, double, double, String)
*/
public ChartSampleContainer(Type type, double x, double y)
{
this(type, x, y, y, y, null);
}
/** Construct new sample from values.
* @see #ChartSampleContainer(Type, double, double, String)
*/
public ChartSampleContainer(Type type, double x, double y, String info)
{
this(type, x, y, y, y, info);
}
/** Construct new sample from values.
* @param type One of the Sample.TYPE_... values
* @param x X coordinate
* @param y Y coordinate
* @param y_min minimum of Y range (low error)
* @param y_max maximum of Y range (high error)
* @param info Info string, e.g. for tooltip, or <code>null</code>.
*/
public ChartSampleContainer(Type type, double x, double y,
double y_min, double y_max, String info)
{
this.type = type;
this.x = x;
this.y = y;
this.y_min = y_min;
this.y_max = y_max;
this.info = info;
}
/** {@inheritDoc} */
public Type getType()
{
return type;
}
/** {@inheritDoc} */
public double getX()
{
return x;
}
/** {@inheritDoc} */
public double getY()
{
return y;
}
/** {@inheritDoc} */
public boolean haveMinMax()
{
return y_min != y_max;
}
/** {@inheritDoc} */
public double getMinY()
{
return y_min;
}
/** {@inheritDoc} */
public double getMaxY()
{
return y_max;
}
/** {@inheritDoc} */
public String getInfo()
{
return info;
}
}
|
package ucar.ma2;
import ucar.nc2.util.Indent;
import java.io.IOException;
import java.util.Formatter;
import java.util.Iterator;
import java.util.List;
import java.nio.ByteBuffer;
/**
* Superclass for implementations of Array of StructureData.
* <p/>
* The general way to access data in an ArrayStructure is to use
* <pre> StructureData getStructureData(Index index).</pre>
* <p/>
* For 1D arrays (or by caclulating your own recnum for nD arrays), you can also use:
* <pre> StructureData getStructureData(int recnum).</pre>
* <p/>
* Once you have a StructureData object, you can access data in a general way by using:
* <pre> Array StructureData.getArray(Member m) </pre>
* <p/>
* When dealing with large arrays of Structures, there can be significant overhead in using the generic interfaces.
* A number of convenience routines may be able to avoid extra Object creation, and so are recommended for efficiency.
* The following may avoid the overhead of creating the StructureData object:
* <pre> Array getArray(int recno, StructureMembers.Member m) </pre>
* <p/>
* The following can be convenient for accessing all the data in the ArrayStructure for one member, but its efficiency
* depends on the implementation:
* <pre> Array getMemberArray(StructureMembers.Member m) </pre>
* <p/>
* These require that you know the data types of the member data, but they are the most efficent:
* <pre>
* getScalarXXX(int recnum, Member m)
* getJavaArrayXXX(int recnum, Member m) </pre>
* where XXX is Byte, Char, Double, Float, Int, Long, Short, or String. For members that are themselves Structures,
* the equivilent is:
* <pre>
* StructureData getScalarStructure(int recnum, Member m)
* ArrayStructure getArrayStructure(int recnum, Member m) </pre>
* <p/>
* These will return any compatible type as a double or float, but will have extra overhead when the types dont match:
* <pre>
* convertScalarXXX(int recnum, Member m)
* convertJavaArrayXXX(int recnum, Member m) </pre>
* where XXX is Double or Float
*
* @author caron
* @see Array
* @see StructureData
*/
public abstract class ArrayStructure extends Array {
/* Implementation notes
ArrayStructure contains the default implementation of storing the data in individual member arrays.
ArrayStructureMA uses all of these.
ArrayStructureW uses some of these.
ArrayStructureBB override all such methods.
*/
protected StructureMembers members;
protected int nelems;
protected StructureData[] sdata;
/**
* Create a new Array of type StructureData and the given members and shape.
* dimensions.length determines the rank of the new Array.
*
* @param members a description of the structure members
* @param shape the shape of the Array.
*/
protected ArrayStructure(StructureMembers members, int[] shape) {
super(shape);
this.members = members;
this.nelems = (int) indexCalc.getSize();
}
// for subclasses to create views
protected ArrayStructure(StructureMembers members, Index ima) {
super(ima);
this.members = members;
this.nelems = (int) indexCalc.getSize();
}
// copy from javaArray to storage using the iterator: used by factory( Object);
protected void copyFrom1DJavaArray(IndexIterator iter, Object javaArray) {
Object[] ja = (Object[]) javaArray;
for (Object aJa : ja)
iter.setObjectNext(aJa);
}
// copy to javaArray from storage using the iterator: used by copyToNDJavaArray;
protected void copyTo1DJavaArray(IndexIterator iter, Object javaArray) {
Object[] ja = (Object[]) javaArray;
for (int i = 0; i < ja.length; i++)
ja[i] = iter.getObjectNext();
}
public Class getElementType() {
return StructureData.class;
}
/**
* Get the StructureMembers object.
* @return the StructureMembers object.
*/
public StructureMembers getStructureMembers() {
return members;
}
/**
* Get a list of structure members.
* @return the structure members.
*/
public List<StructureMembers.Member> getMembers() {
return members.getMembers();
}
/**
* Get a list structure member names.
* @return the structure members.
*/
public List<String> getStructureMemberNames() {
return members.getMemberNames();
}
/**
* Find a member by its name.
*
* @param memberName find member with this name
* @return StructureMembers.Member matching the name, or null if not found
*/
public StructureMembers.Member findMember(String memberName) {
return members.findMember(memberName);
}
@Override
public long getSizeBytes() {
return indexCalc.getSize() * members.getStructureSize();
}
/**
* Get the index-th StructureData of this ArrayStructure.
*
* @param i which one to get, specified by an Index.
* @return object of type StructureData.
*/
public Object getObject(Index i) {
return getObject(i.currentElement());
}
/**
* Set one of the StructureData of this ArrayStructure.
*
* @param i which one to set, specified by an Index.
* @param value must be type StructureData.
*/
public void setObject(Index i, Object value) {
setObject(i.currentElement(), value);
}
/**
* Get the index-th StructureData of this ArrayStructure.
*
* @param index which one to get, specified by an integer.
* @return object of type StructureData.
*/
public Object getObject(int index) {
return getStructureData(index);
}
/**
* Set the index-th StructureData of this ArrayStructure.
*
* @param index which one to set.
* @param value must be type StructureData.
*/
public void setObject(int index, Object value) {
if (sdata == null)
sdata = new StructureData[nelems];
sdata[index] = (StructureData) value;
}
/**
* Get the index-th StructureData of this ArrayStructure.
*
* @param i which one to get, specified by an Index.
* @return object of type StructureData.
*/
public StructureData getStructureData(Index i) {
return getStructureData(i.currentElement());
}
/**
* Get the index-th StructureData of this ArrayStructure.
*
* @param index which one to get, specified by an integer.
* @return object of type StructureData.
*/
public StructureData getStructureData(int index) {
if (sdata == null)
sdata = new StructureData[nelems];
if (index >= sdata.length)
throw new IllegalArgumentException(index + " > " + sdata.length);
if (sdata[index] == null)
sdata[index] = makeStructureData(this, index);
return sdata[index];
}
public Object getStorage() {
// this fills the sdata array
for (int i = 0; i < nelems; i++)
getStructureData(i);
return sdata;
}
abstract protected StructureData makeStructureData(ArrayStructure as, int recno);
/**
* Get the size of each StructureData object in bytes.
*
* @return the size of each StructureData object in bytes.
*/
public int getStructureSize() {
return members.getStructureSize();
}
public StructureDataIterator getStructureDataIterator() { // throws java.io.IOException {
return new ArrayStructureIterator();
}
public class ArrayStructureIterator implements StructureDataIterator {
private int count = 0;
private int size = (int) getSize();
@Override
public boolean hasNext() throws IOException {
return count < size;
}
@Override
public StructureData next() throws IOException {
return getStructureData(count++);
}
@Override
public void setBufferSize(int bytes) {
}
@Override
public StructureDataIterator reset() {
count = 0;
return this;
}
@Override
public int getCurrentRecno() {
return count-1;
}
@Override
public void finish() {
}
// debugging
public ArrayStructure getArrayStructure() { return ArrayStructure.this; }
}
/**
* Get member data of any type for a specific record as an Array.
* This may avoid the overhead of creating the StructureData object, but is equivilent to
* getStructure(recno).getArray( Member m).
*
* @param recno get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member.
* @return Array values.
*/
public Array getArray(int recno, StructureMembers.Member m) {
DataType dataType = m.getDataType();
if (dataType == DataType.DOUBLE) {
double[] pa = getJavaArrayDouble(recno, m);
return Array.factory(double.class, m.getShape(), pa);
} else if (dataType == DataType.FLOAT) {
float[] pa = getJavaArrayFloat(recno, m);
return Array.factory(float.class, m.getShape(), pa);
} else if ((dataType == DataType.BYTE) || (dataType == DataType.ENUM1)) {
byte[] pa = getJavaArrayByte(recno, m);
return Array.factory(byte.class, m.getShape(), pa);
} else if ((dataType == DataType.SHORT) || (dataType == DataType.ENUM2)) {
short[] pa = getJavaArrayShort(recno, m);
return Array.factory(short.class, m.getShape(), pa);
} else if ((dataType == DataType.INT) || (dataType == DataType.ENUM4)) {
int[] pa = getJavaArrayInt(recno, m);
return Array.factory(int.class, m.getShape(), pa);
} else if (dataType == DataType.LONG) {
long[] pa = getJavaArrayLong(recno, m);
return Array.factory(long.class, m.getShape(), pa);
} else if (dataType == DataType.CHAR) {
char[] pa = getJavaArrayChar(recno, m);
return Array.factory(char.class, m.getShape(), pa);
} else if (dataType == DataType.STRING) {
String[] pa = getJavaArrayString(recno, m);
return Array.factory(String.class, m.getShape(), pa);
} else if (dataType == DataType.STRUCTURE) {
return getArrayStructure(recno, m);
} else if (dataType == DataType.SEQUENCE) {
return getArraySequence(recno, m);
} else if (dataType == DataType.OPAQUE) {
return getArrayObject(recno, m);
}
throw new RuntimeException("Dont have implemenation for " + dataType);
}
/**
* Set data for one member, over all structures.
* This is used by VariableDS to do scale/offset.
*
* @param m set data for this StructureMembers.Member.
* @param memberArray Array values.
*/
public void setMemberArray(StructureMembers.Member m, Array memberArray) {
m.setDataArray(memberArray);
if (memberArray instanceof ArrayStructure) { // LOOK
ArrayStructure as = (ArrayStructure) memberArray;
m.setStructureMembers( as.getStructureMembers());
}
}
/**
* Extract data for one member, over all structures.
*
* @param m get data from this StructureMembers.Member.
* @return Array values.
* @throws java.io.IOException on read error (only happens for Sequences, otherwise data is already read)
*/
public Array extractMemberArray(StructureMembers.Member m) throws IOException {
if (m.getDataArray() != null)
return m.getDataArray();
DataType dataType = m.getDataType();
/* special handling for sequences
if (dataType == DataType.SEQUENCE) {
List<StructureData> sdataList = new ArrayList<StructureData>();
for (int recno=0; recno<getSize(); recno++) {
ArraySequence2 seq = getArraySequence(recno, m);
StructureDataIterator iter = seq.getStructureDataIterator();
while (iter.hasNext())
sdataList.add( iter.next());
}
ArraySequence2 seq = getArraySequence(0, m);
int size = sdataList.size();
StructureData[] sdataArray = sdataList.toArray( new StructureData[size]);
return new ArrayStructureW( seq.getStructureMembers(), new int[] {size}, sdataArray);
} */
// combine the shapes
int[] mshape = m.getShape();
int rrank = rank + mshape.length;
int[] rshape = new int[rrank];
System.arraycopy(getShape(), 0, rshape, 0, rank);
System.arraycopy(mshape, 0, rshape, rank, mshape.length);
// create an empty array to hold the result
Array result;
if (dataType == DataType.STRUCTURE) {
StructureMembers membersw = new StructureMembers(m.getStructureMembers()); // no data arrays get propagated
result = new ArrayStructureW(membersw, rshape);
} else if (dataType == DataType.OPAQUE) {
result = new ArrayObject(ByteBuffer.class, rshape);
} else {
result = Array.factory(dataType.getPrimitiveClassType(), rshape);
}
IndexIterator resultIter = result.getIndexIterator();
if (dataType == DataType.DOUBLE) {
for (int recno = 0; recno < getSize(); recno++)
copyDoubles(recno, m, resultIter);
} else if (dataType == DataType.FLOAT) {
for (int recno = 0; recno < getSize(); recno++)
copyFloats(recno, m, resultIter);
} else if ((dataType == DataType.BYTE) || (dataType == DataType.ENUM1)) {
for (int recno = 0; recno < getSize(); recno++)
copyBytes(recno, m, resultIter);
} else if ((dataType == DataType.SHORT) || (dataType == DataType.ENUM2)) {
for (int recno = 0; recno < getSize(); recno++)
copyShorts(recno, m, resultIter);
} else if ((dataType == DataType.INT) || (dataType == DataType.ENUM4)) {
for (int recno = 0; recno < getSize(); recno++)
copyInts(recno, m, resultIter);
} else if (dataType == DataType.LONG) {
for (int recno = 0; recno < getSize(); recno++)
copyLongs(recno, m, resultIter);
} else if (dataType == DataType.CHAR) {
for (int recno = 0; recno < getSize(); recno++)
copyChars(recno, m, resultIter);
} else if ((dataType == DataType.STRING) || (dataType == DataType.OPAQUE)) {
for (int recno = 0; recno < getSize(); recno++)
copyObjects(recno, m, resultIter);
} else if (dataType == DataType.STRUCTURE) {
for (int recno = 0; recno < getSize(); recno++)
copyStructures(recno, m, resultIter);
} else if (dataType == DataType.SEQUENCE) {
for (int recno = 0; recno < getSize(); recno++)
copySequences(recno, m, resultIter);
}
return result;
}
protected void copyChars(int recnum, StructureMembers.Member m, IndexIterator result) {
IndexIterator dataIter = getArray(recnum, m).getIndexIterator();
while (dataIter.hasNext())
result.setCharNext(dataIter.getCharNext());
}
protected void copyDoubles(int recnum, StructureMembers.Member m, IndexIterator result) {
IndexIterator dataIter = getArray(recnum, m).getIndexIterator();
while (dataIter.hasNext())
result.setDoubleNext(dataIter.getDoubleNext());
}
protected void copyFloats(int recnum, StructureMembers.Member m, IndexIterator result) {
IndexIterator dataIter = getArray(recnum, m).getIndexIterator();
while (dataIter.hasNext())
result.setFloatNext(dataIter.getFloatNext());
}
protected void copyBytes(int recnum, StructureMembers.Member m, IndexIterator result) {
IndexIterator dataIter = getArray(recnum, m).getIndexIterator();
while (dataIter.hasNext())
result.setByteNext(dataIter.getByteNext());
}
protected void copyShorts(int recnum, StructureMembers.Member m, IndexIterator result) {
IndexIterator dataIter = getArray(recnum, m).getIndexIterator();
while (dataIter.hasNext())
result.setShortNext(dataIter.getShortNext());
}
protected void copyInts(int recnum, StructureMembers.Member m, IndexIterator result) {
IndexIterator dataIter = getArray(recnum, m).getIndexIterator();
while (dataIter.hasNext())
result.setIntNext(dataIter.getIntNext());
}
protected void copyLongs(int recnum, StructureMembers.Member m, IndexIterator result) {
IndexIterator dataIter = getArray(recnum, m).getIndexIterator();
while (dataIter.hasNext())
result.setLongNext(dataIter.getLongNext());
}
protected void copyObjects(int recnum, StructureMembers.Member m, IndexIterator result) {
IndexIterator dataIter = getArray(recnum, m).getIndexIterator();
while (dataIter.hasNext())
result.setObjectNext(dataIter.getObjectNext());
}
// from the recnum-th structure, copy the member data into result.
// member data is itself a structure, and may be an array of structures.
protected void copyStructures(int recnum, StructureMembers.Member m, IndexIterator result) {
Array data = getArray(recnum, m);
IndexIterator dataIter = data.getIndexIterator();
while (dataIter.hasNext())
result.setObjectNext( dataIter.getObjectNext());
}
protected void copySequences(int recnum, StructureMembers.Member m, IndexIterator result) {
// there can only be one sequence, not an array; copy to an ArrayObject
Array data = getArray(recnum, m);
result.setObjectNext( data);
}
/**
* Get member data array of any type as an Object, eg, Float, Double, String, StructureData etc.
*
* @param recno get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member.
* @return value as Float, Double, etc..
*/
public Object getScalarObject(int recno, StructureMembers.Member m) {
DataType dataType = m.getDataType();
if (dataType == DataType.DOUBLE) {
return getScalarDouble(recno, m);
} else if (dataType == DataType.FLOAT) {
return getScalarFloat(recno, m);
} else if ((dataType == DataType.BYTE) || (dataType == DataType.ENUM1)) {
return getScalarByte(recno, m);
} else if ((dataType == DataType.SHORT)|| (dataType == DataType.ENUM2)) {
return getScalarShort(recno, m);
} else if ((dataType == DataType.INT)|| (dataType == DataType.ENUM4)) {
return getScalarInt(recno, m);
} else if (dataType == DataType.LONG) {
return getScalarLong(recno, m);
} else if (dataType == DataType.CHAR) {
return getScalarString(recno, m);
} else if (dataType == DataType.STRING) {
return getScalarString(recno, m);
} else if (dataType == DataType.STRUCTURE) {
return getScalarStructure(recno, m);
} else if (dataType == DataType.OPAQUE) {
ArrayObject data = (ArrayObject) m.getDataArray();
return data.getObject(recno * m.getSize()); // LOOK ??
}
throw new RuntimeException("Dont have implementation for " + dataType);
}
/**
* Get scalar value as a float, with conversion as needed. Underlying type must be convertible to float.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m member Variable.
* @return scalar float value
* @throws ForbiddenConversionException if not convertible to float.
*/
public float convertScalarFloat(int recnum, StructureMembers.Member m) {
if (m.getDataType() == DataType.FLOAT) return getScalarFloat(recnum, m);
if (m.getDataType() == DataType.DOUBLE) return (float) getScalarDouble(recnum, m);
Object o = getScalarObject(recnum, m);
if (o instanceof Number) return ((Number) o).floatValue();
throw new ForbiddenConversionException("Type is " + m.getDataType() + ", not convertible to float");
}
/**
* Get scalar value as a double, with conversion as needed. Underlying type must be convertible to double.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m member Variable.
* @return scalar double value
* @throws ForbiddenConversionException if not convertible to double.
*/
public double convertScalarDouble(int recnum, StructureMembers.Member m) {
if (m.getDataType() == DataType.DOUBLE) return getScalarDouble(recnum, m);
if (m.getDataType() == DataType.FLOAT) return (double) getScalarFloat(recnum, m);
Object o = getScalarObject(recnum, m);
if (o instanceof Number) return ((Number) o).doubleValue();
throw new ForbiddenConversionException("Type is " + m.getDataType() + ", not convertible to double");
}
/**
* Get scalar value as an int, with conversion as needed. Underlying type must be convertible to int.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m member Variable.
* @return scalar double value
* @throws ForbiddenConversionException if not convertible to double.
*/
public int convertScalarInt(int recnum, StructureMembers.Member m) {
if (m.getDataType() == DataType.INT) return getScalarInt(recnum, m);
if (m.getDataType() == DataType.SHORT) return (int) getScalarShort(recnum, m);
if (m.getDataType() == DataType.BYTE) return (int) getScalarByte(recnum, m);
if (m.getDataType() == DataType.LONG) return (int) getScalarLong(recnum, m);
Object o = getScalarObject(recnum, m);
if (o instanceof Number) return ((Number) o).intValue();
throw new ForbiddenConversionException("Type is " + m.getDataType() + ", not convertible to int");
}
public long convertScalarLong(int recnum, StructureMembers.Member m) {
if (m.getDataType() == DataType.LONG) return getScalarLong(recnum, m);
if (m.getDataType() == DataType.INT) return (long) getScalarInt(recnum, m);
if (m.getDataType() == DataType.SHORT) return (long) getScalarShort(recnum, m);
if (m.getDataType() == DataType.BYTE) return (long) getScalarByte(recnum, m);
Object o = getScalarObject(recnum, m);
if (o instanceof Number) return ((Number) o).longValue();
throw new ForbiddenConversionException("Type is " + m.getDataType() + ", not convertible to int");
}
/**
* Get scalar member data of type double.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type double.
* @return scalar double value
*/
public double getScalarDouble(int recnum, StructureMembers.Member m) {
if (m.getDataType() != DataType.DOUBLE)
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be double");
Array data = m.getDataArray();
return data.getDouble(recnum * m.getSize()); // gets first one in the array
}
/**
* Get member data of type double as a 1D array. The member data may be any rank.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type double.
* @return double[]
*/
public double[] getJavaArrayDouble(int recnum, StructureMembers.Member m) {
if (m.getDataType() != DataType.DOUBLE)
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be double");
int count = m.getSize();
Array data = m.getDataArray();
double[] pa = new double[count];
for (int i = 0; i < count; i++)
pa[i] = data.getDouble(recnum * count + i);
return pa;
}
/**
* Get scalar member data of type float.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type float.
* @return scalar double value
*/
public float getScalarFloat(int recnum, StructureMembers.Member m) {
if (m.getDataType() != DataType.FLOAT)
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be float");
Array data = m.getDataArray();
return data.getFloat(recnum * m.getSize()); // gets first one in the array
}
/**
* Get member data of type float as a 1D array.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type float.
* @return float[]
*/
public float[] getJavaArrayFloat(int recnum, StructureMembers.Member m) {
if (m.getDataType() != DataType.FLOAT)
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be float");
int count = m.getSize();
Array data = m.getDataArray();
float[] pa = new float[count];
for (int i = 0; i < count; i++)
pa[i] = data.getFloat(recnum * count + i);
return pa;
}
/**
* Get scalar member data of type byte.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type byte.
* @return scalar double value
*/
public byte getScalarByte(int recnum, StructureMembers.Member m) {
if ((m.getDataType() != DataType.BYTE) && (m.getDataType() != DataType.ENUM1))
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be byte");
Array data = m.getDataArray();
return data.getByte(recnum * m.getSize()); // gets first one in the array
}
/**
* Get member data of type byte as a 1D array.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type byte.
* @return byte[]
*/
public byte[] getJavaArrayByte(int recnum, StructureMembers.Member m) {
if ((m.getDataType() != DataType.BYTE) && (m.getDataType() != DataType.ENUM1))
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be byte");
int count = m.getSize();
Array data = m.getDataArray();
byte[] pa = new byte[count];
for (int i = 0; i < count; i++)
pa[i] = data.getByte(recnum * count + i);
return pa;
}
/**
* Get scalar member data of type short.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type short.
* @return scalar double value
*/
public short getScalarShort(int recnum, StructureMembers.Member m) {
if ((m.getDataType() != DataType.SHORT) && (m.getDataType() != DataType.ENUM2))
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be short");
Array data = m.getDataArray();
return data.getShort(recnum * m.getSize()); // gets first one in the array
}
/**
* Get member data of type short as a 1D array.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type float.
* @return short[]
*/
public short[] getJavaArrayShort(int recnum, StructureMembers.Member m) {
if ((m.getDataType() != DataType.SHORT) && (m.getDataType() != DataType.ENUM2))
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be short");
int count = m.getSize();
Array data = m.getDataArray();
short[] pa = new short[count];
for (int i = 0; i < count; i++)
pa[i] = data.getShort(recnum * count + i);
return pa;
}
/**
* Get scalar member data of type int.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type int.
* @return scalar double value
*/
public int getScalarInt(int recnum, StructureMembers.Member m) {
if ((m.getDataType() != DataType.INT) && (m.getDataType() != DataType.ENUM4))
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be int");
Array data = m.getDataArray();
return data.getInt(recnum * m.getSize()); // gets first one in the array
}
/**
* Get member data of type int as a 1D array.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type int.
* @return int[]
*/
public int[] getJavaArrayInt(int recnum, StructureMembers.Member m) {
if ((m.getDataType() != DataType.INT) && (m.getDataType() != DataType.ENUM4))
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be int");
int count = m.getSize();
Array data = m.getDataArray();
int[] pa = new int[count];
for (int i = 0; i < count; i++)
pa[i] = data.getInt(recnum * count + i);
return pa;
}
/**
* Get scalar member data of type long.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type long.
* @return scalar double value
*/
public long getScalarLong(int recnum, StructureMembers.Member m) {
if (m.getDataType() != DataType.LONG)
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be long");
Array data = m.getDataArray();
return data.getLong(recnum * m.getSize()); // gets first one in the array
}
/**
* Get member data of type long as a 1D array.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type long.
* @return long[]
*/
public long[] getJavaArrayLong(int recnum, StructureMembers.Member m) {
if (m.getDataType() != DataType.LONG)
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be long");
int count = m.getSize();
Array data = m.getDataArray();
long[] pa = new long[count];
for (int i = 0; i < count; i++)
pa[i] = data.getLong(recnum * count + i);
return pa;
}
/**
* Get scalar member data of type char.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type char.
* @return scalar double value
*/
public char getScalarChar(int recnum, StructureMembers.Member m) {
if (m.getDataType() != DataType.CHAR)
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be char");
Array data = m.getDataArray();
return data.getChar(recnum * m.getSize()); // gets first one in the array
}
/**
* Get member data of type char as a 1D array.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type char.
* @return char[]
*/
public char[] getJavaArrayChar(int recnum, StructureMembers.Member m) {
if (m.getDataType() != DataType.CHAR)
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be char");
int count = m.getSize();
Array data = m.getDataArray();
char[] pa = new char[count];
for (int i = 0; i < count; i++)
pa[i] = data.getChar(recnum * count + i);
return pa;
}
/**
* Get member data of type String or char.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type String or char.
* @return scalar String value
*/
public String getScalarString(int recnum, StructureMembers.Member m) {
if (m.getDataType() == DataType.CHAR) {
ArrayChar data = (ArrayChar) m.getDataArray();
return data.getString(recnum);
}
if (m.getDataType() == DataType.STRING) {
Array data = m.getDataArray();
return (String) data.getObject(recnum);
}
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be String or char");
}
/**
* Get member data of type String as a 1D array.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type String.
* @return String[]
*/
public String[] getJavaArrayString(int recnum, StructureMembers.Member m) {
if (m.getDataType() == DataType.STRING) {
int n = m.getSize();
String[] result = new String[n];
Array data = m.getDataArray();
for (int i = 0; i < n; i++)
result[i] = (String) data.getObject(recnum * n + i);
return result;
}
if (m.getDataType() == DataType.CHAR) {
int strlen = indexCalc.getShape(rank - 1);
int n = m.getSize() / strlen;
String[] result = new String[n];
ArrayChar data = (ArrayChar) m.getDataArray();
for (int i = 0; i < n; i++)
result[i] = data.getString((recnum * n + i) * strlen);
return result;
}
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be String or char");
}
/**
* Get member data of type Structure.
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type Structure.
* @return scalar StructureData
*/
public StructureData getScalarStructure(int recnum, StructureMembers.Member m) {
if (m.getDataType() != DataType.STRUCTURE)
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be Structure");
ArrayStructure data = (ArrayStructure) m.getDataArray();
return data.getStructureData(recnum * m.getSize()); // gets first in the array
}
/**
* Get member data of type array of Structure.
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type Structure.
* @return nested ArrayStructure.
*/
public ArrayStructure getArrayStructure(int recnum, StructureMembers.Member m) {
if ((m.getDataType() != DataType.STRUCTURE) && (m.getDataType() != DataType.SEQUENCE))
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be Structure or Sequence");
if (m.getDataType() == DataType.SEQUENCE)
return getArraySequence(recnum, m);
ArrayStructure array = (ArrayStructure) m.getDataArray();
int count = m.getSize();
StructureData[] this_sdata = new StructureData[count];
for (int i = 0; i < count; i++)
this_sdata[i] = array.getStructureData(recnum * count + i);
// make a copy of the members, but remove the data arrays, since the structureData must be used instead
StructureMembers membersw = new StructureMembers(array.getStructureMembers());
return new ArrayStructureW(membersw, m.getShape(), this_sdata);
}
/**
* Get member data of type ArraySequence
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type Structure.
* @return nested ArrayStructure.
*/
public ArraySequence getArraySequence(int recnum, StructureMembers.Member m) {
if (m.getDataType() != DataType.SEQUENCE)
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be Sequence");
// should store sequences as ArrayObject of ArraySequence objects
ArrayObject array = (ArrayObject) m.getDataArray();
return (ArraySequence) array.getObject(recnum);
}
/**
* Get member data of type ArrayObject
*
* @param recnum get data from the recnum-th StructureData of the ArrayStructure. Must be less than getSize();
* @param m get data from this StructureMembers.Member. Must be of type Structure.
* @return ArrayObject.
*/
public ArrayObject getArrayObject(int recnum, StructureMembers.Member m) {
if (m.getDataType() != DataType.OPAQUE)
throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be Sequence");
ArrayObject array = (ArrayObject) m.getDataArray();
return (ArrayObject) array.getObject(recnum); // LOOK ??
}
public void showInternal(Formatter f, Indent indent) {
f.format("%sArrayStructure %s size=%d class=%s hash=0x%x%n", indent, members.getName(), getSize(), this.getClass().getName(), hashCode());
}
public void showInternalMembers(Formatter f, Indent indent) {
f.format("%sArrayStructure %s class=%s hash=0x%x%n", indent, members.getName(), this.getClass().getName(), hashCode());
indent.incr();
for (StructureMembers.Member m : getMembers())
m.showInternal(f, indent);
indent.incr();
}
@Override
public Array createView(Index index) {
// Section viewSection = index.getSection(); / LOOK if we could do this, we could make this work
throw new UnsupportedOperationException();
}
@Override
public Array sectionNoReduce(List<Range> ranges) throws InvalidRangeException {
Section viewSection = new Section(ranges);
ArrayStructureW result = new ArrayStructureW(this.members, viewSection.getShape());
int count = 0;
Section.Iterator iter = viewSection.getIterator(getShape());
while (iter.hasNext()) {
int recno = iter.next(null);
StructureData sd = getStructureData(recno);
result.setStructureData(sd, count++);
}
return result;
}
/**
* DO NOT USE, throws UnsupportedOperationException
*/
public Array copy() {
throw new UnsupportedOperationException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public double getDouble(Index i) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public void setDouble(Index i, double value) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public float getFloat(Index i) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public void setFloat(Index i, float value) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public long getLong(Index i) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public void setLong(Index i, long value) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public int getInt(Index i) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public void setInt(Index i, int value) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public short getShort(Index i) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public void setShort(Index i, short value) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public byte getByte(Index i) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public void setByte(Index i, byte value) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public boolean getBoolean(Index i) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public void setBoolean(Index i, boolean value) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public char getChar(Index i) {
throw new ForbiddenConversionException();
}
/**
* DO NOT USE, throw ForbiddenConversionException
*/
public void setChar(Index i, char value) {
throw new ForbiddenConversionException();
}
// trusted, assumes that individual dimension lengths have been checked
// package private : mostly for iterators
public double getDouble(int index) {
throw new ForbiddenConversionException();
}
public void setDouble(int index, double value) {
throw new ForbiddenConversionException();
}
public float getFloat(int index) {
throw new ForbiddenConversionException();
}
public void setFloat(int index, float value) {
throw new ForbiddenConversionException();
}
public long getLong(int index) {
throw new ForbiddenConversionException();
}
public void setLong(int index, long value) {
throw new ForbiddenConversionException();
}
public int getInt(int index) {
throw new ForbiddenConversionException();
}
public void setInt(int index, int value) {
throw new ForbiddenConversionException();
}
public short getShort(int index) {
throw new ForbiddenConversionException();
}
public void setShort(int index, short value) {
throw new ForbiddenConversionException();
}
public byte getByte(int index) {
throw new ForbiddenConversionException();
}
public void setByte(int index, byte value) {
throw new ForbiddenConversionException();
}
public char getChar(int index) {
throw new ForbiddenConversionException();
}
public void setChar(int index, char value) {
throw new ForbiddenConversionException();
}
public boolean getBoolean(int index) {
throw new ForbiddenConversionException();
}
public void setBoolean(int index, boolean value) {
throw new ForbiddenConversionException();
}
}
|
package de.gurkenlabs.litiengine.attributes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// TODO: Auto-generated Javadoc
/**
* An attribute is a numerical representation of a property that can be adjusted using {@link AttributeModifier}s.
* <p>
* It typically doesn't adjust the raw base value (unless explicitly requested) and instead adjusts the value by registered
* modifications. This is e.g. useful when a property might only be changed for a certain period of time or we need to know the original
* value of a property.
* </p>
*
* <p>
* <i>
* An example use-case are player stats that might be affected throughout the game (e.g. via certain skills, upgrades or level-ups).
* </i>
* </p>
*
* @param <T>
* The type of the attribute value.
*/
public class Attribute<T extends Number> {
/** The modifiers. */
private final List<AttributeModifier<T>> modifiers;
/** The base value. */
private T baseValue;
/**
* Initializes a new instance of the <code>Attribute</code> class.
*
* @param initialValue
* The initial value
*/
public Attribute(final T initialValue) {
this.modifiers = new ArrayList<>();
this.baseValue = initialValue;
}
/**
* Adds the specified modifier to this attribute.
*
* @param modifier
* The modifier to be added to this instance.
*/
public void addModifier(final AttributeModifier<T> modifier) {
if (this.getModifiers().contains(modifier)) {
return;
}
this.getModifiers().add(modifier);
Collections.sort(this.getModifiers());
}
/**
* Removes the specified modifier from this attribute.
*
* @param modifier
* The modifier to be removed from this instance.
*/
public void removeModifier(final AttributeModifier<T> modifier) {
this.getModifiers().remove(modifier);
Collections.sort(this.getModifiers());
}
/**
* Gets the current value of this attribute, respecting all the registered <code>AttributeModifier</code>s.
*
* @return The current value of this attribute.
*/
public T get() {
return this.applyModifiers(this.getBase());
}
/**
* Gets the raw base value of this attribute without applying any modifications.
*
* @return The raw base value of this attribute.
*/
public T getBase() {
return this.baseValue;
}
/**
* Gets all modifiers added to this instance.
*
* @return All modifiers added to this instance.
*/
public List<AttributeModifier<T>> getModifiers() {
return this.modifiers;
}
/**
* Determines whether the specified modifier instance is added to this attribute instance.
*
* @param modifier
* The modifier to check for.
* @return True if the modifier was added to this attribute instance; otherwise false.
*/
public boolean isModifierApplied(final AttributeModifier<T> modifier) {
return this.getModifiers().contains(modifier);
}
/**
* Adjusts the base value of this attribute once with the specified modifier.
*
* @param modifier
* The modifier used to adjust this attribute's base value.
*
* @see #getBase()
* @see #setBaseValue(Number)
*/
public void modifyBaseValue(final AttributeModifier<T> modifier) {
this.baseValue = modifier.modify(this.getBase());
}
/**
* Sets the base value of this attribute.
*
* @param baseValue
* The base value to be set.
*/
public void setBaseValue(final T baseValue) {
this.baseValue = baseValue;
}
/**
* Apply modifiers.
*
* @param baseValue
* the base value
* @return the t
*/
protected T applyModifiers(final T baseValue) {
T currentValue = baseValue;
for (final AttributeModifier<T> modifier : this.getModifiers()) {
currentValue = modifier.modify(currentValue);
}
return currentValue;
}
@Override
public String toString() {
return this.get() == null ? null : this.get().toString();
}
}
|
package de.gurkenlabs.litiengine.graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import de.gurkenlabs.litiengine.input.Input;
import de.gurkenlabs.litiengine.input.Mouse;
/**
* The visual representation of the <code>Mouse</code> in the LITIengine.<br>
* It controls the appearance of the rendered cursor and allows to specify offsets from the actual mouse location.
*
* @see Mouse
*/
public final class MouseCursor implements IRenderable {
private Image image;
private AffineTransform transform;
private int offsetX;
private int offsetY;
private boolean visible;
public MouseCursor() {
this.visible = true;
}
@Override
public void render(Graphics2D g) {
if (this.isVisible()) {
final Point2D locationWithOffset = new Point2D.Double(Input.mouse().getLocation().getX() - this.getOffsetX(), Input.mouse().getLocation().getY() - this.getOffsetY());
ImageRenderer.renderTransformed(g, this.getImage(), locationWithOffset, this.getTransform());
}
}
public Image getImage() {
return this.image;
}
public AffineTransform getTransform() {
return this.transform;
}
public int getOffsetX() {
return this.offsetX;
}
public int getOffsetY() {
return this.offsetY;
}
/**
* Determines whether the cursor is currently visible (and will thereby be rendered),
* by checking the <code>visible</code> flag and whether the specified cursor image is null.
*
* @return True if the cursor is currently visible; otherwise false.
*/
public boolean isVisible() {
return this.visible && this.getImage() != null;
}
public void set(final Image img) {
this.image = img;
if (this.image != null) {
this.setOffsetX(-(this.image.getWidth(null) / 2));
this.setOffsetY(-(this.image.getHeight(null) / 2));
} else {
this.setOffsetX(0);
this.setOffsetY(0);
}
}
public void set(final Image img, final int offsetX, final int offsetY) {
this.set(img);
this.setOffset(offsetX, offsetY);
}
public void setOffset(final int x, final int y) {
this.setOffsetX(x);
this.setOffsetY(y);
}
public void setOffsetX(final int cursorOffsetX) {
this.offsetX = cursorOffsetX;
}
public void setOffsetY(final int cursorOffsetY) {
this.offsetY = cursorOffsetY;
}
public void setTransform(AffineTransform transform) {
this.transform = transform;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
}
|
import java.io.*;
import javax.swing.*;
import java.util.*;
import java.nio.*;
import java.nio.file.*;
/**
* Reads in all the neccesary csv files and loads the data into the
*
* @author Aidan, Tom, Kevin, Zach
* @version Final
*/
public class CSVreader
{
/**
* Reads in all the data from the four files containing the profile info (2 files),
* list of cities, and the list of attractions.
*/
public void run()
{
String trecData = "../TRECData/";
//String collection = "collection_2015.csv";
String collection = "collection_nyc.csv";//NYC subset used for testing
//id, city, state, lat, long
String locations = "contexts2015.csv";
String coordinates = "contexts2015coordinates.csv";
//id, attraction, description, website
String profile100 = "profiles2014-100.csv";//2014 used for testing
//id, title, description, url
String pois = "examples2014.csv";//2014 used for testing
BufferedReader br = null;
BufferedReader br2 = null;
try {
//br for context csv and br2 for coordinates csv
br = new BufferedReader(new FileReader(Paths.get(trecData + locations).toFile()));
br2 = new BufferedReader(new FileReader(Paths.get(trecData + coordinates).toFile()));
buildLocation(br, br2);
//Reads in examples2014.csv which contains the attractions rated in the profiles
br = new BufferedReader(new FileReader(Paths.get(trecData + pois).toFile()));
//bufferedtestBuildPOI();
//testBuildPOI();
buildPOI(br);
//Reads in profiles2014-100.csv which contains all the example profiles
br = new BufferedReader(new FileReader(Paths.get(trecData + profile100).toFile()));
buildProfile(br);
//Reads in collection_2015.csv which contains all possible attractions to suggest
br = new BufferedReader(new FileReader(Paths.get(trecData + collection).toFile()));
//buildCollection(br);
testBuildCollection();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
//ContextualSuggestion.suggest();
}
/**
* Creates the Context objects given the file listing the cities
*/
public void buildLocation(BufferedReader br, BufferedReader br2) throws IOException
{
System.out.println("Building Contexts");
String line = "";
//read in parameters to ignore them and jump to next line
br.readLine();
br2.readLine();
while ((line = br.readLine()) != null)
{
//combine city id, name, state, and coordinates into one String
line += ",";
line += br2.readLine();
//Separate String by every 6 commas to place values in "context" array.
String[] context = CSVSplitter.split(line,6);
//Populate hashtable using context ID as a key to reference a Context object
ContextualSuggestion.contexts.put(Integer.parseInt(context[0]),
new Context(Integer.parseInt(context[0]), context[1], context[2],
Double.parseDouble(context[4]), Double.parseDouble(context[5])));
}
br.close();
}
/**
* Creates the POI objects given the file listing the attractions
* because of commas in the description the first second and last are located
*/
public void buildPOI(BufferedReader br) throws IOException
{
System.out.println("Building Examples");
String line = "";
//read in paramters to skip them
br.readLine();
while((line = br.readLine())!=null)//Limit search to first 5 examples to avoid going over quota
{
//separate string by commas, place data into "context" array
String[] context = new String[5];
context = CSVSplitter.split(line, 5);
//populate hashtable using attr ID as a key to reference the merged Suggestion object
ContextualSuggestion.pois.put(Integer.parseInt(context[0]), Merging.merge(context[2], Integer.parseInt(context[1])));
}
br.close();
}
/**
* Read examples from a text file instead of querying the APIs
*/
public void testBuildPOI() throws IOException
{
Scanner in = new Scanner(new File("TestInputExamples.txt"));
String line = " ";
String name = "";
ArrayList<String> cats = new ArrayList<String>();
int index = 101;
//Read through the file
while (in.hasNextLine())
{
name = in.nextLine();
System.out.println(name);
line = " ";
//Check for the blank line after the list of categories
while (!line.equals("") && in.hasNextLine())
{
if(line.equals(""))
break;
line = in.nextLine();
cats.add(line);
}
ContextualSuggestion.pois.put(index, new Suggestion(name, 1, 2, 3, cats));
index++;
cats = new ArrayList<String>();
}
}
public void bufferedtestBuildPOI() throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(Paths.get("TestInputExamples.txt").toFile()));
String line = " ";
String name = "";
ArrayList<String> cats = new ArrayList<String>();
int index = 101;
//Read through the file
while( (line = br.readLine()) != null )
{
name = line;
System.out.println(name);
line = br.readLine();
while( line != null && !line.equals(""))
{
cats.add(line);
line = br.readLine();
}
ContextualSuggestion.pois.put(index, new Suggestion(name, 1, 2, 3, cats));
index++;
cats = new ArrayList<String>();
}
br.close();
}
public void buildProfile(BufferedReader br) throws IOException
{
System.out.println("Building Profiles, ratings");
String line = "";
br.readLine();
int person_id = -1;
while ((line = br.readLine()) != null)
{
// use comma as separator
String[] context = line.split(",");
//Get the profile id and check if it is the current profile
int temp = Integer.parseInt(context[0]);
if(temp != person_id)
{
person_id = temp;
ContextualSuggestion.profiles.put(person_id, new Profile(person_id));
}
int att_id = Integer.parseInt(context[1]);
int t_rating = Integer.parseInt(context[2]);
int u_rating = Integer.parseInt(context[3]);
Profile person = ContextualSuggestion.profiles.get(person_id);
person.attr_ratings.put(att_id, t_rating); //only title rating for now
//if attr rank is 3 or 4, place in positive category array for profile
//id attr rank is 0 or 1, place in negative catrgory array for profile
Suggestion curr = ContextualSuggestion.pois.get(att_id);
for (String cat : curr.category)
{
if(cat.equals("bar") && person_id == 26)
{
System.out.println("Bar: \t" + curr.title + "\t" + t_rating);
}
if (person.cat_count.get(cat) == null)
{
person.cat_count.put(cat, 0.0);
person.cat_occurance.put(cat, 0);
}
double[] scores = new double[]{-4.0, -2.0, 1.0, 2.0, 4.0};
if(t_rating != -1)
{
person.cat_count.put(cat, person.cat_count.get(cat) + scores[t_rating]);
person.cat_occurance.put(cat, person.cat_occurance.get(cat) +1);
}
System.out.println("\t\t" + scores[t_rating]);
}
}
//go through each category in the hash table and divide by its frequency to get avg
Set<Integer> people = ContextualSuggestion.profiles.keySet();
for(Integer num : people)
{
Profile person = ContextualSuggestion.profiles.get(num);
Set<String> keys = person.cat_occurance.keySet();
for(String cat: keys)
{
person.cat_count.put(cat, (person.cat_count.get(cat)/person.cat_occurance.get(cat)));
}
}
br.close();
}
public void buildCollection(BufferedReader br) throws IOException
{
System.out.println("Building Collection");
String line = "";
ArrayList<Suggestion> temp = null;
while ((line = br.readLine()) != null)
{
//line = br.readLine();
//separate string by commas, place data into "context" array
String[] context = CSVSplitter.split(line, 4);
String attrID = (context[0].split("-"))[1];
//populate hashtable using attr ID as a key to reference the merged Suggestion object
if (ContextualSuggestion.theCollection.get(Integer.parseInt(context[1])) == null)
{//If first spot is empty
temp = new ArrayList<Suggestion>();
temp.add(Merging.merge(context[3], Integer.parseInt(context[1])));
ContextualSuggestion.theCollection.put(Integer.parseInt(context[1]), temp);
}
else
{//Already contains an arraylist
temp = ContextualSuggestion.theCollection.get(Integer.parseInt(context[1]));
temp.add(Merging.merge(context[3], Integer.parseInt(context[1])));
ContextualSuggestion.theCollection.put(Integer.parseInt(context[1]), temp);
}
}
br.close();
}
/**
* Read colleciton from a text file instead of querying the APIs
*/
public void testBuildCollection() throws IOException
{
Scanner in = new Scanner(new File("TestInputCollection.txt"));
String line = " ";
String name = "";
ArrayList<Suggestion> temp = null;
ArrayList<String> cats = new ArrayList<String>();
//Read through the file
while (in.hasNextLine())
{
name = in.nextLine();
line = " ";
//Check for the blank line after the list of categories
while (!line.equals("") && in.hasNextLine())
{
line = in.nextLine();
if(line.equals(""))
break;
cats.add(line);
}
if (ContextualSuggestion.theCollection.get(151) == null)
{//If first spot is empty
temp = new ArrayList<Suggestion>();
temp.add(new Suggestion(name, 1, 2, 3, cats));
ContextualSuggestion.theCollection.put(151, temp);
}
else
{//Already contains an arraylist
temp = ContextualSuggestion.theCollection.get(151);
temp.add(new Suggestion(name, 1, 2, 3, cats));
ContextualSuggestion.theCollection.put(151, temp);
}
cats = new ArrayList<String>();
}
}
/**
* csv file must be sorted
*/
public static ArrayList<String> getLocations(String id, File csvFile) throws IOException
{
// TODO: binary-serachify this
String line;
ArrayList<String> arr = new ArrayList<>();
Scanner s = new Scanner(csvFile);
while (s.hasNextLine()) {
line = s.nextLine();
String lineID = getCSVElement(1, line);
if (id.compareTo(lineID) < 0) // passed ID
break;
else if (id.equals(lineID))
arr.add(line);
}
s.close();
return arr;
}
/**
* Get the n'th element of a csv line starting at zero (no quotes)
* @param elemIndex n
* @param csvLine csv line
* @return the n'th element of a csv line starting at zero
*/
public static String getCSVElement(int elemIndex, String csvLine)
{
return csvLine.split(",", elemIndex + 2)[elemIndex];
}
public static void test() throws IOException {
ArrayList<String> lol = getLocations("777", new File("../collection_sorted_2015.csv"));
for (String lel : lol)
System.out.println(lel);
System.out.println("done");
}
public static void main(String[] args)
{
CSVreader obj = new CSVreader();
obj.run();
}
}
|
package sfBugs;
public class Bug1911620 {
public long getLongMinus1(String longStr) {
long l = Long.valueOf(longStr);
return --l;
}
public long getLongPlus1(String longStr) {
long l = Long.valueOf(longStr);
return ++l;
}
public long getLongWithDLS(String longStr) {
long l = Long.valueOf(longStr);
long l2 = l; // This is the only place FindBugs should give a DLS warning
return l;
}
public long getLongMinus1_2(String longStr) {
long l = Long.valueOf(longStr);
--l;
return l;
}
public long getLongMinus2(String longStr) {
long l = Long.valueOf(longStr);
return l - 2;
}
public int getIntMinus1(String intStr) {
int i = Integer.valueOf(intStr);
return --i;
}
}
|
package com.palantir.atlasdb.keyvalue.partition;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.common.primitives.UnsignedBytes;
import com.palantir.atlasdb.keyvalue.api.Cell;
import com.palantir.atlasdb.keyvalue.api.KeyValueService;
import com.palantir.atlasdb.keyvalue.api.RangeRequest;
import com.palantir.atlasdb.keyvalue.api.RangeRequests;
import com.palantir.atlasdb.keyvalue.partition.api.PartitionMap;
public final class BasicPartitionMap implements PartitionMap {
private static final Logger log = LoggerFactory.getLogger(BasicPartitionMap.class);
private final QuorumParameters quorumParameters;
private final CycleMap<byte[], KeyValueService> ring;
private final Map<KeyValueService, String> rackByKvs;
private final Set<KeyValueService> services;
private final Set<String> racks;
private BasicPartitionMap(QuorumParameters quorumParameters,
NavigableMap<byte[], KeyValueService> ring,
Map<KeyValueService, String> rackByKvs) {
this.quorumParameters = quorumParameters;
this.ring = CycleMap.wrap(ring);
this.rackByKvs = rackByKvs;
this.services = ImmutableSet.<KeyValueService> builder().addAll(ring.values()).build();
this.racks = ImmutableSet.<String> builder().addAll(rackByKvs.values()).build();
Preconditions.checkArgument(quorumParameters.getReplicationFactor() <= racks.size());
}
public static BasicPartitionMap create(QuorumParameters quorumParameters,
NavigableMap<byte[], KeyValueService> ring,
Map<KeyValueService, String> rackByKvs) {
return new BasicPartitionMap(quorumParameters, ring, rackByKvs);
}
public static BasicPartitionMap create(QuorumParameters quorumParameters,
NavigableMap<byte[], KeyValueService> ring) {
Map<KeyValueService, String> rackByKvs = Maps.newHashMap();
// Assume each kvs to be in separate rack if no info is available.
for (KeyValueService kvs : ImmutableSet.<KeyValueService> builder().addAll(ring.values()).build()) {
rackByKvs.put(kvs, "" + kvs.hashCode());
}
return create(quorumParameters, ring, rackByKvs);
}
private Set<KeyValueService> getServicesHavingRow(byte[] key) {
Set<KeyValueService> result = Sets.newHashSet();
Set<String> racks = Sets.newHashSet();
byte[] point = key;
while (result.size() < quorumParameters.getReplicationFactor()) {
point = ring.nextKey(point);
KeyValueService kvs = ring.get(point);
String rack = rackByKvs.get(kvs);
if (!racks.contains(rack)) {
result.add(ring.get(point));
racks.add(rack);
}
}
assert result.size() == quorumParameters.getReplicationFactor();
return result;
}
@Override
public Multimap<ConsistentRingRangeRequest, KeyValueService> getServicesForRangeRead(String tableName,
RangeRequest range) {
if (range.isReverse()) {
throw new UnsupportedOperationException();
}
Multimap<ConsistentRingRangeRequest, KeyValueService> result = LinkedHashMultimap.create();
byte[] rangeStart = range.getStartInclusive();
if (range.getStartInclusive().length == 0) {
rangeStart = RangeRequests.getFirstRowName();
}
// Note that there is no wrapping around when traversing the circle with the key.
// Ie. the range does not go over through "zero" of the ring.
while (range.inRange(rangeStart)) {
// Setup the consistent subrange
byte[] rangeEnd = ring.higherKey(rangeStart);
if (rangeEnd == null || !range.inRange(rangeEnd)) {
rangeEnd = range.getEndExclusive();
}
ConsistentRingRangeRequest crrr = ConsistentRingRangeRequest.of(RangeRequest.builder(
range.isReverse()).startRowInclusive(rangeStart).endRowExclusive(rangeEnd).build());
// We have now the "consistent" subrange which means that
// every service having the (inclusive) start row will also
// have all the other rows belonging to this range.
// No other services will have any of these rows.
result.putAll(crrr, getServicesHavingRow(rangeStart));
// Proceed with next range
rangeStart = ring.higherKey(rangeStart);
// We are out of ranges to consider.
if (rangeStart == null) {
break;
}
}
return result;
}
@Override
public Map<KeyValueService, NavigableSet<byte[]>> getServicesForRowsRead(String tableName,
Iterable<byte[]> rows) {
Map<KeyValueService, NavigableSet<byte[]>> result = Maps.newHashMap();
for (byte[] row : rows) {
Set<KeyValueService> services = getServicesHavingRow(row);
for (KeyValueService kvs : services) {
if (!result.containsKey(kvs)) {
result.put(
kvs,
Sets.<byte[]> newTreeSet(UnsignedBytes.lexicographicalComparator()));
}
assert !result.get(kvs).contains(row);
result.get(kvs).add(row);
}
}
return result;
}
@Override
public Map<KeyValueService, Map<Cell, Long>> getServicesForCellsRead(String tableName,
Map<Cell, Long> timestampByCell) {
Map<KeyValueService, Map<Cell, Long>> result = Maps.newHashMap();
for (Map.Entry<Cell, Long> e : timestampByCell.entrySet()) {
Set<KeyValueService> services = getServicesHavingRow(e.getKey().getRowName());
for (KeyValueService kvs : services) {
if (!result.containsKey(kvs)) {
result.put(kvs, Maps.<Cell, Long> newHashMap());
}
assert !result.get(kvs).containsKey(e.getKey());
result.get(kvs).put(e.getKey(), e.getValue());
}
}
return result;
}
@Override
public Map<KeyValueService, Set<Cell>> getServicesForCellsRead(String tableName, Set<Cell> cells) {
Map<KeyValueService, Set<Cell>> result = Maps.newHashMap();
for (Cell cell : cells) {
Set<KeyValueService> services = getServicesHavingRow(cell.getRowName());
for (KeyValueService kvs : services) {
if (!result.containsKey(kvs)) {
result.put(kvs, Sets.<Cell> newHashSet());
}
assert (result.get(kvs).contains(cell) == false);
result.get(kvs).add(cell);
}
}
return result;
}
@Override
public Map<KeyValueService, Map<Cell, byte[]>> getServicesForCellsWrite(String tableName,
Map<Cell, byte[]> values) {
Map<KeyValueService, Map<Cell, byte[]>> result = Maps.newHashMap();
for (Map.Entry<Cell, byte[]> e : values.entrySet()) {
Set<KeyValueService> services = getServicesHavingRow(e.getKey().getRowName());
for (KeyValueService kvs : services) {
if (!result.containsKey(kvs)) {
result.put(kvs, Maps.<Cell, byte[]> newHashMap());
}
assert (!result.get(kvs).containsKey(e.getKey()));
result.get(kvs).put(e.getKey(), e.getValue());
}
}
assert result.keySet().size() >= quorumParameters.getReplicationFactor();
return result;
}
@Override
public Map<KeyValueService, Set<Cell>> getServicesForCellsWrite(String tableName,
Set<Cell> cells) {
return getServicesForCellsRead(tableName, cells);
}
public <T> Map<KeyValueService, Multimap<Cell, T>> getServicesForWrite(String tableName,
Multimap<Cell, T> keys) {
Map<KeyValueService, Multimap<Cell, T>> result = Maps.newHashMap();
for (Map.Entry<Cell, T> e : keys.entries()) {
Set<KeyValueService> services = getServicesHavingRow(e.getKey().getRowName());
for (KeyValueService kvs : services) {
if (!result.containsKey(kvs)) {
result.put(kvs, HashMultimap.<Cell, T> create());
}
assert (!result.get(kvs).containsEntry(e.getKey(), e.getValue()));
result.get(kvs).put(e.getKey(), e.getValue());
}
}
return result;
}
@Override
public Set<? extends KeyValueService> getDelegates() {
return services;
}
}
|
package de.st_ddt.crazylogin;
import java.util.Date;
import java.util.HashMap;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class CrazyLoginPlayerListener implements Listener
{
private final CrazyLogin plugin;
private final HashMap<String, Location> savelogin = new HashMap<String, Location>();
public CrazyLoginPlayerListener(final CrazyLogin plugin)
{
super();
this.plugin = plugin;
}
@EventHandler(ignoreCancelled = true)
public void PlayerLogin(final PlayerLoginEvent event)
{
final Player player = event.getPlayer();
if (!plugin.checkNameLength(event.getPlayer().getName()))
{
event.setResult(Result.KICK_OTHER);
event.setKickMessage(plugin.getLocale().getLocaleMessage(player, "NAME.INVALIDLENGTH", plugin.getMinNameLength(), plugin.getMaxNameLength()));
return;
}
if (plugin.isForceSingleSessionEnabled())
if (player.isOnline())
{
if (plugin.isForceSingleSessionSameIPBypassEnabled())
if (player.getAddress() != null)
if (event.getAddress().getHostAddress().equals(player.getAddress().getAddress().getHostAddress()))
if (event.getAddress().getHostName().equals(player.getAddress().getAddress().getHostName()))
return;
event.setResult(Result.KICK_OTHER);
event.setKickMessage(plugin.getLocale().getLocaleMessage(player, "SESSION.DUPLICATE"));
plugin.broadcastLocaleMessage(true, "crazylogin.warnsession", "SESSION.DUPLICATEWARN", event.getAddress().getHostAddress(), player.getName());
plugin.sendLocaleMessage("SESSION.DUPLICATEWARN", player, event.getAddress().getHostAddress(), player.getName());
}
}
@EventHandler
public void PlayerJoin(final PlayerJoinEvent event)
{
final Player player = event.getPlayer();
if (savelogin.get(player.getName().toLowerCase()) != null)
player.teleport(savelogin.get(player.getName().toLowerCase()), TeleportCause.PLUGIN);
if (!plugin.hasAccount(player))
{
if (plugin.isAlwaysNeedPassword())
plugin.sendLocaleMessage("REGISTER.HEADER", player);
else
plugin.sendLocaleMessage("REGISTER.HEADER2", player);
plugin.sendLocaleMessage("REGISTER.MESSAGE", player);
final int autoKick = plugin.getAutoKickUnregistered();
if (plugin.isAlwaysNeedPassword() || autoKick != -1)
savelogin.put(player.getName().toLowerCase(), player.getLocation());
if (autoKick != -1)
plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new ScheduledKickTask(player, plugin.getLocale().getLanguageEntry("REGISTER.REQUEST"), true), autoKick * 20);
return;
}
final LoginData playerdata = plugin.getPlayerData(player);
if (!playerdata.hasIP(player.getAddress().getAddress().getHostAddress()))
playerdata.logout();
if (plugin.isAutoLogoutEnabled())
if (plugin.getAutoLogoutTime() * 1000 + playerdata.getLastActionTime().getTime() < new Date().getTime())
playerdata.logout();
if (plugin.isLoggedIn(player))
return;
if (savelogin.get(player.getName().toLowerCase()) == null)
savelogin.put(player.getName().toLowerCase(), player.getLocation());
plugin.sendLocaleMessage("LOGIN.REQUEST", player);
final int autoKick = plugin.getAutoKick();
if (autoKick >= 10)
plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new ScheduledKickTask(player, plugin.getLocale().getLanguageEntry("LOGIN.REQUEST")), autoKick * 20);
}
@EventHandler
public void PlayerQuit(final PlayerQuitEvent event)
{
final Player player = event.getPlayer();
final LoginData playerdata = plugin.getPlayerData(player);
if (playerdata != null)
{
if (!plugin.isLoggedIn(player))
return;
playerdata.notifyAction();
if (plugin.isInstantAutoLogoutEnabled())
playerdata.logout();
}
}
@EventHandler
public void PlayerDropItem(final PlayerDropItemEvent event)
{
if (plugin.isLoggedIn(event.getPlayer()))
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerInteract(final PlayerInteractEvent event)
{
if (plugin.isLoggedIn(event.getPlayer()))
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerInteractEntity(final PlayerInteractEntityEvent event)
{
if (plugin.isLoggedIn(event.getPlayer()))
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerMove(final PlayerMoveEvent event)
{
final Player player = event.getPlayer();
if (plugin.isLoggedIn(player))
return;
final Location current = savelogin.get(player.getName().toLowerCase());
if (current != null)
if (current.getWorld() == event.getTo().getWorld())
if (current.distance(event.getTo()) < plugin.getMoveRange())
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerTeleport(final PlayerTeleportEvent event)
{
final Player player = event.getPlayer();
if (plugin.isLoggedIn(player))
return;
if (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.UNKNOWN)
return;
final Location target = event.getTo();
if (target.distance(target.getWorld().getSpawnLocation()) < 10)
{
savelogin.put(player.getName().toLowerCase(), event.getTo());
return;
}
if (player.getBedSpawnLocation() != null)
if (target.getWorld() == player.getBedSpawnLocation().getWorld())
if (target.distance(player.getBedSpawnLocation()) < 10)
{
savelogin.put(player.getName().toLowerCase(), event.getTo());
return;
}
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerDamage(final EntityDamageEvent event)
{
if (!(event.getEntity() instanceof Player))
return;
final Player player = (Player) event.getEntity();
if (plugin.isLoggedIn(player))
return;
event.setCancelled(true);
}
@EventHandler
public void PlayerDamage(final EntityDamageByBlockEvent event)
{
if (!(event.getEntity() instanceof Player))
return;
final Player player = (Player) event.getEntity();
if (plugin.isLoggedIn(player))
return;
Location location = player.getBedSpawnLocation();
if (location == null)
location = player.getWorld().getSpawnLocation();
player.teleport(location, TeleportCause.PLUGIN);
event.setCancelled(true);
}
@EventHandler
public void PlayerDamage(final EntityDamageByEntityEvent event)
{
if (!(event.getEntity() instanceof Player))
return;
final Player player = (Player) event.getEntity();
if (plugin.isLoggedIn(player))
return;
Location location = player.getBedSpawnLocation();
if (location == null)
location = player.getWorld().getSpawnLocation();
player.teleport(location, TeleportCause.PLUGIN);
event.setCancelled(true);
}
@EventHandler
public void PlayerPreCommand(final PlayerCommandPreprocessEvent event)
{
final Player player = event.getPlayer();
if (!plugin.isBlockingGuestCommandsEnabled() || plugin.hasAccount(player))
if (plugin.isLoggedIn(player))
return;
final String message = event.getMessage().toLowerCase();
if (message.startsWith("/"))
{
if (message.startsWith("/login") || message.startsWith("/crazylogin password") || message.startsWith("/crazylanguage") || message.startsWith("/language") || message.startsWith("/register"))
return;
for (final String command : plugin.getCommandWhiteList())
if (message.startsWith(command))
return;
event.setCancelled(true);
plugin.broadcastLocaleMessage(true, "crazylogin.warncommandexploits", "COMMAND.EXPLOITWARN", player.getName(), player.getAddress().getAddress().getHostAddress(), message);
if (plugin.isAutoKickCommandUsers())
{
player.kickPlayer(plugin.getLocale().getLocaleMessage(player, "LOGIN.REQUEST"));
return;
}
plugin.requestLogin(event.getPlayer());
return;
}
}
@EventHandler
public void PlayerCommand(final PlayerChatEvent event)
{
final Player player = event.getPlayer();
if (plugin.isLoggedIn(player))
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
public void notifyLogin(Player player)
{
savelogin.remove(player.getName().toLowerCase());
}
}
|
package dr.inference.model;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import dr.app.beagle.evomodel.treelikelihood.BeagleTreeLikelihood;
import dr.util.NumberFormatter;
/**
* A likelihood function which is simply the product of a set of likelihood functions.
*
* @author Marc Suchard
* @author Andrew Rambaut
* @version $Id: CompoundLikelihood.java,v 1.19 2005/05/25 09:14:36 rambaut Exp $
*/
public class ThreadedCompoundLikelihood implements Likelihood {
public static final boolean DEBUG = false;
public ThreadedCompoundLikelihood() {
}
public ThreadedCompoundLikelihood(List<Likelihood> likelihoods) {
for (Likelihood likelihood : likelihoods) {
addLikelihood(likelihood);
}
}
public void addLikelihood(Likelihood likelihood) {
if (!likelihoods.contains(likelihood)) {
likelihoods.add(likelihood);
if (likelihood.getModel() != null) {
compoundModel.addModel(likelihood.getModel());
}
likelihoodCallers.add(new LikelihoodCaller(likelihood));
//System.err.println("LikelihoodCallers size: " + likelihoodCallers.size());
}
}
public int getLikelihoodCount() {
return likelihoods.size();
}
public final Likelihood getLikelihood(int i) {
return likelihoods.get(i);
}
// Likelihood IMPLEMENTATION
public Model getModel() {
return compoundModel;
}
public double getLogLikelihood() {
double logLikelihood = 0.0;
boolean knownLikelihoods = true;
for (Likelihood likelihood : likelihoods) {
if (!((BeagleTreeLikelihood)likelihood).isLikelihoodKnown()) {
knownLikelihoods = false;
break;
} else {
logLikelihood += likelihood.getLogLikelihood();
}
}
if (knownLikelihoods) {
if (DEBUG) {
//System.err.println("BTLs are known; total logLikelihood = " + logLikelihood);
//double check if the total loglikelihood will be identical by recalculating
double backupLikelihood = logLikelihood;
logLikelihood = 0.0;
if (threads == null) {
// first call so setup a thread for each likelihood...
threads = new LikelihoodThread[likelihoodCallers.size()];
for (int i = 0; i < threads.length; i++) {
// and start them running...
threads[i] = new LikelihoodThread();
threads[i].start();
}
}
for (int i = 0; i < threads.length; i++) {
// set the caller which will be called in each thread
threads[i].setCaller(likelihoodCallers.get(i));
}
for (LikelihoodThread thread : threads) {
// now wait for the results to be set...
Double result = thread.getResult();
while (result == null) {
result = thread.getResult();
}
logLikelihood += result;
}
if (backupLikelihood != logLikelihood) {
//System.err.println("Likelihood recalculation does not return stored likelihood");
throw new RuntimeException("Likelihood recalculation does not return stored likelihood");
}
}
} else {
//System.err.println("BTLs are not known: recalculate");
logLikelihood = 0.0;
//double start = System.nanoTime();
//System.err.println("TCL getLogLikelihood()");
if (threads == null) {
//System.err.println("threads == null");
// first call so setup a thread for each likelihood...
threads = new LikelihoodThread[likelihoodCallers.size()];
//System.err.println("LikelihoodThreads: " + threads.length);
for (int i = 0; i < threads.length; i++) {
// and start them running...
threads[i] = new LikelihoodThread();
threads[i].start();
}
}
//double setStart = System.nanoTime();
for (int i = 0; i < threads.length; i++) {
// set the caller which will be called in each thread
threads[i].setCaller(likelihoodCallers.get(i));
}
//double setEnd = System.nanoTime();
//System.err.println("setting callers: " + (setEnd - setStart));
//start = System.nanoTime();
for (LikelihoodThread thread : threads) {
//double testone = System.nanoTime();
// now wait for the results to be set...
Double result = thread.getResult();
while (result == null) {
result = thread.getResult();
}
logLikelihood += result;
//double testtwo = System.nanoTime();
//System.err.println(thread.getName() + " - result = " + result + ": " + (testtwo - testone));
}
//end = System.nanoTime();
//double end = System.nanoTime();
//System.err.println("TCL total time: " + (end - start));
}
return logLikelihood; // * weightFactor;
}
public boolean evaluateEarly() {
return false;
}
public void makeDirty() {
for (Likelihood likelihood : likelihoods) {
likelihood.makeDirty();
}
}
public String prettyName() {
return Abstract.getPrettyName(this);
}
public String getDiagnosis() {
String message = "";
boolean first = true;
for (Likelihood lik : likelihoods) {
if (!first) {
message += ", ";
} else {
first = false;
}
String id = lik.getId();
if (id == null || id.trim().length() == 0) {
String[] parts = lik.getClass().getName().split("\\.");
id = parts[parts.length - 1];
}
message += id + "=";
if (lik instanceof ThreadedCompoundLikelihood) {
String d = ((ThreadedCompoundLikelihood) lik).getDiagnosis();
if (d != null && d.length() > 0) {
message += "(" + d + ")";
}
} else {
if (lik.getLogLikelihood() == Double.NEGATIVE_INFINITY) {
message += "-Inf";
} else if (Double.isNaN(lik.getLogLikelihood())) {
message += "NaN";
} else {
NumberFormatter nf = new NumberFormatter(6);
message += nf.formatDecimal(lik.getLogLikelihood(), 4);
}
}
}
return message;
}
public String toString() {
return Double.toString(getLogLikelihood());
}
public void setWeightFactor(double w) { weightFactor = w; }
public double getWeightFactor() { return weightFactor; }
// Loggable IMPLEMENTATION
/**
* @return the log columns.
*/
public dr.inference.loggers.LogColumn[] getColumns() {
return new dr.inference.loggers.LogColumn[]{
new LikelihoodColumn(getId())
};
}
private class LikelihoodColumn extends dr.inference.loggers.NumberColumn {
public LikelihoodColumn(String label) {
super(label);
}
public double getDoubleValue() {
return getLogLikelihood();
}
}
// Identifiable IMPLEMENTATION
private String id = null;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
private LikelihoodThread[] threads;
private final ArrayList<Likelihood> likelihoods = new ArrayList<Likelihood>();
private final CompoundModel compoundModel = new CompoundModel("compoundModel");
private final List<LikelihoodCaller> likelihoodCallers = new ArrayList<LikelihoodCaller>();
private double weightFactor = 1.0;
class LikelihoodCaller {
public LikelihoodCaller(Likelihood likelihood) {
this.likelihood = likelihood;
}
public double call() {
return likelihood.getLogLikelihood();
}
private final Likelihood likelihood;
}
class LikelihoodThread extends Thread {
public LikelihoodThread() {
}
public void setCaller(LikelihoodCaller caller) {
lock.lock();
resultAvailable = false;
try {
this.caller = caller;
condition.signal();
} finally {
lock.unlock();
}
}
/**
* Main run loop
*/
public void run() {
while (true) {
lock.lock();
try {
while( caller == null)
condition.await();
result = caller.call(); // SLOW
resultAvailable = true;
caller = null;
} catch (InterruptedException e){
} finally {
lock.unlock();
}
}
}
public Double getResult() {
Double returnValue = null;
if (!lock.isLocked() && resultAvailable) { // thread is not busy and completed
resultAvailable = false; // TODO need to lock before changing resultAvailable?
returnValue = result;
}
return returnValue;
}
private LikelihoodCaller caller = null;
private Double result = Double.NaN;
private boolean resultAvailable = false;
private final ReentrantLock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
}
public boolean isUsed() {
return isUsed;
}
public void setUsed() {
isUsed = true;
for (Likelihood l : likelihoods) {
l.setUsed();
}
}
private boolean isUsed = false;
}
|
package org.apereo.cas.config;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.ldap.UnsupportedAuthenticationMechanismException;
import org.apereo.cas.authentication.LdapAuthenticationHandler;
import org.apereo.cas.authentication.principal.PrincipalResolver;
import org.apereo.cas.authentication.support.PasswordPolicyConfiguration;
import org.apereo.cas.authorization.generator.LdapAuthorizationGenerator;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.model.support.ldap.LdapAuthenticationProperties;
import org.apereo.cas.configuration.support.Beans;
import org.apereo.cas.services.ServicesManager;
import org.ldaptive.BindConnectionInitializer;
import org.ldaptive.ConnectionConfig;
import org.ldaptive.ConnectionFactory;
import org.ldaptive.Credential;
import org.ldaptive.DefaultConnectionFactory;
import org.ldaptive.SearchExecutor;
import org.ldaptive.ad.extended.FastBindOperation;
import org.ldaptive.auth.Authenticator;
import org.ldaptive.auth.FormatDnResolver;
import org.ldaptive.auth.PooledBindAuthenticationHandler;
import org.ldaptive.auth.PooledSearchDnResolver;
import org.ldaptive.auth.SearchEntryResolver;
import org.ldaptive.auth.ext.ActiveDirectoryAuthenticationResponseHandler;
import org.ldaptive.auth.ext.PasswordExpirationAuthenticationResponseHandler;
import org.ldaptive.auth.ext.PasswordPolicyAuthenticationResponseHandler;
import org.ldaptive.control.PasswordPolicyControl;
import org.ldaptive.pool.BlockingConnectionPool;
import org.ldaptive.pool.IdlePruneStrategy;
import org.ldaptive.pool.PoolConfig;
import org.ldaptive.pool.PooledConnectionFactory;
import org.ldaptive.pool.SearchValidator;
import org.ldaptive.provider.Provider;
import org.ldaptive.ssl.KeyStoreCredentialConfig;
import org.ldaptive.ssl.SslConfig;
import org.ldaptive.ssl.X509CredentialConfig;
import org.pac4j.core.authorization.AuthorizationGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* This is {@link LdapAuthenticationConfiguration}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
@Configuration("ldapAuthenticationConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class LdapAuthenticationConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(LdapAuthenticationConfiguration.class);
@Autowired(required = false)
@Qualifier("ldapAuthorizationGeneratorConnectionFactory")
private ConnectionFactory connectionFactory;
@Autowired(required = false)
@Qualifier("ldapAuthorizationGeneratorUserSearchExecutor")
private SearchExecutor userSearchExecutor;
@Autowired
private CasConfigurationProperties casProperties;
@Autowired
@Qualifier("personDirectoryPrincipalResolver")
private PrincipalResolver personDirectoryPrincipalResolver;
@Autowired
@Qualifier("authenticationHandlersResolvers")
private Map authenticationHandlersResolvers;
@Autowired
@Qualifier("servicesManager")
private ServicesManager servicesManager;
@Autowired
@Qualifier("ldapPasswordPolicyConfiguration")
private PasswordPolicyConfiguration ldapPasswordPolicyConfiguration;
@Bean
@RefreshScope
public AuthorizationGenerator ldapAuthorizationGenerator() {
if (connectionFactory != null) {
final LdapAuthorizationGenerator gen =
new LdapAuthorizationGenerator(this.connectionFactory, this.userSearchExecutor);
gen.setAllowMultipleResults(casProperties.getLdapAuthz().isAllowMultipleResults());
gen.setRoleAttribute(casProperties.getLdapAuthz().getRoleAttribute());
gen.setRolePrefix(casProperties.getLdapAuthz().getRolePrefix());
return gen;
}
return commonProfile -> {
throw new UnsupportedAuthenticationMechanismException("Authorization generator not specified");
};
}
@PostConstruct
public void initLdapAuthenticationHandlers() {
casProperties.getAuthn().getLdap().forEach(l -> {
if (l.getType() != null) {
final LdapAuthenticationHandler handler = new LdapAuthenticationHandler();
handler.setServicesManager(servicesManager);
handler.setAdditionalAttributes(l.getAdditionalAttributes());
handler.setAllowMultiplePrincipalAttributeValues(l.isAllowMultiplePrincipalAttributeValues());
final Map<String, String> attributes = new HashMap<>();
l.getPrincipalAttributeList().forEach(a -> attributes.put(a.toString(), a.toString()));
attributes.putAll(casProperties.getAuthn().getAttributes());
handler.setPrincipalAttributeMap(attributes);
handler.setPrincipalIdAttribute(l.getPrincipalAttributeId());
final Authenticator authenticator = getAuthenticator(l);
if (l.isUsePasswordPolicy()) {
authenticator.setAuthenticationResponseHandlers(
new ActiveDirectoryAuthenticationResponseHandler(
TimeUnit.DAYS.convert(this.ldapPasswordPolicyConfiguration.getPasswordWarningNumberOfDays(),
TimeUnit.MILLISECONDS)
),
new PasswordPolicyAuthenticationResponseHandler(),
new PasswordExpirationAuthenticationResponseHandler());
handler.setPasswordPolicyConfiguration(this.ldapPasswordPolicyConfiguration);
}
handler.setAuthenticator(authenticator);
if (l.getAdditionalAttributes().isEmpty() && l.getPrincipalAttributeList().isEmpty()) {
this.authenticationHandlersResolvers.put(handler, this.personDirectoryPrincipalResolver);
} else {
this.authenticationHandlersResolvers.put(handler, null);
}
}
});
}
private static Authenticator getAuthenticator(final LdapAuthenticationProperties l) {
if (l.getType() == LdapAuthenticationProperties.AuthenticationTypes.AD) {
return getActiveDirectoryAuthenticator(l);
}
if (l.getType() == LdapAuthenticationProperties.AuthenticationTypes.DIRECT) {
return getDirectBindAuthenticator(l);
}
return getAuthenticatedOrAnonSearchAuthenticator(l);
}
private static Authenticator getAuthenticatedOrAnonSearchAuthenticator(final LdapAuthenticationProperties l) {
final PooledSearchDnResolver resolver = new PooledSearchDnResolver();
resolver.setBaseDn(l.getBaseDn());
resolver.setSubtreeSearch(l.isSubtreeSearch());
resolver.setAllowMultipleDns(l.isAllowMultipleDns());
resolver.setConnectionFactory(getPooledConnectionFactory(l));
resolver.setUserFilter(l.getUserFilter());
return new Authenticator(resolver, getPooledBindAuthenticationHandler(l));
}
private static Authenticator getDirectBindAuthenticator(final LdapAuthenticationProperties l) {
final FormatDnResolver resolver = new FormatDnResolver(l.getBaseDn());
return new Authenticator(resolver, getPooledBindAuthenticationHandler(l));
}
private static Authenticator getActiveDirectoryAuthenticator(final LdapAuthenticationProperties l) {
final FormatDnResolver resolver = new FormatDnResolver(l.getDnFormat());
final Authenticator authn = new Authenticator(resolver, getPooledBindAuthenticationHandler(l));
final SearchEntryResolver entryResolver = new SearchEntryResolver();
entryResolver.setBaseDn(l.getBaseDn());
entryResolver.setUserFilter(l.getUserFilter());
entryResolver.setSubtreeSearch(l.isSubtreeSearch());
authn.setEntryResolver(new SearchEntryResolver());
return authn;
}
private static PooledBindAuthenticationHandler getPooledBindAuthenticationHandler(final LdapAuthenticationProperties l) {
final PooledBindAuthenticationHandler handler = new PooledBindAuthenticationHandler(getPooledConnectionFactory(l));
handler.setAuthenticationControls(new PasswordPolicyControl());
return handler;
}
private static PooledConnectionFactory getPooledConnectionFactory(
final LdapAuthenticationProperties l) {
final PoolConfig pc = new PoolConfig();
pc.setMinPoolSize(l.getMinPoolSize());
pc.setMaxPoolSize(l.getMaxPoolSize());
pc.setValidateOnCheckOut(l.isValidateOnCheckout());
pc.setValidatePeriodically(l.isValidatePeriodically());
pc.setValidatePeriod(l.getValidatePeriod());
final ConnectionConfig cc = new ConnectionConfig();
cc.setLdapUrl(l.getLdapUrl());
cc.setUseSSL(l.isUseSsl());
cc.setUseStartTLS(l.isUseStartTls());
cc.setConnectTimeout(l.getConnectTimeout());
if (l.getTrustCertificates() != null) {
final X509CredentialConfig cfg = new X509CredentialConfig();
cfg.setTrustCertificates(l.getTrustCertificates());
cc.setSslConfig(new SslConfig());
} else if (l.getKeystore() != null) {
final KeyStoreCredentialConfig cfg = new KeyStoreCredentialConfig();
cfg.setKeyStore(l.getKeystore());
cfg.setKeyStorePassword(l.getKeystorePassword());
cfg.setKeyStoreType(l.getKeystoreType());
cc.setSslConfig(new SslConfig(cfg));
} else {
cc.setSslConfig(new SslConfig());
}
if (StringUtils.equals(l.getBindCredential(), "*") && StringUtils.equals(l.getBindDn(), "*")) {
cc.setConnectionInitializer(new FastBindOperation.FastBindConnectionInitializer());
} else if (StringUtils.isNotBlank(l.getBindDn()) && StringUtils.isNotBlank(l.getBindCredential())) {
cc.setConnectionInitializer(new BindConnectionInitializer(l.getBindDn(),
new Credential(l.getBindCredential())));
}
final DefaultConnectionFactory bindCf = new DefaultConnectionFactory(cc);
if (l.getProviderClass() != null) {
try {
final Class clazz = ClassUtils.getClass(l.getProviderClass());
bindCf.setProvider(Provider.class.cast(clazz.newInstance()));
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
final BlockingConnectionPool cp = new BlockingConnectionPool(pc, bindCf);
cp.setBlockWaitTime(l.getBlockWaitTime());
cp.setPoolConfig(pc);
final IdlePruneStrategy strategy = new IdlePruneStrategy();
strategy.setIdleTime(l.getIdleTime());
strategy.setPrunePeriod(l.getPrunePeriod());
cp.setPruneStrategy(strategy);
cp.setValidator(new SearchValidator());
cp.setFailFastInitialize(l.isFailFast());
return new PooledConnectionFactory(cp);
}
}
|
package com.codenvy.factory.storage.mongo;
import com.codenvy.api.factory.FactoryStore;
import com.codenvy.commons.json.JsonHelper;
import com.codenvy.commons.json.JsonParseException;
import com.codenvy.factory.MongoDbConfiguration;
import com.codenvy.factory.storage.InMemoryFactoryStore;
import com.codenvy.inject.DynaModule;
import com.google.inject.AbstractModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@DynaModule
public class FactoryModule extends AbstractModule {
private static final Logger LOG = LoggerFactory.getLogger(FactoryModule.class);
@Override
protected void configure() {
bind(FactoryStore.class).toInstance(getFactoryStore());
}
private FactoryStore getFactoryStore() {
if (System.getProperty("codenvy.local.conf.dir") != null) {
File dbSettings =
new File(System.getProperty("codenvy.local.conf.dir"), "old/factory-storage-configuration.json");
if (dbSettings.exists() && !dbSettings.isDirectory()) {
try (InputStream is = new FileInputStream(dbSettings)) {
MongoDbConfiguration mConf = JsonHelper.fromJson(is, MongoDbConfiguration.class, null);
return new MongoDBFactoryStore(mConf);
} catch (IOException | JsonParseException e) {
LOG.error(e.getLocalizedMessage(), e);
throw new RuntimeException(
"Invalid mongo database configuration : " + dbSettings.getAbsolutePath());
}
}
}
LOG.warn("Persistent storage configuration not found, inmemory impl will be used.");
return new InMemoryFactoryStore();
}
}
|
package edu.columbia.slime.service.core;
import java.io.*;
import java.io.Closeable;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.util.Map;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.nio.channels.ServerSocketChannel;
import com.jcraft.jsch.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.columbia.slime.Slime;
import edu.columbia.slime.conf.Config;
import edu.columbia.slime.service.Service;
import edu.columbia.slime.service.Event;
import edu.columbia.slime.service.MessageEvent;
import edu.columbia.slime.util.Network;
public class DeployService extends Service {
private static final int SSH_PORT = 22;
private boolean ptimestamp = true;
JSch jsch = new JSch();
Session session;
Map<String, Map<String, String>> servers;
public String getName() {
return "deploy";
}
public void init() throws IOException {
servers = Slime.getConfig().getServerInfo();
}
public void dispatch(Event e) throws IOException {
if (e instanceof MessageEvent) {
MessageEvent me = (MessageEvent) e;
if (me.getMessage().equals("deployAll") && servers != null) {
LOG.info("'deploy' service: Got a 'deployAll' message");
for (String server : servers.keySet()) {
if (Network.checkIfMyAddress(server))
continue;
deployServer(server);
}
}
}
}
/* inherited from Closeable */
public void close() throws IOException {
}
public void makeRemoteDir(String rdir) throws IOException, JSchException {
String command = "mkdir -p " + rdir + "\n";
executeCommand(command);
}
public void launchSlime() throws IOException, JSchException {
String distDir = Slime.getConfig().get(Config.ELEMENT_NAME_DIST);
String command = "cd " + distDir + " && " +
"mkdir -p logs && " +
"java -D" + Config.PROPERTY_NAME_LAUNCHERADDR + "=" + Network.getMyAddress() +
|
package edu.dynamic.dynamiz.controller;
import static org.junit.Assert.*;
import org.junit.Test;
import edu.dynamic.dynamiz.parser.CommandLine;
import edu.dynamic.dynamiz.parser.Parser;
import edu.dynamic.dynamiz.structure.MyDateTime;
import edu.dynamic.dynamiz.structure.EventItem;
import edu.dynamic.dynamiz.structure.ToDoItem;
/**
* JUnit test case for Command Add.
* @author A0110781N
*/
public class CommandAddTest {
@Test
public void test() {
Command cmd = new CommandAdd(new ToDoItem("Learn C++"));
cmd.execute();
assertEquals(1, cmd.getAffectedItems().length);
assertEquals("Learn C++", cmd.getAffectedItems()[0].getDescription());
//((Undoable)cmd).undo();
cmd = new CommandAdd(new EventItem("Learn C++", new MyDateTime(31, 10, 2014, 12, 0), new MyDateTime(11, 11, 2014, 12, 0)));
cmd.execute();
assertEquals(new MyDateTime(31, 10, 2014, 12, 0), ((EventItem)cmd.getAffectedItems()[0]).getStartDate());
assertEquals(new MyDateTime(11, 11, 2014, 12, 0), ((EventItem)cmd.getAffectedItems()[0]).getEndDate());
//((Undoable)cmd).undo();
}
// TODO: Implement Exception for CommandAdd
@Test(expected=IllegalArgumentException.class)
public void testIllegalActions(){
Parser parser = Parser.getInstance();
}
}
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.templates.commands.CommandBase;
import edu.wpi.first.wpilibj.templates.commands.DriveToUltrasonicThenFIre;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends IterativeRobot {
Command autonomousCommand;
/**
* Utility function to set the color of the LED's on the robot
* to match the team's alliance color.
*/
public void setLedColor() {
if (DriverStation.getInstance().getAlliance() == DriverStation.Alliance.kRed) {
CommandBase.myLED.redON();
} else {
CommandBase.myLED.blueOn();
}
}
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
// instantiate the command used for the autonomous period
setLedColor();
autonomousCommand = new DriveToUltrasonicThenFIre();
// Initialize all subsystems
CommandBase.init();
}
/**
* Initialize robot for autonomous period
*/
public void autonomousInit() {
// schedule the autonomous command (example)
autonomousCommand.start();
setLedColor();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
/**
* carry out functions that need to occur at the end of autonomous
*/
public void disabledInit() {
setLedColor();
}
/**
* Set up to begin telop/human controlled period.
*/
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
autonomousCommand.cancel();
setLedColor();
CommandBase.subGatherer.retractGatherer();
CommandBase.subShooter.unLatch();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
SmartDashboard();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
/**
* Set up the callback functions to update status for the
* smartdashboard.
*/
public void SmartDashboard() {
// CommandBase.myAimer.SmartDashboard();
CommandBase.oi.SmartDashboard();
CommandBase.subCompressor.SmartDashboard();
CommandBase.subDriveTrain.SmartDashboard();
CommandBase.subGatherer.SmartDashboard();
CommandBase.subShooter.SmartDashboard();
}
}
|
package it.unibz.inf.ontop.datalog.impl;
import java.util.*;
import com.google.common.collect.ImmutableList;
import it.unibz.inf.ontop.constraints.LinearInclusionDependencies;
import it.unibz.inf.ontop.datalog.*;
import it.unibz.inf.ontop.model.atom.AtomFactory;
import it.unibz.inf.ontop.model.atom.AtomPredicate;
import it.unibz.inf.ontop.model.atom.DataAtom;
import it.unibz.inf.ontop.model.term.*;
import it.unibz.inf.ontop.model.term.functionsymbol.Predicate;
import it.unibz.inf.ontop.model.term.impl.ImmutabilityTools;
import it.unibz.inf.ontop.substitution.Substitution;
import it.unibz.inf.ontop.substitution.SubstitutionBuilder;
import it.unibz.inf.ontop.utils.ImmutableCollectors;
public class CQContainmentCheckUnderLIDs {
private final Map<List<Function>, Map<Predicate, List<Function>>> indexedCQcache = new HashMap<>();
private final LinearInclusionDependencies<AtomPredicate> dependencies;
private final AtomFactory atomFactory;
private final TermFactory termFactory;
private final ImmutabilityTools immutabilityTools;
/**
* *@param sigma
* A set of ABox dependencies
*/
public CQContainmentCheckUnderLIDs(LinearInclusionDependencies<AtomPredicate> dependencies,
AtomFactory atomFactory, TermFactory termFactory, ImmutabilityTools immutabilityTools) {
// index dependencies
this.dependencies = dependencies;
this.atomFactory = atomFactory;
this.termFactory = termFactory;
this.immutabilityTools = immutabilityTools;
}
private Map<Predicate, List<Function>> index(Collection<Function> body) {
Map<Predicate, List<Function>> factMap = new HashMap<>(body.size() * 2);
for (Function atom : body)
// not boolean, not algebra, not arithmetic, not datatype
if (atom != null && atom.isDataFunction()) {
Predicate pred = atom.getFunctionSymbol();
List<Function> facts = factMap.get(pred);
if (facts == null) {
facts = new LinkedList<>();
factMap.put(pred, facts);
}
facts.add(atom);
}
return factMap;
}
private Map<Predicate, List<Function>> getFactMap(List<Function> b) {
Map<Predicate, List<Function>> factMap1 = indexedCQcache.get(b);
if (factMap1 == null) {
ImmutableList<DataAtom<AtomPredicate>> matoms = b.stream()
.map(a -> atomFactory.getDataAtom((AtomPredicate)a.getFunctionSymbol(),
a.getTerms().stream()
.map(t -> (VariableOrGroundTerm)immutabilityTools.convertIntoImmutableTerm(t))
.collect(ImmutableCollectors.toList())))
.collect(ImmutableCollectors.toList());
Collection<Function> q1body = dependencies.chaseAllAtoms(matoms).stream()
.map(immutabilityTools::convertToMutableFunction)
.collect(ImmutableCollectors.toSet());
factMap1 = index(q1body);
indexedCQcache.put(b, factMap1);
}
return factMap1;
}
public Substitution computeHomomorphsim(Function h1, List<Function> b1, Function h2, List<Function> b2) {
SubstitutionBuilder sb = new SubstitutionBuilder(termFactory);
// get the substitution for the head first
// it will ensure that all answer variables are mapped either to constants or
// to answer variables in the base (but not to the labelled nulls generated by the chase)
boolean headResult = extendHomomorphism(sb, h2, h1);
if (!headResult)
return null;
Substitution sub = computeSomeHomomorphism(sb, b2, getFactMap(b1));
return sub;
}
public CQIE removeRedundantAtoms(CQIE query) {
List<Function> databaseAtoms = new ArrayList<>(query.getBody().size());
Set<Term> groundTerms = new HashSet<>();
for (Function atom : query.getBody())
// non-database atom
if (!(atom.getFunctionSymbol() instanceof AtomPredicate)) {
collectVariables(groundTerms, atom);
}
else {
databaseAtoms.add(atom);
}
if (databaseAtoms.size() < 2) {
return query;
}
collectVariables(groundTerms, query.getHead());
for (int i = 0; i < databaseAtoms.size(); i++) {
Function atomToBeRemoved = databaseAtoms.get(i);
if (checkRedundant(databaseAtoms, groundTerms, atomToBeRemoved)) {
query.getBody().remove(atomToBeRemoved);
databaseAtoms.remove(atomToBeRemoved);
i
}
}
return query;
}
private boolean checkRedundant(List<Function> body, Set<Term> groundTerms, Function atomToBeRemoved) {
List<Function> atomsToLeave = new ArrayList<>(body.size() - 1);
Set<Term> variablesInAtomsToLeave = new HashSet<>();
for (Function a: body)
if (a != atomToBeRemoved) {
atomsToLeave.add(a);
collectVariables(variablesInAtomsToLeave, a);
}
if (!variablesInAtomsToLeave.containsAll(groundTerms)) {
return false;
}
SubstitutionBuilder sb = new SubstitutionBuilder(termFactory);
Substitution sub = computeSomeHomomorphism(sb, body, getFactMap(atomsToLeave));
if (sub != null)
return true;
return false;
}
private static void collectVariables(Set<Term> vars, Function atom) {
Deque<Term> terms = new LinkedList<>(atom.getTerms());
while (!terms.isEmpty()) {
Term t = terms.pollFirst();
if (t instanceof Variable)
vars.add(t);
else if (!(t instanceof Constant))
terms.addAll(((Function)t).getTerms());
}
}
@Override
public String toString() {
if (dependencies != null)
return dependencies.toString();
return "(empty)";
}
private static boolean extendHomomorphism(SubstitutionBuilder sb, Function from, Function to) {
if ((from.getArity() != to.getArity()) || !(from.getFunctionSymbol().equals(to.getFunctionSymbol())))
return false;
int arity = from.getArity();
for (int i = 0; i < arity; i++) {
Term fromTerm = from.getTerm(i);
Term toTerm = to.getTerm(i);
if (fromTerm instanceof Variable) {
boolean result = sb.extend((Variable)fromTerm, toTerm);
// if we cannot find a match, terminate the process and return false
if (!result)
return false;
}
else if (fromTerm instanceof Constant) {
// constants must match
if (!fromTerm.equals(toTerm))
return false;
}
else /*if (fromTerm instanceof Function)*/ {
// the to term must also be a function
if (!(toTerm instanceof Function))
return false;
boolean result = extendHomomorphism(sb, (Function)fromTerm, (Function)toTerm);
// if we cannot find a match, terminate the process and return false
if (!result)
return false;
}
}
return true;
}
/**
* Extends a given substitution that maps each atom in {@code from} to match at least one atom in {@code to}
*
* @param sb
* @param from
* @param to
* @return
*/
private static Substitution computeSomeHomomorphism(SubstitutionBuilder sb, List<Function> from, Map<Predicate, List<Function>> to) {
int fromSize = from.size();
if (fromSize == 0)
return sb.getSubstituition();
// stack of partial homomorphisms
Stack<SubstitutionBuilder> sbStack = new Stack<>();
sbStack.push(sb);
// set the capacity to reduce memory re-allocations
List<Stack<Function>> choicesMap = new ArrayList<>(fromSize);
int currentAtomIdx = 0;
while (currentAtomIdx >= 0) {
Function currentAtom = from.get(currentAtomIdx);
Stack<Function> choices;
if (currentAtomIdx >= choicesMap.size()) {
// we have never reached this atom (this is lazy initialization)
// initializing the stack
choices = new Stack<>();
// add all choices for the current predicate symbol
choices.addAll(to.getOrDefault(currentAtom.getFunctionSymbol(), ImmutableList.of()));
choicesMap.add(currentAtomIdx, choices);
}
else
choices = choicesMap.get(currentAtomIdx);
boolean choiceMade = false;
while (!choices.isEmpty()) {
SubstitutionBuilder sb1 = sb.clone(); // clone!
choiceMade = extendHomomorphism(sb1, currentAtom, choices.pop());
if (choiceMade) {
// we reached the last atom
if (currentAtomIdx == fromSize - 1)
return sb1.getSubstituition();
// otherwise, save the partial homomorphism
sbStack.push(sb);
sb = sb1;
currentAtomIdx++; // move to the next atom
break;
}
}
if (!choiceMade) {
// backtracking
// restore all choices for the current predicate symbol
choices.addAll(to.getOrDefault(currentAtom.getFunctionSymbol(), ImmutableList.of()));
sb = sbStack.pop(); // restore the partial homomorphism
currentAtomIdx--; // move to the previous atom
}
}
// checked all possible substitutions and have not found anything
return null;
}
}
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Joystick;
//import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Timer;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends IterativeRobot {
int autonomousState = 0;
public void printMsg(String message) {
userMessages.println(DriverStationLCD.Line.kMain6, 1, message );
userMessages.updateLCD();
}
boolean deadband(double[] values){
for(int i = 0; i < 6; i++){
if (values[i] < 0.5 && values[i] > -0.5){
return true;
}
}
return false;
}
RobotDrive drivetrain;
//Relay spikeA;
Joystick leftStick;
Joystick rightStick;
//public String controlScheme = "twostick";
int leftStickX, leftStickY;
DriverStationLCD userMessages;
String controlScheme = "twostick";
Timer timer;
DigitalInput switchA, switchB;
Jaguar launcher;
Jaguar launcher2;
Jaguar launcher3;
//maybe more?
double voltage;
//DriverStation driverStation = new DriverStation();
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
//Instantialize objects for RobotTemplate
//driverStation = new DriverStation();
rightStick = new Joystick(1);
leftStick = new Joystick(2);
userMessages = DriverStationLCD.getInstance();
//2-Wheel tank drive
//spikeA = new Relay(1);
drivetrain = new RobotDrive(1,2);
launcher = new Jaguar(5);
/*pistonUp = new Solenoid(1);
pistonDown = new Solenoid(2);
sol3 = new Solenoid(3);
sol4 = new Solenoid(4);
sol5 = new Solenoid(5);*/
//4-Wheel tank drive
//Motors must be set in the following order:
//LeftFront=1; LeftRear=2; RightFront=3; RightRear=4;
//drivetrain = new RobotDrive(1,2,3,4);
//drivetrain.tankDrive(leftStick, rightStick);
/*pistonDown.set(true);
pistonUp.set(true);*/
switchA = new DigitalInput(1);
switchB = new DigitalInput(2);//remember to check port
}
/**
* This function is called periodically during autonomous
*/
public void autonomousInit() {
autonTimer.reset();
autonTimer.start();
autonomousState = 0;
}
Timer autonTimer = new Timer();
public void autonomousPeriodic()
{
switch ( autonomousState )
{
case 0:
drivetrain.drive(.30, 0);
if ( autonTimer.get() > 7 ){
autonomousState++;
}
break;
case 1:
drivetrain.drive(0, 0);
launcher.set(1.0);
break;
}
}
public void telopInit() {
//drivetrain.setSafetyEnabled(true);
//drivetrain.tankDrive(leftStick.getY(), rightStick.getY());
//compressorA.start();
printMsg("Teleop started.");
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
//x is a placeholder variable
/*if(switchA.get()){//if switch isn't tripped
printMsg("Moving motor.");
//victor.set(0.5); //start motor
}
else{
printMsg("Motor stopped");
//victor.set(0); //stop motor
}*/
//getWatchdog().setEnabled(true);
drivetrain.tankDrive(leftStick, rightStick);
double[] values = {leftStick.getX(), leftStick.getY(), rightStick.getX(), rightStick.getY()};
if(deadband(values)){
drivetrain.stopMotor();
}
if (leftStick.getTrigger()) {
if(launcher.get() != -1){
launcher.set(-1);
launcher2.set(-1);
launcher3.set(-1);
}
else {
launcher.set(0);
launcher2.set(0);
launcher3.set(0);
}
}
if (rightStick.getTrigger()) {
if(launcher.get() != 1){
launcher.set(1);
launcher2.set(1);
launcher3.set(1);
}
else {
launcher.set(0);
launcher2.set(0);
launcher3.set(0);
}
}
/* //Switch between "onestick" and "twostick" control schemes
if (leftStick.getRawButton(6)) {
controlScheme = "twostick";
}
if (leftStick.getRawButton(7)) {
controlScheme = "onestick";
}
if (controlScheme.equals("twostick")) {
drivetrain.tankDrive(rightStick, leftStick);
printMsg("Tankdrive activated.");
}
else if (controlScheme.equals("onestick")) {
drivetrain.arcadeDrive(leftStick);
printMsg("Arcade drive activated.");
}*/
/*if(switchA.get()){//if switch isn't tripped
printMsg("Moving motor.");
//victor.set(0.5); //start motor
}
else{
printMsg("Motor stopped");
//victor.set(0); //stop motor
}*/
//Rotate in-place left and right, respectively
if (leftStick.getRawButton(8)) {
drivetrain.setLeftRightMotorOutputs(-1.0, 1.0);
printMsg("Rotating counterclockwise in place.");
}
if (leftStick.getRawButton(9)) {
drivetrain.setLeftRightMotorOutputs(1.0, -1.0);
printMsg("Rotating clockwise in place.");
}
//userMessages.println(DriverStationLCD.Line.kMain6, 1, "This is a test" );
userMessages.updateLCD();
}
/*public void disabledInit() {
}*/
}
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Talon;
import com.sun.squawk.util.*;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends IterativeRobot {
double STARTINGTHRESHOLD = 0.0;
Talon frontleft;
Talon frontright;
Talon backleft;
Talon backright;
RobotDrive drive;
Joystick operatorStick;
Joystick driverStick;
Talon winch1;
Talon winch2;
Relay CollectorRelay;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
driverStick= new Joystick(1);
operatorStick = new Joystick(2);
CollectorRelay = new Relay(5, Relay.Direction.kBoth);
CollectorRelay.set(Relay.Value.kOff);
frontleft = new Talon (1);
frontright = new Talon (2);
backleft = new Talon (3);
backright = new Talon (4);
winch1 = new Talon (5);
winch2 = new Talon (6);
drive = new RobotDrive (frontleft,backleft, frontright,backright);
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
checkDrive();
if(operatorStick.getRawButton(7))
{
winch();
}
if(operatorStick.getRawButton(8))
{
collectorIn();
}
if(operatorStick.getRawButton(9))
{
collectorOut();
}
}
public void collectorIn()
{
CollectorRelay.set(Relay.Value.kForward);
}
public void collectorOut()
{
CollectorRelay.set(Relay.Value.kReverse);
}
public void winch()
{
winch1.set(1.0);
winch2.set(1.0);
}
private void checkDrive(){
double x = driverStick.getRawAxis(1);
if(x < 0.1 && x > -0.1){
x = 0;
}
if(x > 0){
x = (1-STARTINGTHRESHOLD) * MathUtils.pow(x,2-STARTINGTHRESHOLD) + STARTINGTHRESHOLD;
}
else if(x < 0){
x = -1 * ((1-STARTINGTHRESHOLD) * MathUtils.pow(x,2-STARTINGTHRESHOLD) + STARTINGTHRESHOLD);
}
double y = driverStick.getRawAxis(2);
if(y < 0.1 && y > -0.1){
y = 0;
}
if(y > 0){
y = (1-STARTINGTHRESHOLD) * MathUtils.pow(y,2-STARTINGTHRESHOLD) + STARTINGTHRESHOLD;
}
else if(y < 0){
y = -1 * ((1-STARTINGTHRESHOLD) * MathUtils.pow(y,2-STARTINGTHRESHOLD) + STARTINGTHRESHOLD);
}
double rotation = driverStick.getRawAxis(3);
if(rotation < 0.05 && rotation > -0.05){
rotation = 0;
}
if(rotation > 0){
rotation = (1-STARTINGTHRESHOLD) * MathUtils.pow(rotation,2-STARTINGTHRESHOLD) + STARTINGTHRESHOLD;
}
else if (rotation < 0){
rotation = -1 * ((1-STARTINGTHRESHOLD) * MathUtils.pow(rotation,2-STARTINGTHRESHOLD) + STARTINGTHRESHOLD);
}
double gyroAngle = 0;
System.out.println("x:"+x+" y:"+y+" rotation:"+rotation);
drive.mecanumDrive_Cartesian(x, y, rotation, 0.0);
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
}
}
|
package org.eclipse.birt.data.engine.executor;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.eclipse.birt.core.util.IOUtil;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.core.security.FileSecurity;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.impl.DataSetCacheUtil;
import org.eclipse.birt.data.engine.odi.IResultClass;
/**
* The data set cache object which serve for disk based data set cache.
*/
public class DiskDataSetCacheObject implements IDataSetCacheObject
{
private String cacheDir;
private static Integer count = 0;
//the most row count this cache can save
private int cacheCapability;
/**
*
* @param tempFolder
* @param appContext
* @param parameterHints
* @param baseDataSetDesign
* @param baseDataSourceDesign
*/
public DiskDataSetCacheObject( String cacheDir, int cacheCapability )
{
assert cacheCapability > 0;
if( cacheDir.endsWith( File.separator ))
{
this.cacheDir = cacheDir + "DataSetCacheObject_" + this.hashCode( ) + "_" + getCount() ;
}
else
{
this.cacheDir = cacheDir + File.separator + "DataSetCacheObject_" + this.hashCode( ) + "_" + getCount();
}
FileSecurity.fileMakeDirs( new File( this.cacheDir ));
this.cacheCapability = cacheCapability;
}
/**
*
* @return
*/
private int getCount()
{
synchronized( count )
{
count = (count + 1) % 100000;
return count.intValue( );
}
}
/**
*
* @return
*/
public File getDataFile()
{
return new File( cacheDir + File.separator + "data.data");
}
/**
*
* @return
*/
public File getMetaFile()
{
return new File( cacheDir + File.separator + "meta.data");
}
public boolean isCachedDataReusable( int requiredCapability )
{
assert requiredCapability > 0;
// Only check if meta data file exists, because empty data file should
// be still valid and cached.
// Removed: FileSecurity.fileExist( getDataFile()) &&
return FileSecurity.fileExist( getMetaFile( ) )
&& cacheCapability >= requiredCapability;
}
public boolean needUpdateCache( int requiredCapability )
{
return !isCachedDataReusable(requiredCapability);
}
public void release( )
{
DataSetCacheUtil.deleteFile( cacheDir );
}
public IResultClass getResultClass( ) throws DataException
{
IResultClass rsClass;
FileInputStream fis1 = null;
BufferedInputStream bis1 = null;
try
{
fis1 = FileSecurity.createFileInputStream( getMetaFile( ) );
bis1 = new BufferedInputStream( fis1 );
IOUtil.readInt( bis1 );
rsClass = new ResultClass( bis1, 0 );
bis1.close( );
fis1.close( );
return rsClass;
}
catch ( FileNotFoundException e )
{
throw new DataException( ResourceConstants.DATASETCACHE_LOAD_ERROR,
e );
}
catch ( IOException e )
{
throw new DataException( ResourceConstants.DATASETCACHE_LOAD_ERROR,
e );
}
}
public String getCacheDir( )
{
return cacheDir;
}
}
|
//$HeadURL$
package org.deegree.filter.xml;
import static junit.framework.Assert.assertEquals;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import junit.framework.Assert;
import org.deegree.commons.config.DeegreeWorkspace;
import org.deegree.commons.tom.primitive.PrimitiveValue;
import org.deegree.commons.xml.schema.RedirectingEntityResolver;
import org.deegree.commons.xml.stax.XMLStreamUtils;
import org.deegree.filter.Filter;
import org.deegree.filter.IdFilter;
import org.deegree.filter.OperatorFilter;
import org.deegree.filter.comparison.PropertyIsBetween;
import org.deegree.filter.comparison.PropertyIsEqualTo;
import org.deegree.filter.comparison.PropertyIsLessThan;
import org.deegree.filter.comparison.PropertyIsLike;
import org.deegree.filter.expression.Function;
import org.deegree.filter.expression.Literal;
import org.deegree.filter.expression.ValueReference;
import org.deegree.filter.function.FunctionManager;
import org.deegree.filter.logical.And;
import org.deegree.filter.logical.Not;
import org.deegree.filter.spatial.Disjoint;
import org.deegree.filter.spatial.Overlaps;
import org.deegree.geometry.Envelope;
import org.deegree.geometry.primitive.Polygon;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
/**
* Tests the correct parsing of Filter Encoding 2.0.0 documents using the official examples (excluding filter
* capabilities examples and filter examples with custom operations).
*
* @author <a href="mailto:schneider@lat-lon.de">Markus Schneider </a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class Filter200XMLDecoderTest {
private static final Logger LOG = getLogger( Filter200XMLDecoderTest.class );
// files are not really fetched from this URL, but taken from cached version (module deegree-ogcschemas)
private static final String OGC_EXAMPLES_BASE_URL = "http://schemas.opengis.net/filter/2.0/examples/";
@Before
public void setUp()
throws Exception {
new FunctionManager().startup( DeegreeWorkspace.getInstance() );
}
@Test
public void parseOGCExample01()
throws XMLStreamException, FactoryConfigurationError, IOException {
for ( Filter filter : getFilters( "filter01.xml" ) ) {
PropertyIsEqualTo op = (PropertyIsEqualTo) ( (OperatorFilter) filter ).getOperator();
ValueReference valRef = (ValueReference) op.getParameter1();
Assert.assertEquals( "SomeProperty", valRef.getAsText() );
Assert.assertEquals( new QName( "SomeProperty" ), valRef.getAsQName() );
@SuppressWarnings("unchecked")
Literal<PrimitiveValue> literal = (Literal<PrimitiveValue>) op.getParameter2();
PrimitiveValue pv = literal.getValue();
Assert.assertEquals( "100", pv.getValue() );
}
}
@Test
public void parseOGCExample02()
throws XMLStreamException, FactoryConfigurationError, IOException {
for ( Filter filter : getFilters( "filter02.xml" ) ) {
PropertyIsLessThan op = (PropertyIsLessThan) ( (OperatorFilter) filter ).getOperator();
ValueReference valRef = (ValueReference) op.getParameter1();
Assert.assertEquals( "DEPTH", valRef.getAsText() );
Assert.assertEquals( new QName( "DEPTH" ), valRef.getAsQName() );
@SuppressWarnings("unchecked")
Literal<PrimitiveValue> literal = (Literal<PrimitiveValue>) op.getParameter2();
PrimitiveValue pv = literal.getValue();
Assert.assertEquals( "30", pv.getValue() );
}
}
@Test
public void parseOGCExample03()
throws XMLStreamException, FactoryConfigurationError, IOException {
URL[] urls = getUrls( "filter03.xml" );
for ( int i = 1; i < urls.length; i++ ) {
// gml 2.1.2 version of this example is borked (coordinates)
InputStream is = urls[i].openStream();
XMLStreamReader xmlStream = XMLInputFactory.newInstance().createXMLStreamReader( is );
XMLStreamUtils.skipStartDocument( xmlStream );
Filter filter = Filter200XMLDecoder.parse( xmlStream );
Not not = (Not) ( (OperatorFilter) filter ).getOperator();
Disjoint op = (Disjoint) not.getParameter();
ValueReference valRef = (ValueReference) op.getParam1();
Assert.assertEquals( "Geometry", valRef.getAsText() );
Assert.assertEquals( new QName( "Geometry" ), valRef.getAsQName() );
@SuppressWarnings("unchecked")
Envelope env = (Envelope) op.getGeometry();
// Assert.assertEquals( "urn:fes:def:crs:EPSG::4326", env.getCoordinateSystem().getName() );
}
}
@Test
public void parseOGCExample04()
throws XMLStreamException, FactoryConfigurationError, IOException {
for ( Filter filter : getFilters( "filter04.xml" ) ) {
And and = (And) ( (OperatorFilter) filter ).getOperator();
PropertyIsLessThan propIsLessThan = (PropertyIsLessThan) and.getParams()[0];
ValueReference valRef = (ValueReference) propIsLessThan.getParameter1();
Assert.assertEquals( "DEPTH", valRef.getAsText() );
Assert.assertEquals( new QName( "DEPTH" ), valRef.getAsQName() );
@SuppressWarnings("unchecked")
Literal<PrimitiveValue> literal = (Literal<PrimitiveValue>) propIsLessThan.getParameter2();
PrimitiveValue pv = literal.getValue();
Assert.assertEquals( "30", pv.getValue() );
Not not = (Not) and.getParams()[1];
Disjoint op = (Disjoint) not.getParameter();
valRef = (ValueReference) op.getParam1();
Assert.assertEquals( "Geometry", valRef.getAsText() );
Assert.assertEquals( new QName( "Geometry" ), valRef.getAsQName() );
Envelope env = (Envelope) op.getGeometry();
// Assert.assertEquals( "urn:fes:def:crs:EPSG::4326", env.getCoordinateSystem().getName() );
}
}
@Test
public void parseOGCExample05()
throws XMLStreamException, FactoryConfigurationError, IOException {
for ( Filter filter : getFilters( "filter05.xml" ) ) {
IdFilter idFilter = (IdFilter) filter;
Assert.assertTrue( idFilter.getSelectedIds().size() == 6 );
Assert.assertEquals( "TREESA_1M.1234", idFilter.getSelectedIds().get( 0 ).getRid() );
Assert.assertEquals( "TREESA_1M.5678", idFilter.getSelectedIds().get( 1 ).getRid() );
Assert.assertEquals( "TREESA_1M.9012", idFilter.getSelectedIds().get( 2 ).getRid() );
Assert.assertEquals( "INWATERA_1M.3456", idFilter.getSelectedIds().get( 3 ).getRid() );
Assert.assertEquals( "INWATERA_1M.7890", idFilter.getSelectedIds().get( 4 ).getRid() );
Assert.assertEquals( "BUILTUPA_1M.4321", idFilter.getSelectedIds().get( 5 ).getRid() );
}
}
@Test
public void parseOGCExample06()
throws XMLStreamException, FactoryConfigurationError, IOException {
for ( Filter filter : getFilters( "filter06.xml" ) ) {
PropertyIsEqualTo op = (PropertyIsEqualTo) ( (OperatorFilter) filter ).getOperator();
Function function = (Function) op.getParameter1();
Assert.assertEquals( "SIN", function.getName() );
ValueReference valRef = (ValueReference) function.getParams()[0];
Assert.assertEquals( "DISPERSION_ANGLE", valRef.getAsText() );
@SuppressWarnings("unchecked")
Literal<PrimitiveValue> literal = (Literal<PrimitiveValue>) op.getParameter2();
PrimitiveValue pv = literal.getValue();
Assert.assertEquals( "1", pv.getValue() );
}
}
@Test
public void parseOGCExample07()
throws XMLStreamException, FactoryConfigurationError, IOException {
for ( Filter filter : getFilters( "filter07.xml" ) ) {
PropertyIsEqualTo op = (PropertyIsEqualTo) ( (OperatorFilter) filter ).getOperator();
ValueReference valRef = (ValueReference) op.getParameter1();
Assert.assertEquals( "PROPA", valRef.getAsText() );
Function function = (Function) op.getParameter2();
Assert.assertEquals( "Add", function.getName() );
valRef = (ValueReference) function.getParams()[0];
Assert.assertEquals( "PROPB", valRef.getAsText() );
@SuppressWarnings("unchecked")
Literal<PrimitiveValue> literal = (Literal<PrimitiveValue>) function.getParams()[1];
PrimitiveValue pv = literal.getValue();
Assert.assertEquals( "100", pv.getValue() );
}
}
@Test
@SuppressWarnings("unchecked")
public void parseOGCExample08()
throws XMLStreamException, FactoryConfigurationError, IOException {
for ( Filter filter : getFilters( "filter08.xml" ) ) {
PropertyIsBetween op = (PropertyIsBetween) ( (OperatorFilter) filter ).getOperator();
ValueReference valRef = (ValueReference) op.getExpression();
Assert.assertEquals( "DEPTH", valRef.getAsText() );
Literal<PrimitiveValue> literal = (Literal<PrimitiveValue>) op.getLowerBoundary();
PrimitiveValue pv = literal.getValue();
Assert.assertEquals( "100", pv.getValue() );
literal = (Literal<PrimitiveValue>) op.getUpperBoundary();
pv = literal.getValue();
Assert.assertEquals( "200", pv.getValue() );
}
}
@SuppressWarnings("unchecked")
@Test
public void parseOGCExample09()
throws XMLStreamException, FactoryConfigurationError, IOException {
for ( Filter filter : getFilters( "filter09.xml" ) ) {
PropertyIsBetween op = (PropertyIsBetween) ( (OperatorFilter) filter ).getOperator();
ValueReference valRef = (ValueReference) op.getExpression();
Assert.assertEquals( "SAMPLE_DATE", valRef.getAsText() );
Literal<PrimitiveValue> literal = (Literal<PrimitiveValue>) op.getLowerBoundary();
PrimitiveValue pv = literal.getValue();
Assert.assertEquals( "2001-01-15T20:07:48.11", pv.getValue() );
literal = (Literal<PrimitiveValue>) op.getUpperBoundary();
pv = literal.getValue();
Assert.assertEquals( "2001-03-06T12:00:00.00", pv.getValue() );
}
}
@SuppressWarnings("unchecked")
@Test
public void parseOGCExample10()
throws XMLStreamException, FactoryConfigurationError, IOException {
for ( Filter filter : getFilters( "filter10.xml" ) ) {
PropertyIsLike op = (PropertyIsLike) ( (OperatorFilter) filter ).getOperator();
assertEquals( "*", op.getWildCard() );
assertEquals( "#", op.getSingleChar() );
assertEquals( "!", op.getEscapeChar() );
ValueReference valRef = (ValueReference) op.getExpression();
assertEquals( "LAST_NAME", valRef.getAsText() );
Literal<PrimitiveValue> literal = (Literal<PrimitiveValue>) op.getPattern();
PrimitiveValue pv = literal.getValue();
assertEquals( "JOHN*", pv.getValue() );
}
}
@Test
public void parseOGCExample11()
throws XMLStreamException, FactoryConfigurationError, IOException {
for ( Filter filter : getFilters( "filter11.xml" ) ) {
Overlaps op = (Overlaps) ( (OperatorFilter) filter ).getOperator();
ValueReference valRef = (ValueReference) op.getParam1();
assertEquals( "Geometry", valRef.getAsText() );
Polygon polygon = (Polygon) op.getGeometry();
// Assert.assertEquals( "urn:fes:def:crs:EPSG::4326", polygon.getCoordinateSystem().getName() );
}
}
@Test
public void parseOGCExample12()
throws XMLStreamException, FactoryConfigurationError, IOException {
for ( Filter filter : getFilters( "filter12.xml" ) ) {
And and = (And) ( (OperatorFilter) filter ).getOperator();
}
}
@Test
public void parseOGCExample13()
throws XMLStreamException, FactoryConfigurationError, IOException {
for ( Filter filter : getFilters( "filter13.xml" ) ) {
And and = (And) ( (OperatorFilter) filter ).getOperator();
}
}
@Test
public void parseOGCExample14()
throws XMLStreamException, FactoryConfigurationError, IOException {
for ( Filter filter : getFilters( "filter14.xml" ) ) {
And and = (And) ( (OperatorFilter) filter ).getOperator();
}
}
// @Test
// public void parseOGCExample15()
// throws XMLStreamException, FactoryConfigurationError, IOException {
// for ( Filter filter : getFilters( "filter15.xml" ) ) {
// @Test
// public void parseOGCExample16()
// throws XMLStreamException, FactoryConfigurationError, IOException {
// for ( Filter filter : getFilters( "filter16.xml" ) ) {
// @Test
// public void parseOGCExample17()
// throws XMLStreamException, FactoryConfigurationError, IOException {
// for ( Filter filter : getFilters( "filter17.xml" ) ) {
// @Test
// public void parseOGCExample18()
// throws XMLStreamException, FactoryConfigurationError, IOException {
// for ( Filter filter : getFilters( "filter18.xml" ) ) {
private Filter[] getFilters( String name )
throws IOException, XMLStreamException, FactoryConfigurationError {
URL[] urls = getUrls( name );
Filter[] filters = new Filter[urls.length];
for ( int i = 0; i < urls.length; i++ ) {
InputStream is = urls[i].openStream();
XMLStreamReader xmlStream = XMLInputFactory.newInstance().createXMLStreamReader( is );
XMLStreamUtils.skipStartDocument( xmlStream );
filters[i] = Filter200XMLDecoder.parse( xmlStream );
Assert.assertNotNull( filters[i] );
}
Assert.assertEquals( 4, filters.length );
return filters;
}
private URL[] getUrls( String name ) {
URL[] urls = new URL[4];
urls[0] = buildUrl( name, "2.1.2" );
urls[1] = buildUrl( name, "3.1.1" );
urls[2] = buildUrl( name, "3.2.0" );
urls[3] = buildUrl( name, "3.2.1" );
return urls;
}
private URL buildUrl( String name, String version ) {
try {
String url = new RedirectingEntityResolver().redirect( OGC_EXAMPLES_BASE_URL + version + "/" + name );
return new URL( url );
} catch ( MalformedURLException e ) {
// should never happen
}
return null;
}
}
|
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class TPARobotDrive extends RobotDrive {
private double m_magnitude;
private double m_direction;
private double m_rotation;
private final TPAJoystick joystick;
public TPARobotDrive(int frontLeftMotor, int rearLeftMotor, int frontRightMotor, int rearRightMotor, TPAJoystick joystick) {
super(frontLeftMotor, rearLeftMotor, frontRightMotor, rearRightMotor);
this.joystick=joystick;
}
public void mecanumDrive_Polar() {
double throttle=(joystick.getRawAxis(4) - 1) / -2;
TPALCD.getInstance().println(1, "Speed mult: x" + throttle);
SmartDashboard.putNumber("Speed multiplier", throttle);
m_magnitude = joystick.getMagnitude() * throttle;
m_direction = joystick.getDirectionDegrees();
m_rotation = joystick.getTwist() * throttle;
mecanumDrive_Polar(m_magnitude, m_direction, m_rotation);
}
public SpeedController getFrontLeftMotor()
{
return m_frontLeftMotor;
}
public SpeedController getFrontRightMotor()
{
return m_frontRightMotor;
}
public SpeedController getRearLeftMotor()
{
return m_rearLeftMotor;
}
public SpeedController getRearRightMotor()
{
return m_rearRightMotor;
}
}
|
package edu.oregonstate.cope.eclipse.branding;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.AssertionFailedException;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.WorkbenchWindow;
import org.eclipse.ui.internal.actions.CommandAction;
import org.eclipse.ui.texteditor.StatusLineContributionItem;
import edu.illinois.bundleupdater.BundleUpdater;
@SuppressWarnings("restriction")
public class LogoManager {
private static LogoManager instance;
private final static String STATUS_LINE_CONTRIBUTION_ITEM_ID= "edu.illinois.codingspectator.branding.StatusLine";
private static final String COMMAND_ID = "edu.oregonstate.edu.cope.eclipse.branding.logoAction";
private final static String NORMAL_LOGO = "icons/cope-logo-normal.png";
private final static String UPDATE_LOGO = "icons/cope-logo-update.png";
private IStatusLineManager statusLineManager;
private String commandToExecute = "org.eclipse.ui.help.aboutAction";
private class CheckForUpdatesJob extends Job {
public CheckForUpdatesJob(String name) {
super(name);
}
@Override
protected IStatus run(IProgressMonitor monitor) {
if(new BundleUpdater("http://cope.eecs.oregonstate.edu/client-recorder", "org.oregonstate.edu.eclipse").shouldUpdate()) {
showUpdateIsAvailable();
commandToExecute = "org.eclipse.equinox.p2.ui.sdk.update";
}
return Status.OK_STATUS;
}
}
public static LogoManager getInstance() {
if (instance == null)
instance = new LogoManager();
return instance;
}
private LogoManager() {
}
private IStatusLineManager getStatusLineManager() {
if (statusLineManager != null)
return statusLineManager;
IWorkbenchWindow activeWindow= PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (activeWindow == null)
return null;
statusLineManager = ((WorkbenchWindow)activeWindow).getStatusLineManager();
return statusLineManager;
}
private boolean logoExists() {
return getStatusLineManager().find(STATUS_LINE_CONTRIBUTION_ITEM_ID) != null;
}
private void addLogoToStatusLine() {
addLogoToStatusLine(NORMAL_LOGO);
}
private void addLogoToStatusLine(String imageFilePath) {
Image codingspectatorLogo= Activator.imageDescriptorFromPlugin(Activator.PLUGIN_ID, imageFilePath).createImage(); //$NON-NLS-1$
StatusLineContributionItem contributionItem= new StatusLineContributionItem(STATUS_LINE_CONTRIBUTION_ITEM_ID);
contributionItem.setImage(codingspectatorLogo);
contributionItem.setToolTipText("COPE recorder");
IWorkbench workbench = PlatformUI.getWorkbench();
getStatusLineManager().add(contributionItem);
getStatusLineManager().update(false);
CommandAction commandAction = new CommandAction(workbench, COMMAND_ID);
contributionItem.setActionHandler(commandAction);
try {
Assert.isTrue(logoExists());
} catch (AssertionFailedException e) {
// add loggin stuff
}
}
public void showLogo() {
showLogo(NORMAL_LOGO);
}
public synchronized void showLogo(final String imageFilePath) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
addLogoToStatusLine(imageFilePath);
}
});
}
public void removeLogo() {
getStatusLineManager().remove(STATUS_LINE_CONTRIBUTION_ITEM_ID);
getStatusLineManager().markDirty();
getStatusLineManager().update(false);
}
public void showUpdateIsAvailable() {
removeLogo();
showLogo(UPDATE_LOGO);
}
public String getCommandToExecute() {
return commandToExecute;
}
}
|
package org.camunda.bpm.engine.test.history;
import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
public class HistoricProcessInstanceQueryOrTest {
@Rule
public ProcessEngineRule processEngineRule = new ProcessEngineRule();
@Rule
public ExpectedException thrown = ExpectedException.none();
protected HistoryService historyService;
protected RuntimeService runtimeService;
protected RepositoryService repositoryService;
protected ManagementService managementService;
protected List<String> deploymentIds = new ArrayList<>();
@Before
public void init() {
historyService = processEngineRule.getHistoryService();
runtimeService = processEngineRule.getRuntimeService();
repositoryService = processEngineRule.getRepositoryService();
managementService = processEngineRule.getManagementService();
}
@After
public void deleteDeployments() {
for (String deploymentId : deploymentIds) {
repositoryService.deleteDeployment(deploymentId, true);
}
}
@Test
public void shouldThrowExceptionByMissingStartOr() {
thrown.expect(ProcessEngineException.class);
thrown.expectMessage("Invalid query usage: cannot set endOr() before or()");
historyService.createHistoricProcessInstanceQuery()
.or()
.endOr()
.endOr();
}
@Test
public void shouldThrowExceptionByNesting() {
thrown.expect(ProcessEngineException.class);
thrown.expectMessage("Invalid query usage: cannot set or() within 'or' query");
historyService.createHistoricProcessInstanceQuery()
.or()
.or()
.endOr()
.endOr()
.or()
.endOr();
}
@Test
public void shouldThrowExceptionOnOrderByProcessInstanceId() {
// given
// then
thrown.expect(ProcessEngineException.class);
thrown.expectMessage("Invalid query usage: cannot set orderByProcessInstanceId() within 'or' query");
// when
historyService.createHistoricProcessInstanceQuery()
.or()
.orderByProcessInstanceId()
.endOr();
}
@Test
public void shouldThrowExceptionOnOrderByProcessDefinitionId() {
// given
// then
thrown.expect(ProcessEngineException.class);
thrown.expectMessage("Invalid query usage: cannot set orderByProcessDefinitionId() within 'or' query");
// when
historyService.createHistoricProcessInstanceQuery()
.or()
.orderByProcessDefinitionId()
.endOr();
}
@Test
public void shouldThrowExceptionOnOrderByProcessDefinitionKey() {
// given
// then
thrown.expect(ProcessEngineException.class);
thrown.expectMessage("Invalid query usage: cannot set orderByProcessDefinitionKey() within 'or' query");
// when
historyService.createHistoricProcessInstanceQuery()
.or()
.orderByProcessDefinitionKey()
.endOr();
}
@Test
public void shouldThrowExceptionOnOrderByTenantId() {
// given
// then
thrown.expect(ProcessEngineException.class);
thrown.expectMessage("Invalid query usage: cannot set orderByTenantId() within 'or' query");
// when
historyService.createHistoricProcessInstanceQuery()
.or()
.orderByTenantId()
.endOr();
}
@Test
public void shouldThrowExceptionOnOrderByProcessInstanceDuration() {
// given
// then
thrown.expect(ProcessEngineException.class);
thrown.expectMessage("Invalid query usage: cannot set orderByProcessInstanceDuration() within 'or' query");
// when
historyService.createHistoricProcessInstanceQuery()
.or()
.orderByProcessInstanceDuration()
.endOr();
}
@Test
public void shouldThrowExceptionOnOrderByProcessInstanceStartTime() {
// given
// then
thrown.expect(ProcessEngineException.class);
thrown.expectMessage("Invalid query usage: cannot set orderByProcessInstanceStartTime() within 'or' query");
// when
historyService.createHistoricProcessInstanceQuery()
.or()
.orderByProcessInstanceStartTime()
.endOr();
}
@Test
public void shouldThrowExceptionOnOrderByProcessInstanceEndTime() {
// given
// then
thrown.expect(ProcessEngineException.class);
thrown.expectMessage("Invalid query usage: cannot set orderByProcessInstanceEndTime() within 'or' query");
// then
historyService.createHistoricProcessInstanceQuery()
.or()
.orderByProcessInstanceEndTime()
.endOr();
}
@Test
public void shouldThrowExceptionOnOrderByProcessInstanceBusinessKey() {
// given
// then
thrown.expect(ProcessEngineException.class);
thrown.expectMessage("Invalid query usage: cannot set orderByProcessInstanceBusinessKey() within 'or' query");
// then
historyService.createHistoricProcessInstanceQuery()
.or()
.orderByProcessInstanceBusinessKey()
.endOr();
}
@Test
public void shouldThrowExceptionOnOrderByProcessDefinitionName() {
// given
// then
thrown.expect(ProcessEngineException.class);
thrown.expectMessage("Invalid query usage: cannot set orderByProcessDefinitionName() within 'or' query");
// then
historyService.createHistoricProcessInstanceQuery()
.or()
.orderByProcessDefinitionName()
.endOr();
}
@Test
public void shouldThrowExceptionOnOrderByProcessDefinitionVersion() {
// given
// then
thrown.expect(ProcessEngineException.class);
thrown.expectMessage("Invalid query usage: cannot set orderByProcessDefinitionVersion() within 'or' query");
// then
historyService.createHistoricProcessInstanceQuery()
.or()
.orderByProcessDefinitionVersion()
.endOr();
}
@Test
@Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
public void shouldReturnHistoricProcInstWithEmptyOrQuery() {
// given
ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.deleteProcessInstance(processInstance1.getId(), "test");
runtimeService.deleteProcessInstance(processInstance2.getId(), "test");
// when
List<HistoricProcessInstance> processInstances = historyService.createHistoricProcessInstanceQuery()
.or()
.endOr()
.list();
// then
assertEquals(2, processInstances.size());
}
@Test
@Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
public void shouldReturnHistoricProcInstWithVarValue1OrVarValue2() {
// given
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("stringVar", "abcdef");
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
vars = new HashMap<String, Object>();
vars.put("stringVar", "ghijkl");
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
// when
List<HistoricProcessInstance> processInstances = historyService.createHistoricProcessInstanceQuery()
.or()
.variableValueEquals("stringVar", "abcdef")
.variableValueEquals("stringVar", "ghijkl")
.endOr()
.list();
// then
assertEquals(2, processInstances.size());
}
@Test
@Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
public void shouldReturnHistoricProcInstWithMultipleOrCriteria() {
// given
ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("stringVar", "abcdef");
ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
runtimeService.setVariable(processInstance2.getProcessInstanceId(), "aVarName", "varValue");
vars = new HashMap<>();
vars.put("stringVar2", "aaabbbaaa");
ProcessInstance processInstance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
runtimeService.setVariable(processInstance3.getProcessInstanceId(), "bVarName", "bTestb");
vars = new HashMap<>();
vars.put("stringVar2", "cccbbbccc");
ProcessInstance processInstance4 = runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
runtimeService.setVariable(processInstance4.getProcessInstanceId(), "bVarName", "aTesta");
// when
List<HistoricProcessInstance> processInstances = historyService.createHistoricProcessInstanceQuery()
.or()
.variableValueEquals("stringVar", "abcdef")
.variableValueLike("stringVar2", "%bbb%")
.processInstanceId(processInstance1.getId())
.endOr()
.list();
// then
assertEquals(4, processInstances.size());
}
@Test
@Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
public void shouldReturnHistoricProcInstFilteredByMultipleOrAndCriteria() {
// given
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("stringVar", "abcdef");
vars.put("longVar", 12345L);
ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
vars = new HashMap<>();
vars.put("stringVar", "ghijkl");
vars.put("longVar", 56789L);
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
vars = new HashMap<>();
vars.put("stringVar", "abcdef");
vars.put("longVar", 56789L);
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
vars = new HashMap<>();
vars.put("stringVar", "ghijkl");
vars.put("longVar", 12345L);
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
// when
List<HistoricProcessInstance> processInstances = historyService.createHistoricProcessInstanceQuery()
.or()
.variableValueEquals("longVar", 56789L)
.processInstanceId(processInstance1.getId())
.endOr()
.variableValueEquals("stringVar", "abcdef")
.list();
// then
assertEquals(2, processInstances.size());
}
@Test
@Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
public void shouldReturnHistoricProcInstFilteredByMultipleOrQueries() {
// given
Map<String, Object> vars = new HashMap<>();
vars.put("stringVar", "abcdef");
vars.put("longVar", 12345L);
vars.put("boolVar", true);
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
vars = new HashMap<>();
vars.put("stringVar", "ghijkl");
vars.put("longVar", 56789L);
vars.put("boolVar", true);
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
vars = new HashMap<>();
vars.put("stringVar", "abcdef");
vars.put("longVar", 56789L);
vars.put("boolVar", true);
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
vars = new HashMap<>();
vars.put("stringVar", "ghijkl");
vars.put("longVar", 12345L);
vars.put("boolVar", true);
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
vars = new HashMap<>();
vars.put("stringVar", "ghijkl");
vars.put("longVar", 56789L);
vars.put("boolVar", false);
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
vars = new HashMap<>();
vars.put("stringVar", "abcdef");
vars.put("longVar", 12345L);
vars.put("boolVar", false);
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
// when
List<HistoricProcessInstance> processInstances = historyService.createHistoricProcessInstanceQuery()
.or()
.variableValueEquals("stringVar", "abcdef")
.variableValueEquals("longVar", 12345L)
.endOr()
.or()
.variableValueEquals("boolVar", true)
.variableValueEquals("longVar", 12345L)
.endOr()
.or()
.variableValueEquals("stringVar", "ghijkl")
.variableValueEquals("longVar", 56789L)
.endOr()
.or()
.variableValueEquals("stringVar", "ghijkl")
.variableValueEquals("boolVar", false)
.variableValueEquals("longVar", 56789L)
.endOr()
.list();
// then
assertEquals(2, processInstances.size());
}
@Test
@Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
public void shouldReturnHistoricProcInstWhereSameCriterionWasAppliedThreeTimesInOneQuery() {
// given
ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
ProcessInstance processInstance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
// when
List<HistoricProcessInstance> processInstances = historyService.createHistoricProcessInstanceQuery()
.or()
.processInstanceId(processInstance1.getId())
.processInstanceId(processInstance2.getId())
.processInstanceId(processInstance3.getId())
.endOr()
.list();
// then
assertEquals(1, processInstances.size());
}
@Test
@Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
public void shouldReturnHistoricProcInstWithVariableValueEqualsOrVariableValueGreaterThan() {
// given
Map<String, Object> vars = new HashMap<>();
vars.put("longVar", 12345L);
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
vars = new HashMap<>();
vars.put("longerVar", 56789L);
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
vars = new HashMap<>();
vars.put("longerVar", 56789L);
runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);
// when
HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery()
.or()
.variableValueEquals("longVar", 12345L)
.variableValueGreaterThan("longerVar", 20000L)
.endOr();
// then
assertEquals(3, query.count());
}
@Test
public void shouldReturnHistoricProcInstWithProcessDefinitionNameOrProcessDefinitionKey() {
// given
BpmnModelInstance aProcessDefinition = Bpmn.createExecutableProcess("aProcessDefinition")
.name("process1")
.startEvent()
.userTask()
.endEvent()
.done();
String deploymentId = repositoryService
.createDeployment()
.addModelInstance("foo.bpmn", aProcessDefinition)
.deploy()
.getId();
deploymentIds.add(deploymentId);
ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("aProcessDefinition");
BpmnModelInstance anotherProcessDefinition = Bpmn.createExecutableProcess("anotherProcessDefinition")
.startEvent()
.userTask()
.endEvent()
.done();
deploymentId = repositoryService
.createDeployment()
.addModelInstance("foo.bpmn", anotherProcessDefinition)
.deploy()
.getId();
deploymentIds.add(deploymentId);
runtimeService.startProcessInstanceByKey("anotherProcessDefinition");
// when
List<HistoricProcessInstance> processInstances = historyService.createHistoricProcessInstanceQuery()
.or()
.processDefinitionId(processInstance1.getProcessDefinitionId())
.processDefinitionKey("anotherProcessDefinition")
.endOr()
.list();
// then
assertEquals(2, processInstances.size());
}
@Test
public void shouldReturnHistoricProcInstWithBusinessKeyOrBusinessKeyLike() {
// given
BpmnModelInstance aProcessDefinition = Bpmn.createExecutableProcess("aProcessDefinition")
.startEvent()
.userTask()
.endEvent()
.done();
String deploymentId = repositoryService
.createDeployment()
.addModelInstance("foo.bpmn", aProcessDefinition)
.deploy()
.getId();
deploymentIds.add(deploymentId);
runtimeService.startProcessInstanceByKey("aProcessDefinition", "aBusinessKey");
BpmnModelInstance anotherProcessDefinition = Bpmn.createExecutableProcess("anotherProcessDefinition")
.startEvent()
.userTask()
.endEvent()
.done();
deploymentId = repositoryService
.createDeployment()
.addModelInstance("foo.bpmn", anotherProcessDefinition)
.deploy()
.getId();
deploymentIds.add(deploymentId);
runtimeService.startProcessInstanceByKey("anotherProcessDefinition", "anotherBusinessKey");
// when
List<HistoricProcessInstance> processInstances = historyService.createHistoricProcessInstanceQuery()
.or()
.processInstanceBusinessKey("aBusinessKey")
.processInstanceBusinessKeyLike("anotherBusinessKey")
.endOr()
.list();
// then
assertEquals(2, processInstances.size());
}
@Test
public void shouldReturnHistoricProcInstWithActivityIdInOrProcInstId() {
// given
BpmnModelInstance aProcessDefinition = Bpmn.createExecutableProcess("aProcessDefinition")
.startEvent()
.userTask()
.endEvent()
.done();
String deploymentId = repositoryService
.createDeployment()
.addModelInstance("foo.bpmn", aProcessDefinition)
.deploy()
.getId();
deploymentIds.add(deploymentId);
ProcessInstance processInstance1 = runtimeService
.startProcessInstanceByKey("aProcessDefinition");
String activityInstanceId = runtimeService.getActivityInstance(processInstance1.getId())
.getChildActivityInstances()[0].getActivityId();
ProcessInstance processInstance2 = runtimeService
.startProcessInstanceByKey("aProcessDefinition");
// when
List<HistoricProcessInstance> tasks = historyService.createHistoricProcessInstanceQuery()
.or()
.activeActivityIdIn(activityInstanceId)
.processInstanceId(processInstance2.getId())
.endOr()
.list();
// then
assertEquals(2, tasks.size());
}
@Test
public void shouldReturnHistoricProcInstByVariableAndActiveProcesses() {
// given
BpmnModelInstance aProcessDefinition = Bpmn.createExecutableProcess("oneTaskProcess")
.startEvent()
.userTask("testQuerySuspensionStateTask")
.endEvent()
.done();
String deploymentId = repositoryService
.createDeployment()
.addModelInstance("foo.bpmn", aProcessDefinition)
.deploy()
.getId();
deploymentIds.add(deploymentId);
// start two process instance and leave them active
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
// start one process instance and suspend it
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("foo", 0);
ProcessInstance suspendedProcessInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", variables);
runtimeService.suspendProcessInstanceById(suspendedProcessInstance.getProcessInstanceId());
// assume
assertEquals(2, historyService.createHistoricProcessInstanceQuery().processDefinitionKey("oneTaskProcess").active().count());
assertEquals(1, historyService.createHistoricProcessInstanceQuery().processDefinitionKey("oneTaskProcess").suspended().count());
// then
assertEquals(3, historyService.createHistoricProcessInstanceQuery().or().active().variableValueEquals("foo", 0).endOr().list().size());
}
@Test
@Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
public void shouldReturnByProcessDefinitionKeyOrActivityId() {
// given
runtimeService.startProcessInstanceByKey("oneTaskProcess");
BpmnModelInstance aProcessDefinition = Bpmn.createExecutableProcess("process")
.startEvent()
.userTask("aUserTask")
.endEvent()
.done();
String deploymentId = repositoryService
.createDeployment()
.addModelInstance("foo.bpmn", aProcessDefinition)
.deploy()
.getId();
deploymentIds.add(deploymentId);
runtimeService.startProcessInstanceByKey("process");
// when
List<HistoricProcessInstance> processInstances = historyService.createHistoricProcessInstanceQuery()
.or()
.activeActivityIdIn("theTask")
.processDefinitionKey("process")
.endOr()
.list();
// then
assertThat(processInstances.size()).isEqualTo(2);
}
@Test
@Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
public void shouldReturnByProcessDefinitionIdOrIncidentType() {
// given
String processDefinitionId = runtimeService.startProcessInstanceByKey("oneTaskProcess")
.getProcessDefinitionId();
BpmnModelInstance aProcessDefinition = Bpmn.createExecutableProcess("process")
.startEvent().camundaAsyncBefore()
.userTask("aUserTask")
.endEvent()
.done();
String deploymentId = repositoryService
.createDeployment()
.addModelInstance("foo.bpmn", aProcessDefinition)
.deploy()
.getId();
deploymentIds.add(deploymentId);
runtimeService.startProcessInstanceByKey("process");
String jobId = managementService.createJobQuery().singleResult().getId();
managementService.setJobRetries(jobId, 0);
// when
List<HistoricProcessInstance> processInstances = historyService.createHistoricProcessInstanceQuery()
.or()
.incidentType("failedJob")
.processDefinitionId(processDefinitionId)
.endOr()
.list();
// then
assertThat(processInstances.size()).isEqualTo(2);
}
}
|
package de.charite.compbio.exomiser.core.factories;
import jannovar.exception.JannovarException;
import jannovar.io.SerializationManager;
import jannovar.reference.Chromosome;
import jannovar.reference.TranscriptModel;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handles de-serialising of known genes files produced from UCSC or Ensemble
* data.
*
* @author Jules Jacobsen <jules.jacobsen@sanger.ac.uk>
*/
public class ChromosomeMapFactory {
public static final Logger logger = LoggerFactory.getLogger(ChromosomeMapFactory.class);
private static final SerializationManager manager = new SerializationManager();
/**
* Jannovar makes a serialized file that represents a HashMap<String,
* TranscriptModel> containing each and every
* {@link jannovar.reference.TranscriptModel TranscriptModel} object. This
* method both deserializes this file and also adds each TranscriptModel to
* the corresponding IntervalTree of the
* {@link jannovar.reference.Chromosome Chromosome} object. When we are
* done, the {@link exomizer.Exomizer#chromosomeMap} contains Chromosome
* objects for chromosomes 1-22,X,Y, and M, each of which contains the
* TranscriptModel objects for each of the genes located on those
* chromosomes.
*/
public static Map<Byte, Chromosome> deserializeKnownGeneData(Path serealizedKnownGenePath) {
logger.info("DESERIALISING KNOWN GENES FILE: {}", serealizedKnownGenePath);
ArrayList<TranscriptModel> transcriptModels = makeTranscriptModelsFromFile(serealizedKnownGenePath);
logger.info("DONE DESERIALISING KNOWN GENES");
return Chromosome.constructChromosomeMapWithIntervalTree(transcriptModels);
}
private static ArrayList<TranscriptModel> makeTranscriptModelsFromFile(Path serealizedKnownGenePath) throws RuntimeException {
try {
return manager.deserializeKnownGeneList(serealizedKnownGenePath.toString());
} catch (JannovarException je) {
String message = String.format("Unable to deserialize the known gene definition file: %s", serealizedKnownGenePath);
logger.error(message);
throw new RuntimeException(message, je);
}
}
}
|
package net.sf.taverna.t2.workbench.file.impl.menu;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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.Serializable;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import net.sf.taverna.raven.appconfig.ApplicationRuntime;
import net.sf.taverna.t2.lang.observer.Observable;
import net.sf.taverna.t2.lang.observer.Observer;
import net.sf.taverna.t2.ui.menu.AbstractMenuCustom;
import net.sf.taverna.t2.workbench.file.FileManager;
import net.sf.taverna.t2.workbench.file.FileType;
import net.sf.taverna.t2.workbench.file.events.AbstractDataflowEvent;
import net.sf.taverna.t2.workbench.file.events.ClosedDataflowEvent;
import net.sf.taverna.t2.workbench.file.events.FileManagerEvent;
import net.sf.taverna.t2.workbench.file.events.OpenedDataflowEvent;
import net.sf.taverna.t2.workbench.file.events.SavedDataflowEvent;
import net.sf.taverna.t2.workbench.file.exceptions.OpenException;
import net.sf.taverna.t2.workflowmodel.Dataflow;
import net.sf.taverna.t2.workflowmodel.serialization.xml.AbstractXMLDeserializer;
import net.sf.taverna.t2.workflowmodel.serialization.xml.AbstractXMLSerializer;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
public class FileOpenRecentMenuAction extends AbstractMenuCustom implements
Observer<FileManagerEvent> {
public static final URI RECENT_URI = URI
.create("http://taverna.sf.net/2008/t2workbench/menu#fileOpenRecent");
private static final String CONF = "conf";
private static FileManager fileManager = FileManager.getInstance();
private static Logger logger = Logger
.getLogger(FileOpenRecentMenuAction.class);
private static final String RECENT_WORKFLOWS_XML = "recentWorkflows.xml";
private final int MAX_ITEMS = 10;
private JMenu menu;
private List<Recent> recents = new ArrayList<Recent>();
public FileOpenRecentMenuAction() {
super(FileOpenMenuSection.FILE_OPEN_SECTION_URI, 30, RECENT_URI);
fileManager.addObserver(this);
}
public void notify(Observable<FileManagerEvent> sender,
FileManagerEvent message) throws Exception {
FileManager fileManager = (FileManager) sender;
if ((message instanceof OpenedDataflowEvent)
|| (message instanceof SavedDataflowEvent)) {
AbstractDataflowEvent dataflowEvent = (AbstractDataflowEvent) message;
Dataflow dataflow = dataflowEvent.getDataflow();
Object dataflowSource = fileManager.getDataflowSource(dataflow);
FileType dataflowType = fileManager.getDataflowType(dataflow);
addRecent(dataflowSource, dataflowType);
}
if (message instanceof ClosedDataflowEvent) {
// Make sure enabled/disabled status is correct
updateRecentMenu();
}
}
public void updateRecentMenu() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
updateRecentMenuGUI();
}
});
saveRecent();
}
protected void addRecent(Object dataflowSource, FileType dataflowType) {
if (dataflowSource == null) {
return;
}
if (!(dataflowSource instanceof Serializable)) {
logger.warn("Can't serialize dataflow source for 'Recent workflows': "
+ dataflowSource);
return;
}
synchronized (recents) {
Recent recent = new Recent((Serializable) dataflowSource, dataflowType);
if (recents.contains(recent)) {
recents.remove(recent);
}
recents.add(0, recent); // Add to front
}
updateRecentMenu();
}
@Override
protected Component createCustomComponent() {
action = new DummyAction("Recent workflows");
action.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_R);
menu = new JMenu(action);
loadRecent();
updateRecentMenu();
return menu;
}
protected synchronized void loadRecent() {
File confDir = new File(ApplicationRuntime.getInstance()
.getApplicationHomeDir(), CONF);
confDir.mkdir();
File recentFile = new File(confDir, RECENT_WORKFLOWS_XML);
if (!recentFile.isFile()) {
return;
}
SAXBuilder builder = new SAXBuilder();
Document document;
try {
InputStream fileInputStream;
fileInputStream = new BufferedInputStream(new FileInputStream(
recentFile));
document = builder.build(fileInputStream);
} catch (JDOMException e) {
logger.warn("Could not read recent workflows from file "
+ recentFile, e);
return;
} catch (IOException e) {
logger.warn("Could not read recent workflows from file "
+ recentFile, e);
return;
}
synchronized (recents) {
recents.clear();
RecentDeserializer deserialiser = new RecentDeserializer();
try {
recents.addAll(deserialiser.deserializeRecent(document
.getRootElement()));
} catch (Exception e) {
logger.warn("Could not read recent workflows from file "
+ recentFile, e);
return;
}
}
}
protected synchronized void saveRecent() {
File confDir = new File(ApplicationRuntime.getInstance()
.getApplicationHomeDir(), CONF);
confDir.mkdir();
File recentFile = new File(confDir, RECENT_WORKFLOWS_XML);
RecentSerializer serializer = new RecentSerializer();
XMLOutputter outputter = new XMLOutputter();
OutputStream outputStream = null;
try {
Element serializedRecent;
synchronized (recents) {
if (recents.size() > MAX_ITEMS) {
// Remove excess entries
recents.subList(MAX_ITEMS, recents.size()).clear();
}
serializedRecent = serializer.serializeRecent(recents);
}
outputStream = new BufferedOutputStream(new FileOutputStream(
recentFile));
outputter.output(serializedRecent, outputStream);
} catch (JDOMException e) {
logger.warn("Could not generate XML for recent workflows to file "
+ recentFile, e);
return;
} catch (IOException e) {
logger.warn("Could not write recent workflows to file "
+ recentFile, e);
return;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
logger.warn(
"Could not close file writing recent workflows to file "
+ recentFile, e);
}
}
}
}
protected void updateRecentMenuGUI() {
int items = 0;
menu.removeAll();
synchronized (recents) {
for (Recent recent : recents) {
if (++items >= MAX_ITEMS) {
break;
}
OpenRecentAction openRecentAction = new OpenRecentAction(recent);
if (fileManager.getDataflowBySource(recent.getDataflowSource()) != null) {
openRecentAction.setEnabled(false);
} // else setEnabled(true)
JMenuItem menuItem = new JMenuItem(openRecentAction);
if (items < 10) {
openRecentAction.putValue(Action.NAME, items + " " + openRecentAction.getValue(Action.NAME));
menuItem.setMnemonic(KeyEvent.VK_0 + items);
}
menu.add(menuItem);
}
}
menu.setEnabled(items > 0);
menu.revalidate();
}
public static class OpenRecentAction extends AbstractAction implements
Runnable {
private final Recent recent;
private Component component = null;
public OpenRecentAction(Recent recent) {
this.recent = recent;
Serializable source = recent.getDataflowSource();
String name;
if (source instanceof File) {
name = ((File) source).getAbsolutePath();
} else {
name = source.toString();
}
this.putValue(NAME, name);
this.putValue(SHORT_DESCRIPTION, "Open the workflow " + name);
}
public void actionPerformed(ActionEvent e) {
component = null;
if (e.getSource() instanceof Component) {
component = (Component) e.getSource();
}
setEnabled(false);
new Thread(this, "Opening workflow from "
+ recent.getDataflowSource()).start();
}
/**
* Opening workflow in separate thread
*/
public void run() {
final Serializable source = recent.getDataflowSource();
try {
fileManager.openDataflow(recent.makefileType(), source);
} catch (OpenException ex) {
logger.warn("Failed to open the workflow from " + source
+ " \n", ex);
JOptionPane.showMessageDialog(component,
"Failed to open the workflow from url " + source
+ " \n" + ex.getMessage(), "Error!",
JOptionPane.ERROR_MESSAGE);
} finally {
setEnabled(true);
}
}
}
public static class Recent implements Serializable {
private final class RecentFileType extends FileType {
@Override
public String getMimeType() {
return mimeType;
}
@Override
public String getExtension() {
return extension;
}
@Override
public String getDescription() {
return "File type " + extension + " " + mimeType;
}
}
private Serializable dataflowSource;
private String mimeType;
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
private String extension;
public Recent() {
}
public FileType makefileType() {
if (mimeType == null && extension == null) {
return null;
}
return new RecentFileType();
}
public Recent(Serializable dataflowSource, FileType dataflowType) {
this.setDataflowSource(dataflowSource);
if (dataflowType != null) {
this.setMimeType(dataflowType.getMimeType());
this.setExtension(dataflowType.getExtension());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((dataflowSource == null) ? 0 : dataflowSource.hashCode());
result = prime * result
+ ((extension == null) ? 0 : extension.hashCode());
result = prime * result
+ ((mimeType == null) ? 0 : mimeType.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Recent)) {
return false;
}
Recent other = (Recent) obj;
if (dataflowSource == null) {
if (other.dataflowSource != null) {
return false;
}
} else if (!dataflowSource.equals(other.dataflowSource)) {
return false;
}
if (extension == null) {
if (other.extension != null) {
return false;
}
} else if (!extension.equals(other.extension)) {
return false;
}
if (mimeType == null) {
if (other.mimeType != null) {
return false;
}
} else if (!mimeType.equals(other.mimeType)) {
return false;
}
return true;
}
public Serializable getDataflowSource() {
return dataflowSource;
}
public void setDataflowSource(Serializable dataflowSource) {
this.dataflowSource = dataflowSource;
}
@Override
public String toString() {
return getDataflowSource() + "";
}
}
protected static class RecentDeserializer extends AbstractXMLDeserializer {
public Collection<Recent> deserializeRecent(Element el) {
return (Collection<Recent>) super.createBean(el, getClass()
.getClassLoader());
}
}
protected static class RecentSerializer extends AbstractXMLSerializer {
public Element serializeRecent(List<Recent> x) throws JDOMException,
IOException {
Element beanAsElement = super.beanAsElement(x);
return beanAsElement;
}
}
}
|
/*
* $Id: LockssTestCase.java,v 1.52 2004-04-05 08:01:58 tlipkis Exp $
*/
package org.lockss.test;
import java.util.*;
import java.io.*;
import java.net.*;
import org.lockss.util.*;
import org.lockss.daemon.*;
import junit.framework.TestCase;
import junit.framework.TestResult;
public class LockssTestCase extends TestCase {
protected static Logger log =
Logger.getLoggerWithInitialLevel("LockssTest",
Logger.getInitialDefaultLevel());
/** Timeout duration for timeouts that are expected to time out. Setting
* this higher makes normal tests take longer, setting it too low might
* cause failing tests to erroneously succeed on slow or busy
* machines. */
public static int TIMEOUT_SHOULD = 300;
/** Timeout duration for timeouts that are expected not to time out.
* This should be set high to ensure catching failures. */
public static final int DEFAULT_TIMEOUT_SHOULDNT = 2000;
public static int TIMEOUT_SHOULDNT = DEFAULT_TIMEOUT_SHOULDNT;
private MockLockssDaemon mockDaemon = null;
List tmpDirs;
List doLaters = null;
public LockssTestCase(String msg) {
this();
setName(msg);
}
public LockssTestCase() {
super();
Integer timeout = Integer.getInteger("org.lockss.test.timeout.shouldnt");
if (timeout != null) {
TIMEOUT_SHOULDNT = timeout.intValue();
}
}
/**
* Create and return the name of a temp dir. The dir is created within
* the default temp file dir.
* It will be deleted following the test, by tearDown(). (So if you
* override tearDown(), be sure to call <code>super.tearDown()</code>.)
* @return The newly created directory
* @throws IOException
*/
public File getTempDir() throws IOException {
File tmpdir = FileTestUtil.createTempDir("locksstest", null);
if (tmpdir != null) {
if (tmpDirs == null) {
tmpDirs = new LinkedList();
}
tmpDirs.add(tmpdir);
}
return tmpdir;
}
/**
* Return the MockLockssDaemon instance for this testcase, creating one
* if necessary.
*/
public synchronized MockLockssDaemon getMockLockssDaemon() {
if (mockDaemon == null) {
mockDaemon = new MockLockssDaemon();
}
return mockDaemon;
}
/** Create a fresh config manager, MockLockssDaemon */
protected void setUp() throws Exception {
mockDaemon = null;
super.setUp();
disableThreadWatchdog();
ConfigManager.makeConfigManager();
}
/**
* Remove any temp dirs, cancel any outstanding {@link
* org.lockss.test.LockssTestCase.DoLater}s
* @throws Exception
*/
protected void tearDown() throws Exception {
if (doLaters != null) {
List copy;
synchronized (this) {
copy = new ArrayList(doLaters);
}
for (Iterator iter = copy.iterator(); iter.hasNext(); ) {
DoLater doer = (DoLater)iter.next();
doer.cancel();
}
// do NOT set doLaters to null here. It may be referenced by
// exiting DoLaters. It won't hurt anything because the next test
// will create a new instance of the test case, and get a different
// doLaters list
}
// XXX this should be folded into LockssDaemon shutdown
ConfigManager cfg = ConfigManager.getConfigManager();
if (cfg != null) {
cfg.stopService();
}
TimerQueue.stopTimerQueue();
// delete temp dirs
boolean leave = Boolean.getBoolean("org.lockss.keepTempFiles");
if (tmpDirs != null && !leave) {
for (ListIterator iter = tmpDirs.listIterator(); iter.hasNext(); ) {
File dir = (File)iter.next();
if (FileTestUtil.delTree(dir)) {
log.debug2("deltree(" + dir + ") = true");
iter.remove();
} else {
log.debug2("deltree(" + dir + ") = false");
}
}
}
super.tearDown();
if (Boolean.getBoolean("org.lockss.test.threadDump")) {
DebugUtils.getInstance().threadDump();
TimerUtil.guaranteedSleep(1000);
}
enableThreadWatchdog();
}
protected void disableThreadWatchdog() {
LockssThread.disableWatchdog(true);
}
protected void enableThreadWatchdog() {
LockssThread.disableWatchdog(false);
}
double successRate;
int successMaxRepetitions;
int successMaxFailures;
/** Causes the current test case to be repeated if it fails, ultimately
* succeeding if the success rate is sufficiently high. If a test is
* repeated, a message will be written to System.err. Repetitions are
* not reflected in test statistics.
* @param rate the minimum success rate between 0 and 1 (successes /
* attempts) necessary for the test ultimately to succeed.
* @param maxRepetitions the maximum number of times the test will be
* repeated in an attempt to achieve the specified success rate.
* @see #successRateSetUp()
* @see #successRateTearDown()
*/
protected void assertSuccessRate(double rate, int maxRepetitions) {
if (successMaxFailures == 0) {
successRate = rate;
successMaxRepetitions = maxRepetitions;
successMaxFailures = maxRepetitions - ((int)(rate * maxRepetitions));
}
}
/**
* Runs the bare test sequence, repeating if necessary to achieve the
* specified success rate.
* @see #assertSuccessRate
* @exception Throwable if any exception is thrown
*/
public void runBare() throws Throwable {
int rpt = 0;
int failures = 0;
successRateSetUp();
try {
while (true) {
try {
super.runBare();
} catch (Throwable e) {
if (++failures > successMaxFailures) {
rpt++;
throw e;
}
}
if (++rpt >= successMaxRepetitions) {
break;
}
if ((((double)(rpt - failures)) / ((double)rpt)) > successRate) {
break;
}
}
} finally {
if (successMaxFailures > 0 && failures > 0) {
System.err.println(getName() + " failed " + failures +
" of " + rpt + " tries, " +
((failures > successMaxFailures) ? "not " : "") +
"achieving a " + successRate + " success rate.");
}
successRateTearDown();
}
}
/** Called once (before setUp()) before a set of repetitions of a test
* case that uses assertSuccessRate(). (setUp() is called before each
* repetition.) */
protected void successRateSetUp() {
successMaxFailures = 0;
}
/** Called once (after tearDown()) after a set of repetitions of a test
* case that uses assertSuccessRate(). (tearDown() is called after each
* repetition.) */
protected void successRateTearDown() {
}
/**
* Asserts that two Maps are equal (contain the same mappings).
* If they are not an AssertionFailedError is thrown.
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
static public void assertEqual(String message, Map expected, Map actual) {
if (expected == null && actual == null) {
return;
}
if (expected != null && expected.equals(actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that two Maps are equal (contain the same mappings).
* If they are not an AssertionFailedError is thrown.
* @param expected the expected value
* @param actual the actual value
*/
static public void assertEqual(Map expected, Map actual) {
assertEqual(null, expected, actual);
}
/**
* Asserts that two collections are isomorphic. If they are not
* an AssertionFailedError is thrown.
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
static public void assertIsomorphic(String message,
Collection expected, Collection actual) {
if (CollectionUtil.isIsomorphic(expected, actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that two collections are isomorphic. If they are not
* an AssertionFailedError is thrown.
* @param expected the expected value
* @param actual the actual value
*/
static public void assertIsomorphic(Collection expected, Collection actual) {
assertIsomorphic(null, expected, actual);
}
/**
* Asserts that the array is isomorphic with the collection. If not
* an AssertionFailedError is thrown.
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
static public void assertIsomorphic(String message,
Object expected[], Collection actual) {
if (CollectionUtil.isIsomorphic(expected, actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that the array is isomorphic with the collection. If not
* an AssertionFailedError is thrown.
* @param expected the expected value
* @param actual the actual value
*/
static public void assertIsomorphic(Object expected[], Collection actual) {
assertIsomorphic(null, expected, actual);
}
/**
* Asserts that the array is isomorphic with the collection behind the
* iterator. If not an AssertionFailedError is thrown.
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
static public void assertIsomorphic(String message,
Object expected[], Iterator actual) {
if (CollectionUtil.isIsomorphic(new ArrayIterator(expected), actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that the array is isomorphic with the collection behind the
* iterator. If not an AssertionFailedError is thrown.
* @param expected the expected value
* @param actual the actual value
*/
static public void assertIsomorphic(Object expected[], Iterator actual) {
assertIsomorphic(null, expected, actual);
}
/**
* Asserts that the two boolean arrays have equal contents
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(boolean[] expected, boolean[] actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that the two boolean arrays have equal contents
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(String message,
boolean[] expected, boolean[] actual) {
if (Arrays.equals(expected, actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that the two byte arrays have equal contents
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(byte[] expected, byte[] actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that the two byte arrays have equal contents
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(String message,
byte[] expected, byte[] actual) {
if (Arrays.equals(expected, actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that the two char arrays have equal contents
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(char[] expected, char[] actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that the two char arrays have equal contents
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(String message,
char[] expected, char[] actual) {
if (Arrays.equals(expected, actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that the two double arrays have equal contents
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(double[] expected, double[] actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that the two double arrays have equal contents
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(String message,
double[] expected, double[] actual) {
if (Arrays.equals(expected, actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that the two float arrays have equal contents
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(float[] expected, float[] actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that the two float arrays have equal contents
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(String message,
float[] expected, float[] actual) {
if (Arrays.equals(expected, actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that the two int arrays have equal contents
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(int[] expected, int[] actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that the two int arrays have equal contents
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(String message,
int[] expected, int[] actual) {
if (Arrays.equals(expected, actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that the two short arrays have equal contents
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(short[] expected, short[] actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that the two short arrays have equal contents
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(String message,
short[] expected, short[] actual) {
if (Arrays.equals(expected, actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that the two long arrays have equal contents
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(long[] expected, long[] actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that the two long arrays have equal contents
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(String message,
long[] expected, long[] actual) {
if (Arrays.equals(expected, actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that the two Object arrays have equal contents
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(Object[] expected, Object[] actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that the two Object arrays have equal contents
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(String message,
Object[] expected, Object[] actual) {
if (Arrays.equals(expected, actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that the two URLs are equal
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(URL expected, URL actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that the two URLs are equal
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(String message,
URL expected, URL actual) {
if (UrlUtil.equalUrls(expected, actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that two objects are not equal. If they are not
* an AssertionFailedError is thrown with the given message.
* @param message the message to give on failure
* @param expected the expected value
* @param actual the actual value
*/
public static void assertNotEquals(String message,
Object expected, Object actual) {
if ((expected == null && actual == null) ||
(expected != null && expected.equals(actual))) {
failEquals(message, expected, actual);
}
}
/**
* Asserts that two objects are not equal. If they are not
* an AssertionFailedError is thrown with the given message.
* @param expected the expected value
* @param actual the actual value
*/
public static void assertNotEquals(Object expected, Object actual) {
assertNotEquals(null, expected, actual);
}
public static void assertNotEquals(long expected, long actual) {
assertNotEquals(null, expected, actual);
}
public static void assertNotEquals(String message,
long expected, long actual) {
assertNotEquals(message, new Long(expected), new Long(actual));
}
public static void assertNotEquals(int expected, int actual) {
assertNotEquals(null, expected, actual);
}
public static void assertNotEquals(String message,
int expected, int actual) {
assertNotEquals(message, new Integer(expected), new Integer(actual));
}
public static void assertNotEquals(short expected, short actual) {
assertNotEquals(null, expected, actual);
}
public static void assertNotEquals(String message,
short expected, short actual) {
assertNotEquals(message, new Short(expected), new Short(actual));
}
public static void assertNotEquals(byte expected, byte actual) {
assertNotEquals(null, expected, actual);
}
public static void assertNotEquals(String message,
byte expected, byte actual) {
assertNotEquals(message, new Byte(expected), new Byte(actual));
}
public static void assertNotEquals(char expected, char actual) {
assertNotEquals(null, expected, actual);
}
public static void assertNotEquals(String message,
char expected, char actual) {
assertNotEquals(message, new Character(expected), new Character(actual));
}
public static void assertNotEquals(boolean expected, boolean actual) {
assertNotEquals(null, expected, actual);
}
public static void assertNotEquals(String message,
boolean expected, boolean actual) {
assertNotEquals(message, new Boolean(expected), new Boolean(actual));
}
public static void assertNotEquals(double expected, double actual,
double delta) {
assertNotEquals(null, expected, actual, delta);
}
public static void assertNotEquals(String message, double expected,
double actual, double delta) {
// handle infinity specially since subtracting to infinite
//values gives NaN and the the following test fails
if (Double.isInfinite(expected)) {
if (expected == actual){
failEquals(message, new Double(expected), new Double(actual));
}
} else if ((Math.abs(expected-actual) <= delta)) {
// Because comparison with NaN always returns false
failEquals(message, new Double(expected), new Double(actual));
}
}
public static void assertNotEquals(float expected, float actual,
float delta) {
assertNotEquals(null, expected, actual, delta);
}
public static void assertNotEquals(String message, float expected,
float actual, float delta) {
// handle infinity specially since subtracting to infinite
//values gives NaN and the the following test fails
if (Double.isInfinite(expected)) {
if (expected == actual){
failEquals(message, new Float(expected), new Float(actual));
}
} else if ((Math.abs(expected-actual) <= delta)) {
// Because comparison with NaN always returns false
failEquals(message, new Float(expected), new Float(actual));
}
}
public static void assertEmpty(Collection coll) {
assertEmpty(null, coll);
}
public static void assertEmpty(String message, Collection coll) {
if (coll.size() > 0) {
StringBuffer sb = new StringBuffer();
if (message != null) {
sb.append(message);
sb.append(" ");
}
sb.append("Expected empty Collection, but containted ");
sb.append(coll);
fail(sb.toString());
}
}
public static void assertEmpty(Map map) {
assertEmpty(null, map);
}
public static void assertEmpty(String message, Map map) {
if (map.size() > 0) {
StringBuffer sb = new StringBuffer();
if (message != null) {
sb.append(message);
sb.append(" ");
}
sb.append("Expected empty Map, but contained ");
sb.append(map);
fail(sb.toString());
}
}
public static void assertContainsAll(Collection coll,
Object[] elements) {
for (int i = 0; i < elements.length; i++) {
assertContains(coll, elements[i]);
}
}
public static void assertContains(Collection coll, Object element) {
assertContains(null, coll, element);
}
public static void assertContains(String msg, Collection coll,
Object element) {
if (!coll.contains(element)) {
StringBuffer sb = new StringBuffer();
if (msg != null) {
sb.append(msg);
sb.append(" ");
}
sb.append("Collection doesn't contain expected element: ");
sb.append(element);
fail(sb.toString());
}
}
public static void assertDoesNotContain(Collection coll, Object element) {
assertDoesNotContain(null, coll, element);
}
public static void assertDoesNotContain(String msg, Collection coll,
Object element) {
if (coll.contains(element)) {
StringBuffer sb = new StringBuffer();
if (msg != null) {
sb.append(msg);
sb.append(" ");
}
sb.append("Collection contains unexpected element: ");
sb.append(element);
fail(sb.toString());
}
}
private static void failEquals(String message,
Object expected, Object actual) {
StringBuffer sb = new StringBuffer();
if (message != null) {
sb.append(message);
sb.append(" ");
}
sb.append("expected not equals, but both were ");
sb.append(expected);
fail(sb.toString());
}
// tk do a better job of printing collections
static private void failNotEquals(String message,
Object expected, Object actual) {
String formatted= "";
if (message != null)
formatted= message+" ";
fail(formatted+"expected:<"+expected+"> but was:<"+actual+">");
}
static private void failNotEquals(String message,
int[] expected, int[] actual) {
String formatted= "";
if (message != null)
formatted= message+" ";
fail(formatted+"expected:<"+arrayString(expected)+
"> but was:<"+arrayString(actual)+">");
}
static protected Object[] objArray(int[] a) {
Object[] o = new Object[a.length];
for (int ix = 0; ix < a.length; ix++) {
o[ix] = new Integer(a[ix]);
}
return o;
}
static protected String arrayString(int[] a) {
return StringUtil.separatedString(objArray(a), ", ");
}
static private void failNotEquals(String message,
long[] expected, long[] actual) {
String formatted= "";
if (message != null)
formatted= message+" ";
fail(formatted+"expected:<"+arrayString(expected)+
"> but was:<"+arrayString(actual)+">");
}
static protected Object[] objArray(long[] a) {
Object[] o = new Object[a.length];
for (int ix = 0; ix < a.length; ix++) {
o[ix] = new Long(a[ix]);
}
return o;
}
static protected String arrayString(long[] a) {
return StringUtil.separatedString(objArray(a), ", ");
}
static private void failNotEquals(String message,
byte[] expected, byte[] actual) {
String formatted= "";
if (message != null)
formatted= message+" ";
fail(formatted+"expected:<"+ByteArray.toHexString(expected)+
"> but was:<"+ByteArray.toHexString(actual)+">");
// fail(formatted+"expected:<"+arrayString(expected)+
// "> but was:<"+arrayString(actual)+">");
}
static protected Object[] objArray(byte[] a) {
Object[] o = new Object[a.length];
for (int ix = 0; ix < a.length; ix++) {
o[ix] = new Integer(a[ix]);
}
return o;
}
static protected String arrayString(byte[] a) {
return StringUtil.separatedString(objArray(a), ", ");
}
static private void failNotEquals(String message,
Object[] expected, Object actual) {
failNotEquals(message,
"[" + StringUtil.separatedString(expected, ", ") + "]",
actual);
}
/**
* Asserts that the two DatagramPackets have equal contents
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(DatagramPacket expected,
DatagramPacket actual) {
assertEquals(expected.getAddress(), actual.getAddress());
assertEquals(expected.getPort(), actual.getPort());
assertEquals(expected.getLength(), actual.getLength());
assertEquals(expected.getOffset(), actual.getOffset());
assertTrue(Arrays.equals(expected.getData(), actual.getData()));
}
/**
* Asserts that two collections have all the same elements of the same
* cardinality; tries to give useful output if it fails
*/
public static void assertSameElements(Collection expected,
Collection actual) {
assertTrue("Expected "+expected+" but was "+actual,
org.apache.commons.collections.
CollectionUtils.isEqualCollection(expected, actual));
}
/**
* Asserts that a string matches the content of a reader
*/
public static void assertReaderMatchesString(String expected, Reader reader)
throws IOException{
int len = expected.length() * 2;
char[] ca = new char[len];
StringBuffer actual = new StringBuffer(expected.length());
int n;
while ((n = reader.read(ca)) != -1) {
actual.append(ca, 0, n);
}
assertEquals(expected, actual.toString());
}
/**
* Asserts that a string matches the content of a reader. Old, character
* at a time version. Should be integrated into tests because it
* possibly causes different behavior in the stream under test.
*/
public static void assertReaderMatchesStringSlow(String expected,
Reader reader)
throws IOException{
StringBuffer actual = new StringBuffer(expected.length());
int kar;
while ((kar = reader.read()) != -1) {
actual.append((char)kar);
}
assertEquals(expected, actual.toString());
}
/** Abstraction to do something in another thread, after a delay,
* unless cancelled. If the sceduled activity is still pending when the
* test completes, it is cancelled by tearDown().
* <br>For one-off use:<pre>
* final Object obj = ...;
* DoLater doer = new DoLater(1000) {
* protected void doit() {
* obj.method(...);
* }
* };
* doer.start();</pre>
*
* Or, for convenient repeated use of a particular delayed operation,
* define a class that extends <code>DoLater</code>,
* with a constructor that calls
* <code>super(wait)</code> and stores any other necessary args into
* instance vars, and a <code>doit()</code> method that does whatever needs
* to be done. And a convenience method to create and start it.
* For example, <code>Interrupter</code> is defined as:<pre>
* public class Interrupter extends DoLater {
* private Thread thread;
* Interrupter(long waitMs, Thread thread) {
* super(waitMs);
* this.thread = thread;
* }
*
* protected void doit() {
* thread.interrupt();
* }
* }
*
* public Interrupter interruptMeIn(long ms) {
* Interrupter i = new Interrupter(ms, Thread.currentThread());
* i.start();
* return i;
* }</pre>
*
* Then, to protect a test with a timeout:<pre>
* Interrupter intr = null;
* try {
* intr = interruptMeIn(1000);
* // perform a test that should complete in less than one second
* intr.cancel();
* } finally {
* if (intr.did()) {
* fail("operation failed to complete in one second");
* }
* }</pre>
* The <code>cancel()</code> ensures that the interrupt will not
* happen after the try block completes. (This is not necessary at the
* end of a test case, as any pending interrupters will be cancelled
* by tearDown.)
*/
protected abstract class DoLater extends Thread {
private long wait;
private boolean want = true;
private boolean did = false;
protected DoLater(long waitMs) {
wait = waitMs;
}
/** Must override this to perform desired action */
protected abstract void doit();
/**
* Return true iff action was taken
* @return true iff taken
*/
public boolean did() {
return did;
}
/** Cancel the action iff it hasn't already started. If it has started,
* wait until it completes. (Thus when <code>cancel()</code> returns, it
* is safe to destroy any environment on which the action relies.)
*/
public synchronized void cancel() {
if (want) {
want = false;
this.interrupt();
}
}
public final void run() {
try {
synchronized (LockssTestCase.this) {
if (doLaters == null) {
doLaters = new LinkedList();
}
doLaters.add(this);
}
if (wait != 0) {
TimerUtil.sleep(wait);
}
synchronized (this) {
if (want) {
want = false;
did = true;
doit();
}
}
} catch (InterruptedException e) {
// exit thread
} finally {
synchronized (LockssTestCase.this) {
doLaters.remove(this);
}
}
}
}
/** Interrupter interrupts a thread in a while */
public class Interrupter extends DoLater {
private Thread thread;
private boolean threadDump = false;
Interrupter(long waitMs, Thread thread) {
super(waitMs);
setPriority(thread.getPriority() + 1);
this.thread = thread;
}
/** Interrupt the thread */
protected void doit() {
log.debug("Interrupting");
if (threadDump) {
try {
DebugUtils.getInstance().threadDump();
TimerUtil.guaranteedSleep(1000);
} catch (Exception e) {
}
}
thread.interrupt();
}
/** Interrupt the thread */
public void setThreadDump() {
threadDump = true;
}
}
/**
* Interrupt current thread in a while
* @param ms interval to wait before interrupting
* @return an Interrupter
*/
public Interrupter interruptMeIn(long ms) {
Interrupter i = new Interrupter(ms, Thread.currentThread());
i.start();
return i;
}
/**
* Interrupt current thread in a while, first printing a thread dump
* @param ms interval to wait before interrupting
* @param threadDump true if thread dump wanted
* @return an Interrupter
*/
public Interrupter interruptMeIn(long ms, boolean threadDump) {
Interrupter i = new Interrupter(ms, Thread.currentThread());
if (threadDump) {
i.setThreadDump();
}
i.start();
return i;
}
}
|
package com.dmdirc.parser.irc;
import com.dmdirc.parser.common.BaseSocketAwareParser;
import com.dmdirc.parser.common.ChannelJoinRequest;
import com.dmdirc.parser.common.ChildImplementations;
import com.dmdirc.parser.common.CompositionState;
import com.dmdirc.parser.common.IgnoreList;
import com.dmdirc.parser.common.MyInfo;
import com.dmdirc.parser.common.ParserError;
import com.dmdirc.parser.common.QueuePriority;
import com.dmdirc.parser.common.SRVRecord;
import com.dmdirc.parser.common.SystemEncoder;
import com.dmdirc.parser.events.ConnectErrorEvent;
import com.dmdirc.parser.events.DataInEvent;
import com.dmdirc.parser.events.DataOutEvent;
import com.dmdirc.parser.events.DebugInfoEvent;
import com.dmdirc.parser.events.ErrorInfoEvent;
import com.dmdirc.parser.events.PingFailureEvent;
import com.dmdirc.parser.events.PingSentEvent;
import com.dmdirc.parser.events.PingSuccessEvent;
import com.dmdirc.parser.events.ServerErrorEvent;
import com.dmdirc.parser.events.ServerReadyEvent;
import com.dmdirc.parser.events.SocketCloseEvent;
import com.dmdirc.parser.interfaces.ChannelInfo;
import com.dmdirc.parser.interfaces.Encoder;
import com.dmdirc.parser.interfaces.EncodingParser;
import com.dmdirc.parser.interfaces.SecureParser;
import com.dmdirc.parser.irc.IRCReader.ReadLine;
import com.dmdirc.parser.irc.outputqueue.OutputQueue;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Timer;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import dagger.ObjectGraph;
/**
* IRC Parser.
*/
@ChildImplementations({
IRCChannelClientInfo.class,
IRCChannelInfo.class,
IRCClientInfo.class
})
public class IRCParser extends BaseSocketAwareParser implements SecureParser, EncodingParser {
/** Max length an outgoing line should be (NOT including \r\n). */
public static final int MAX_LINELENGTH = 510;
/** General Debug Information. */
public static final int DEBUG_INFO = 1;
/** Socket Debug Information. */
public static final int DEBUG_SOCKET = 2;
/** Processing Manager Debug Information. */
public static final int DEBUG_PROCESSOR = 4;
/** List Mode Queue Debug Information. */
public static final int DEBUG_LMQ = 8;
/** Attempt to update user host all the time, not just on Who/Add/NickChange. */
public static final boolean ALWAYS_UPDATECLIENT = true;
/** Byte used to show that a non-boolean mode is a list (b). */
public static final byte MODE_LIST = 1;
/** Byte used to show that a non-boolean mode is not a list, and requires a parameter to set (lk). */
static final byte MODE_SET = 2;
/** Byte used to show that a non-boolean mode is not a list, and requires a parameter to unset (k). */
public static final byte MODE_UNSET = 4;
/**
* Default channel prefixes if none are specified by the IRCd.
*
* <p>These are the RFC 2811 specified prefixes: '#', '&', '!' and '+'.
*/
private static final String DEFAULT_CHAN_PREFIX = "
/**
* This is what the user wants settings to be.
* Nickname here is *not* always accurate.<br><br>
* ClientInfo variable tParser.getMyself() should be used for accurate info.
*/
private MyInfo me = new MyInfo();
/** Should PINGs be sent to the server to check if its alive? */
private boolean checkServerPing = true;
/** Timer for server ping. */
private Timer pingTimer;
/** Semaphore for access to pingTimer. */
private final Semaphore pingTimerSem = new Semaphore(1);
/** Is a ping needed? */
private final AtomicBoolean pingNeeded = new AtomicBoolean(false);
/** Time last ping was sent at. */
private long pingTime;
/** Current Server Lag. */
private long serverLag;
/** Last value sent as a ping argument. */
private String lastPingValue = "";
/**
* Count down to next ping.
* The timer fires every 10 seconds, this value is decreased every time the
* timer fires.<br>
* Once it reaches 0, we send a ping, and reset it to 6, this means we ping
* the server every minute.
*
* @see #setPingTimerInterval
*/
private int pingCountDown;
/** Network name. This is "" if no network name is provided */
public String networkName;
/** This is what we think the nickname should be. */
public String thinkNickname;
/** Have we received the 001. */
public boolean got001;
/** Have we fired post005? */
boolean post005;
/** Has the thread started execution yet, (Prevents run() being called multiple times). */
boolean hasBegan;
/** Manager used to handle prefix modes. */
private final PrefixModeManager prefixModes = new PrefixModeManager();
/** Manager used to handle user modes (owxis etc). */
private final ModeManager userModes = new ModeManager();
/**
* Manager used to handle channel boolean modes.
* <p>
* Channel modes discovered but not listed in 005 are stored as boolean modes automatically (and a ERROR_WARNING Error is called)
*/
private final ModeManager chanModesBool = new ModeManager();
/**
* Hashtable storing known non-boolean chan modes (klbeI etc).
* Non Boolean Modes (for Channels) are stored together in this hashtable, the value param
* is used to show the type of variable. (List (1), Param just for set (2), Param for Set and Unset (2+4=6))<br><br>
* <br>
* see MODE_LIST<br>
* see MODE_SET<br>
* see MODE_UNSET<br>
*/
public final Map<Character, Byte> chanModesOther = new HashMap<>();
/** The last line of input received from the server */
private ReadLine lastLine;
/** Should the lastline (where given) be appended to the "data" part of any onErrorInfo call? */
private boolean addLastLine;
/** Channel Prefixes (ie # + etc). */
private String chanPrefix = DEFAULT_CHAN_PREFIX;
/** Hashtable storing all known clients based on nickname (in lowercase). */
private final Map<String, IRCClientInfo> clientList = new HashMap<>();
/** Hashtable storing all known channels based on chanel name (inc prefix - in lowercase). */
private final Map<String, IRCChannelInfo> channelList = new HashMap<>();
/** Reference to the ClientInfo object that references ourself. */
private IRCClientInfo myself;
/** Hashtable storing all information gathered from 005. */
public final Map<String, String> h005Info = new HashMap<>();
/** difference in ms between our time and the servers time (used for timestampedIRC). */
private long tsdiff;
/** Reference to the Processing Manager. */
private final ProcessingManager myProcessingManager;
/** Should we automatically disconnect on fatal errors?. */
private boolean disconnectOnFatal = true;
/** Current Socket State. */
protected SocketState currentSocketState = SocketState.NULL;
/**
* The underlying socket used for reading/writing to the IRC server.
* For normal sockets this will be the same as {@link #socket} but for SSL
* connections this will be the underlying {@link Socket} while
* {@link #socket} will be an {@link SSLSocket}.
*/
private Socket rawSocket;
/** Used for writing to the server. */
private final OutputQueue out;
/** The encoder to use to encode incoming lines. */
private Encoder encoder = new SystemEncoder();
/** Used for reading from the server. */
private IRCReader in;
/** This is the default TrustManager for SSL Sockets, it trusts all ssl certs. */
private final TrustManager[] trustAllCerts = {new TrustingTrustManager()};
/** Should channels automatically request list modes? */
private boolean autoListMode = true;
/** Should part/quit/kick callbacks be fired before removing the user internally? */
private boolean removeAfterCallback = true;
/** This is the TrustManager used for SSL Sockets. */
private TrustManager[] myTrustManager = trustAllCerts;
/** The KeyManagers used for client certificates for SSL sockets. */
private KeyManager[] myKeyManagers;
/** This is list containing 001 - 005 inclusive. */
private final List<String> serverInformationLines = new LinkedList<>();
/** Map of capabilities and their state. */
private final Map<String, CapabilityState> capabilities = new HashMap<>();
/** Handler for whois responses. */
private final WhoisResponseHandler whoisHandler;
/** Used to synchronize calls to resetState. */
private final Object resetStateSync = new Object();
/**
* Default constructor, ServerInfo and MyInfo need to be added separately (using IRC.me and IRC.server).
*/
public IRCParser() {
this((MyInfo) null);
}
/**
* Constructor with ServerInfo, MyInfo needs to be added separately (using IRC.me).
*
* @param uri The URI to connect to
*/
public IRCParser(final URI uri) {
this(null, uri);
}
/**
* Constructor with MyInfo, ServerInfo needs to be added separately (using IRC.server).
*
* @param myDetails Client information.
*/
public IRCParser(final MyInfo myDetails) {
this(myDetails, null);
}
/**
* Creates a new IRCParser with the specified client details which will
* connect to the specified URI.
*
* @since 0.6.3
* @param myDetails The client details to use
* @param uri The URI to connect to
*/
public IRCParser(final MyInfo myDetails, final URI uri) {
super(uri);
// TODO: There should be a factory or builder for parsers that can construct the graph
final ObjectGraph graph = ObjectGraph.create(new IRCParserModule(this, prefixModes,
userModes, chanModesBool));
myProcessingManager = graph.get(ProcessingManager.class);
myself = new IRCClientInfo(this, userModes, "myself").setFake(true);
out = new OutputQueue();
if (myDetails != null) {
this.me = myDetails;
}
this.whoisHandler = new WhoisResponseHandler(this, getCallbackManager());
setIgnoreList(new IgnoreList());
setPingTimerInterval(10000);
setPingTimerFraction(6);
resetState();
}
/**
* Get the current OutputQueue
*
* @return the current OutputQueue
*/
public OutputQueue getOutputQueue() {
return out;
}
@Override
public boolean compareURI(final URI uri) {
// Get the old URI.
final URI oldURI = getURI();
// Check that protocol, host and port are the same.
// Anything else won't change the server we connect to just what we
// would do after connecting, so is not relevent.
return uri.getScheme().equalsIgnoreCase(oldURI.getScheme())
&& uri.getHost().equalsIgnoreCase(oldURI.getHost())
&& (uri.getUserInfo() == null || uri.getUserInfo().isEmpty()
|| uri.getUserInfo().equalsIgnoreCase(oldURI.getUserInfo() == null ? "" : oldURI.getUserInfo()))
&& uri.getPort() == oldURI.getPort();
}
/**
* From the given URI, get a URI to actually connect to.
* This function will check for DNS SRV records for the given URI and use
* those if found.
* If no SRV records exist, then fallback to using the URI as-is but with
* a default port specified if none is given.
*
* @param uri Requested URI.
* @return A connectable version of the given URI.
*/
private URI getConnectURI(final URI uri) {
if (uri == null) { return null; }
final boolean isSSL = uri.getScheme().endsWith("s");
final int defaultPort = isSSL ? IrcConstants.DEFAULT_SSL_PORT : IrcConstants.DEFAULT_PORT;
// Default to what the URI has already..
int port = uri.getPort();
String host = uri.getHost();
// Look for SRV records if no port is specified.
if (port == -1) {
List<SRVRecord> recordList = new ArrayList<>();
if (isSSL) {
// There are a few possibilities for ssl...
final String[] protocols = {"_ircs._tcp.", "_irc._tls."};
for (final String protocol : protocols) {
recordList = SRVRecord.getRecords(protocol + host);
if (!recordList.isEmpty()) {
break;
}
}
} else {
recordList = SRVRecord.getRecords("_irc._tcp." + host);
}
if (!recordList.isEmpty()) {
host = recordList.get(0).getHost();
port = recordList.get(0).getPort();
}
}
// Fix the port if required.
if (port == -1) { port = defaultPort; }
// Return the URI to connect to based on the above.
try {
return new URI(uri.getScheme(), uri.getUserInfo(), host, port, uri.getPath(), uri.getQuery(), uri.getFragment());
} catch (URISyntaxException ex) {
// Shouldn't happen - but return the URI as-is if it does.
return uri;
}
}
@Override
public Collection<? extends ChannelJoinRequest> extractChannels(final URI uri) {
if (uri == null) {
return Collections.<ChannelJoinRequest>emptyList();
}
String channelString = uri.getPath();
if (uri.getRawQuery() != null && !uri.getRawQuery().isEmpty()) {
channelString += '?' + uri.getRawQuery();
}
if (uri.getRawFragment() != null && !uri.getRawFragment().isEmpty()) {
channelString += '#' + uri.getRawFragment();
}
if (!channelString.isEmpty() && channelString.charAt(0) == '/') {
channelString = channelString.substring(1);
}
return extractChannels(channelString);
}
/**
* Extracts a set of channels and optional keys from the specified String.
* Channels are separated by commas, and keys are separated from their
* channels by a space.
*
* @since 0.6.4
* @param channels The string of channels to parse
* @return A corresponding collection of join request objects
*/
protected Collection<? extends ChannelJoinRequest> extractChannels(final String channels) {
final Collection<ChannelJoinRequest> res = new ArrayList<>();
for (String channel : channels.split(",")) {
final String[] parts = channel.split(" ", 2);
if (parts.length == 2) {
res.add(new ChannelJoinRequest(parts[0], parts[1]));
} else {
res.add(new ChannelJoinRequest(parts[0]));
}
}
return res;
}
/**
* Get the current Value of autoListMode.
*
* @return Value of autoListMode (true if channels automatically ask for list modes on join, else false)
*/
public boolean getAutoListMode() {
return autoListMode;
}
/**
* Set the current Value of autoListMode.
*
* @param newValue New value to set autoListMode
*/
public void setAutoListMode(final boolean newValue) {
autoListMode = newValue;
}
/**
* Get the current Value of removeAfterCallback.
*
* @return Value of removeAfterCallback (true if kick/part/quit callbacks are fired before internal removal)
*/
public boolean getRemoveAfterCallback() {
return removeAfterCallback;
}
/**
* Get the current Value of removeAfterCallback.
*
* @param newValue New value to set removeAfterCallback
*/
public void setRemoveAfterCallback(final boolean newValue) {
removeAfterCallback = newValue;
}
/**
* Get the current Value of addLastLine.
*
* @return Value of addLastLine (true if lastLine info will be automatically
* added to the errorInfo data line). This should be true if lastLine
* isn't handled any other way.
*/
public boolean getAddLastLine() {
return addLastLine;
}
/**
* Get the current Value of addLastLine.
*
* @param newValue New value to set addLastLine
*/
public void setAddLastLine(final boolean newValue) {
addLastLine = newValue;
}
/**
* Get the current socket State.
*
* @since 0.6.3m1
* @return Current {@link SocketState}
*/
public SocketState getSocketState() {
return currentSocketState;
}
/**
* Get a reference to the Processing Manager.
*
* @return Reference to the CallbackManager
*/
public ProcessingManager getProcessingManager() {
return myProcessingManager;
}
/**
* Get a reference to the default TrustManager for SSL Sockets.
*
* @return a reference to trustAllCerts
*/
public TrustManager[] getDefaultTrustManager() {
return Arrays.copyOf(trustAllCerts, trustAllCerts.length);
}
/**
* Get a reference to the current TrustManager for SSL Sockets.
*
* @return a reference to myTrustManager;
*/
public TrustManager[] getTrustManager() {
return Arrays.copyOf(myTrustManager, myTrustManager.length);
}
@Override
public void setTrustManagers(final TrustManager... managers) {
myTrustManager = managers == null ? null : Arrays.copyOf(managers, managers.length);
}
@Override
public void setKeyManagers(final KeyManager... managers) {
myKeyManagers = managers == null ? null : Arrays.copyOf(managers, managers.length);
}
// Start Callbacks
/**
* Callback to all objects implementing the ServerError Callback.
*
* @param message The error message
*/
protected void callServerError(final String message) {
getCallbackManager().publish(new ServerErrorEvent(this, LocalDateTime.now(), message));
}
/**
* Callback to all objects implementing the DataIn Callback.
*
* @param data Incoming Line.
*/
protected void callDataIn(final String data) {
getCallbackManager().publish(new DataInEvent(this, LocalDateTime.now(), data));
}
/**
* Callback to all objects implementing the DataOut Callback.
*
* @param data Outgoing Data
* @param fromParser True if parser sent the data, false if sent using .sendLine
*/
protected void callDataOut(final String data, final boolean fromParser) {
getCallbackManager().publish(new DataOutEvent(this, LocalDateTime.now(), data));
}
/**
* Callback to all objects implementing the DebugInfo Callback.
*
* @param level Debugging Level (DEBUG_INFO, DEBUG_SOCKET etc)
* @param data Debugging Information as a format string
* @param args Formatting String Options
*/
public void callDebugInfo(final int level, final String data, final Object... args) {
callDebugInfo(level, String.format(data, args));
}
/**
* Callback to all objects implementing the DebugInfo Callback.
*
* @param level Debugging Level (DEBUG_INFO, DEBUG_SOCKET etc)
* @param data Debugging Information
*/
protected void callDebugInfo(final int level, final String data) {
getCallbackManager().publish(new DebugInfoEvent(this, LocalDateTime.now(), level, data));
}
/**
* Callback to all objects implementing the IErrorInfo Interface.
*
* @param errorInfo ParserError object representing the error.
*/
public void callErrorInfo(final ParserError errorInfo) {
getCallbackManager().publish(new ErrorInfoEvent(this, LocalDateTime.now(), errorInfo));
}
/**
* Callback to all objects implementing the IConnectError Interface.
*
* @param errorInfo ParserError object representing the error.
*/
protected void callConnectError(final ParserError errorInfo) {
getCallbackManager().publish(new ConnectErrorEvent(this, LocalDateTime.now(), errorInfo));
}
/**
* Callback to all objects implementing the SocketClosed Callback.
*/
protected void callSocketClosed() {
// Don't allow state resetting whilst there may be handlers requiring
// state.
synchronized (resetStateSync) {
getCallbackManager().publish(new SocketCloseEvent(this, LocalDateTime.now()));
}
}
/**
* Callback to all objects implementing the PingFailed Callback.
*/
protected void callPingFailed() {
getCallbackManager().publish(new PingFailureEvent(this, LocalDateTime.now()));
}
/**
* Callback to all objects implementing the PingSent Callback.
*/
protected void callPingSent() {
getCallbackManager().publish(new PingSentEvent(this, LocalDateTime.now()));
}
/**
* Callback to all objects implementing the PingSuccess Callback.
*/
protected void callPingSuccess() {
getCallbackManager().publish(new PingSuccessEvent(this, LocalDateTime.now()));
}
/**
* Callback to all objects implementing the Post005 Callback.
*/
protected synchronized void callPost005() {
if (post005) {
return;
}
post005 = true;
if (!h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES)) {
parsePrefixModes();
}
if (!h005Info.containsKey(IrcConstants.ISUPPORT_USER_MODES)) {
parseUserModes();
}
if (!h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_MODES)) {
parseChanModes();
}
whoisHandler.start();
getCallbackManager().publish(new ServerReadyEvent(this, LocalDateTime.now()));
}
// End Callbacks
/** Reset internal state (use before doConnect). */
private void resetState() {
synchronized (resetStateSync) {
// Reset General State info
got001 = false;
post005 = false;
// Clear the hash tables
channelList.clear();
clientList.clear();
h005Info.clear();
prefixModes.clear();
chanModesOther.clear();
chanModesBool.clear();
userModes.clear();
chanPrefix = DEFAULT_CHAN_PREFIX;
// Clear output queue.
if (out != null) {
out.clearQueue();
}
setServerName("");
networkName = "";
lastLine = null;
myself = new IRCClientInfo(this, userModes, "myself").setFake(true);
synchronized (serverInformationLines) {
serverInformationLines.clear();
}
stopPingTimer();
currentSocketState = SocketState.CLOSED;
setEncoding(IRCEncoding.RFC1459);
whoisHandler.stop();
}
}
/**
* Called after other error callbacks.
* CallbackOnErrorInfo automatically calls this *AFTER* any registered callbacks
* for it are called.
*
* @param errorInfo ParserError object representing the error.
* @param called True/False depending on the the success of other callbacks.
*/
public void onPostErrorInfo(final ParserError errorInfo, final boolean called) {
if (errorInfo.isFatal() && disconnectOnFatal) {
disconnect("Fatal Parser Error");
}
}
/**
* Get the current Value of disconnectOnFatal.
*
* @return Value of disconnectOnFatal (true if the parser automatically disconnects on fatal errors, else false)
*/
public boolean getDisconnectOnFatal() {
return disconnectOnFatal;
}
/**
* Set the current Value of disconnectOnFatal.
*
* @param newValue New value to set disconnectOnFatal
*/
public void setDisconnectOnFatal(final boolean newValue) {
disconnectOnFatal = newValue;
}
/**
* Connect to IRC.
*
* @throws IOException if the socket can not be connected
* @throws NoSuchAlgorithmException if SSL is not available
* @throws KeyManagementException if the trustManager is invalid
*/
private void doConnect() throws IOException, NoSuchAlgorithmException, KeyManagementException {
if (getURI() == null || getURI().getHost() == null) {
throw new UnknownHostException("Unspecified host.");
}
resetState();
callDebugInfo(DEBUG_SOCKET, "Connecting to " + getURI().getHost() + ':' + getURI().getPort());
currentSocketState = SocketState.OPENING;
final URI connectUri = getConnectURI(getURI());
rawSocket = getSocketFactory().createSocket(connectUri.getHost(), connectUri.getPort());
final Socket socket;
if (getURI().getScheme().endsWith("s")) {
callDebugInfo(DEBUG_SOCKET, "Server is SSL.");
if (myTrustManager == null) {
myTrustManager = trustAllCerts;
}
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init(myKeyManagers, myTrustManager, new SecureRandom());
final SSLSocketFactory socketFactory = sc.getSocketFactory();
socket = socketFactory.createSocket(rawSocket, getURI().getHost(), getURI()
.getPort(), false);
// Manually start a handshake so we get proper SSL errors here,
// and so that we can control the connection timeout
final int timeout = socket.getSoTimeout();
socket.setSoTimeout(10000);
((SSLSocket) socket).startHandshake();
socket.setSoTimeout(timeout);
currentSocketState = SocketState.OPENING;
} else {
socket = rawSocket;
}
callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket output stream PrintWriter");
out.setOutputStream(socket.getOutputStream());
out.setQueueEnabled(true);
currentSocketState = SocketState.OPEN;
callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket input stream BufferedReader");
in = new IRCReader(socket.getInputStream(), encoder);
callDebugInfo(DEBUG_SOCKET, "\t-> Socket Opened");
}
/**
* Send server connection strings (NICK/USER/PASS).
*/
protected void sendConnectionStrings() {
sendString("CAP LS");
if (getURI().getUserInfo() != null && !getURI().getUserInfo().isEmpty()) {
sendString("PASS " + getURI().getUserInfo());
}
sendString("NICK " + me.getNickname());
thinkNickname = me.getNickname();
String localhost;
try {
localhost = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException uhe) {
localhost = "*";
}
sendString("USER " + me.getUsername() + ' ' + localhost + ' ' + getURI().getHost() + " :" + me.getRealname());
}
/**
* Handle an onConnect error.
*
* @param e Exception to handle
* @param isUserError Is this a user error?
*/
private void handleConnectException(final Exception e, final boolean isUserError) {
callDebugInfo(DEBUG_SOCKET, "Error Connecting (" + e.getMessage() + "), Aborted");
final ParserError ei = new ParserError(ParserError.ERROR_ERROR + (isUserError ? ParserError.ERROR_USER : 0), "Exception with server socket", getLastLine());
ei.setException(e);
callConnectError(ei);
if (currentSocketState != SocketState.CLOSED) {
currentSocketState = SocketState.CLOSED;
callSocketClosed();
}
resetState();
}
/**
* Begin execution.
* Connect to server, and start parsing incoming lines
*/
@Override
public void run() {
callDebugInfo(DEBUG_INFO, "Begin Thread Execution");
if (hasBegan) {
return;
} else {
hasBegan = true;
}
try {
doConnect();
} catch (IOException e) {
handleConnectException(e, true);
return;
} catch (NoSuchAlgorithmException | KeyManagementException e) {
handleConnectException(e, false);
return;
}
callDebugInfo(DEBUG_SOCKET, "Socket Connected");
sendConnectionStrings();
while (true) {
try {
lastLine = in.readLine(); // Blocking :/
if (lastLine == null) {
if (currentSocketState != SocketState.CLOSED) {
currentSocketState = SocketState.CLOSED;
callSocketClosed();
}
resetState();
break;
} else if (currentSocketState != SocketState.CLOSING) {
processLine(lastLine);
}
} catch (IOException e) {
callDebugInfo(DEBUG_SOCKET, "Exception in main loop (" + e.getMessage() + "), Aborted");
if (currentSocketState != SocketState.CLOSED) {
currentSocketState = SocketState.CLOSED;
callSocketClosed();
}
resetState();
break;
}
}
callDebugInfo(DEBUG_INFO, "End Thread Execution");
}
/** Close socket on destroy. */
@Override
protected void finalize() throws Throwable {
try {
// See note at disconnect() method for why we close rawSocket.
if (rawSocket != null) {
rawSocket.close();
}
} catch (IOException e) {
callDebugInfo(DEBUG_SOCKET, "Could not close socket");
}
super.finalize();
}
/**
* Get the trailing parameter for a line.
* The parameter is everything after the first occurrence of " :" to the last token in the line after a space.
*
* @param line Line to get parameter for
* @return Parameter of the line
*/
public static String getParam(final String line) {
final String[] params = line.split(" :", 2);
return params[params.length - 1];
}
/**
* Tokenise a line.
* splits by " " up to the first " :" everything after this is a single token
*
* @param line Line to tokenise
* @return Array of tokens
*/
public static String[] tokeniseLine(final String line) {
if (line == null || line.isEmpty()) {
return new String[]{""};
}
int lastarg = line.indexOf(" :");
String[] tokens;
// Check for IRC Tags.
if (line.charAt(0) == '@') {
// We have tags.
tokens = line.split(" ", 2);
final int tsEnd = tokens[0].indexOf('@', 1);
boolean hasTSIRCDate = false;
if (tsEnd > -1) {
try {
final long ts = Long.parseLong(tokens[0].substring(1, tsEnd));
hasTSIRCDate = true;
} catch (final NumberFormatException nfe) { /* Not a timestamp. */ }
}
if (!hasTSIRCDate) {
// IRCv3 Tags, last arg is actually the second " :"
lastarg = line.indexOf(" :", lastarg+1);
}
}
if (lastarg > -1) {
final String[] temp = line.substring(0, lastarg).split(" ");
tokens = new String[temp.length + 1];
System.arraycopy(temp, 0, tokens, 0, temp.length);
tokens[temp.length] = line.substring(lastarg + 2);
} else {
tokens = line.split(" ");
}
if (tokens.length < 1) {
tokens = new String[]{""};
}
return tokens;
}
@Override
public IRCClientInfo getClient(final String details) {
final String sWho = getStringConverter().toLowerCase(IRCClientInfo.parseHost(details));
if (clientList.containsKey(sWho)) {
return clientList.get(sWho);
} else {
return new IRCClientInfo(this, userModes, details).setFake(true);
}
}
public boolean isKnownClient(final String host) {
final String sWho = getStringConverter().toLowerCase(IRCClientInfo.parseHost(host));
return clientList.containsKey(sWho);
}
@Override
public IRCChannelInfo getChannel(final String channel) {
synchronized (channelList) {
return channelList.get(getStringConverter().toLowerCase(channel));
}
}
@Override
public void sendInvite(final String channel, final String user) {
sendRawMessage("INVITE " + user + ' ' + channel);
}
@Override
public void sendWhois(final String nickname) {
sendRawMessage("WHOIS " + nickname);
}
@Override
public void sendRawMessage(final String message) {
doSendString(message, QueuePriority.NORMAL, false);
}
@Override
public void sendRawMessage(final String message, final QueuePriority priority) {
doSendString(message, priority, false);
}
/**
* Send a line to the server and add proper line ending.
*
* @param line Line to send (\r\n termination is added automatically)
* @return True if line was sent, else false.
*/
public boolean sendString(final String line) {
return doSendString(line, QueuePriority.NORMAL, true);
}
/**
* Send a line to the server and add proper line ending.
* If a non-empty argument is given, it is appended as a trailing argument
* (i.e., separated by " :"); otherwise, the line is sent as-is.
*
* @param line Line to send
* @param argument Trailing argument for the command, if any
* @return True if line was sent, else false.
*/
protected boolean sendString(final String line, final String argument) {
return sendString(argument.isEmpty() ? line : line + " :" + argument);
}
/**
* Send a line to the server and add proper line ending.
*
* @param line Line to send (\r\n termination is added automatically)
* @param priority Priority of this line.
* @return True if line was sent, else false.
*/
public boolean sendString(final String line, final QueuePriority priority) {
return doSendString(line, priority, true);
}
/**
* Send a line to the server and add proper line ending.
*
* @param line Line to send (\r\n termination is added automatically)
* @param priority Priority of this line.
* @param fromParser is this line from the parser? (used for callDataOut)
* @return True if line was sent, else false.
*/
protected boolean doSendString(final String line, final QueuePriority priority, final boolean fromParser) {
if (out == null || getSocketState() != SocketState.OPEN) {
return false;
}
callDataOut(line, fromParser);
out.sendLine(line, priority);
final String[] newLine = tokeniseLine(line);
if ("away".equalsIgnoreCase(newLine[0]) && newLine.length > 1) {
myself.setAwayReason(newLine[newLine.length - 1]);
} else if ("mode".equalsIgnoreCase(newLine[0]) && newLine.length == 3) {
final IRCChannelInfo channel = getChannel(newLine[1]);
if (channel != null) {
// This makes sure we don't add the same item to the LMQ twice,
// even if its requested twice, as the ircd will only reply once
final Queue<Character> foundModes = new LinkedList<>();
final Queue<Character> listModeQueue = channel.getListModeQueue();
for (int i = 0; i < newLine[2].length(); ++i) {
final Character mode = newLine[2].charAt(i);
callDebugInfo(DEBUG_LMQ, "Intercepted mode request for " + channel + " for mode " + mode);
if (chanModesOther.containsKey(mode) && chanModesOther.get(mode) == MODE_LIST) {
if (foundModes.contains(mode)) {
callDebugInfo(DEBUG_LMQ, "Already added to LMQ");
} else {
listModeQueue.offer(mode);
foundModes.offer(mode);
callDebugInfo(DEBUG_LMQ, "Added to LMQ");
}
}
}
}
}
return true;
}
@Override
public String getNetworkName() {
return networkName;
}
@Override
public String getLastLine() {
return lastLine == null ? "" : lastLine.getLine();
}
@Override
public List<String> getServerInformationLines() {
synchronized (serverInformationLines) {
return new LinkedList<>(serverInformationLines);
}
}
/**
* Process a line and call relevant methods for handling.
*
* @param line Line read from the IRC server
*/
@SuppressWarnings("fallthrough")
protected void processLine(final ReadLine line) {
callDataIn(line.getLine());
final String[] token = line.getTokens();
LocalDateTime lineTS = LocalDateTime.now();
if (line.getTags().containsKey("tsirc date")) {
try {
final long ts = Long.parseLong(line.getTags().get("tsirc date")) - tsdiff;
lineTS = LocalDateTime.ofEpochSecond(ts / 1000L, (int) (ts % 1000L), ZoneOffset.UTC);
} catch (final NumberFormatException nfe) { /* Do nothing. */ }
} else if (line.getTags().containsKey("time")) {
try {
lineTS = LocalDateTime.parse(line.getTags().get("time"),
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
} catch (final DateTimeParseException pe) { /* Do nothing. */ }
}
setPingNeeded(false);
if (token.length < 2) {
return;
}
try {
final String sParam = token[1];
if ("PING".equalsIgnoreCase(token[0]) || "PING".equalsIgnoreCase(token[1])) {
sendString("PONG :" + sParam, QueuePriority.HIGH);
} else if ("PONG".equalsIgnoreCase(token[0]) || "PONG".equalsIgnoreCase(token[1])) {
if (!lastPingValue.isEmpty() && lastPingValue.equals(token[token.length - 1])) {
lastPingValue = "";
serverLag = System.currentTimeMillis() - pingTime;
callPingSuccess();
}
} else if ("ERROR".equalsIgnoreCase(token[0])) {
final StringBuilder errorMessage = new StringBuilder();
for (int i = 1; i < token.length; ++i) {
errorMessage.append(token[i]);
}
callServerError(errorMessage.toString());
} else if ("TSIRC".equalsIgnoreCase(token[1]) && token.length > 3) {
if ("1".equals(token[2])) {
try {
final long ts = Long.parseLong(token[3]);
tsdiff = ts - System.currentTimeMillis();
} catch (final NumberFormatException nfe) { /* Do nothing. */ }
}
} else {
int nParam;
if (got001) {
// Freenode sends a random notice in a stupid place, others might do aswell
// These shouldn't cause post005 to be fired, so handle them here.
if ("NOTICE".equalsIgnoreCase(token[0]) ||
token.length > 2 && "NOTICE".equalsIgnoreCase(token[2])) {
try {
myProcessingManager.process(lineTS, "Notice Auth", token);
} catch (ProcessorNotFoundException e) {
}
return;
}
if (!post005) {
try {
nParam = Integer.parseInt(token[1]);
} catch (NumberFormatException e) {
nParam = -1;
}
if (nParam < 0 || nParam > 5) {
callPost005();
} else {
// Store 001 - 005 for informational purposes.
synchronized (serverInformationLines) {
serverInformationLines.add(line.getLine());
}
}
}
// After 001 we potentially care about everything!
try {
myProcessingManager.process(lineTS, sParam, token);
} catch (ProcessorNotFoundException e) {
}
} else {
// Before 001 we don't care about much.
try {
nParam = Integer.parseInt(token[1]);
} catch (NumberFormatException e) {
nParam = -1;
}
switch (nParam) {
case 1: // 001 - Welcome to IRC
synchronized (serverInformationLines) {
serverInformationLines.add(line.getLine());
}
// Fallthrough
case IrcConstants.NUMERIC_ERROR_PASSWORD_MISMATCH:
case IrcConstants.NUMERIC_ERROR_NICKNAME_IN_USE:
try {
myProcessingManager.process(sParam, token);
} catch (ProcessorNotFoundException e) {
}
break;
default: // Unknown - Send to Notice Auth
// Some networks send a CTCP during the auth process, handle it
if (token.length > 3 && !token[3].isEmpty() && token[3].charAt(0) == (char) 1 && token[3].charAt(token[3].length() - 1) == (char) 1) {
try {
myProcessingManager.process(lineTS, sParam, token);
} catch (ProcessorNotFoundException e) {
}
break;
}
// Some networks may send a NICK message if you nick change before 001
// Eat it up so that it isn't treated as a notice auth.
if ("NICK".equalsIgnoreCase(token[1])) {
break;
}
// CAP also happens here, so try that.
if ("CAP".equalsIgnoreCase(token[1])) {
myProcessingManager.process(lineTS, sParam, token);
break;
}
// Otherwise, send to Notice Auth
try {
myProcessingManager.process(lineTS, "Notice Auth", token);
} catch (ProcessorNotFoundException e) {
}
break;
}
}
}
} catch (Exception e) {
final ParserError ei = new ParserError(ParserError.ERROR_FATAL, "Fatal Exception in Parser.", getLastLine());
ei.setException(e);
callErrorInfo(ei);
}
}
/** The IRCStringConverter for this parser */
private IRCStringConverter stringConverter;
@Override
public IRCStringConverter getStringConverter() {
if (stringConverter == null) {
stringConverter = new IRCStringConverter(IRCEncoding.RFC1459);
}
return stringConverter;
}
/**
* Sets the encoding that this parser's string converter should use.
*
* @param encoding The encoding to use
*/
public void setEncoding(final IRCEncoding encoding) {
stringConverter = new IRCStringConverter(encoding);
}
/**
* Check the state of the requested capability.
*
* @param capability The capability to check the state of.
* @return State of the requested capability.
*/
public CapabilityState getCapabilityState(final String capability) {
synchronized (capabilities) {
if (capabilities.containsKey(capability.toLowerCase())) {
return capabilities.get(capability.toLowerCase());
} else {
return CapabilityState.INVALID;
}
}
}
/**
* Set the state of the requested capability.
*
* @param capability Requested capability
* @param state State to set for capability
*/
public void setCapabilityState(final String capability, final CapabilityState state) {
synchronized (capabilities) {
if (capabilities.containsKey(capability.toLowerCase())) {
capabilities.put(capability.toLowerCase(), state);
}
}
}
/**
* Add the given capability as a supported capability by the server.
*
* @param capability Requested capability
*/
public void addCapability(final String capability) {
synchronized (capabilities) {
capabilities.put(capability.toLowerCase(), CapabilityState.DISABLED);
}
}
/**
* Get the server capabilities and their current state.
*
* @return Server capabilities and their current state.
*/
public Map<String, CapabilityState> getCapabilities() {
synchronized (capabilities) {
return new HashMap<>(capabilities);
}
}
/**
* Process CHANMODES from 005.
*/
public void parseChanModes() {
final StringBuilder sDefaultModes = new StringBuilder("b,k,l,");
String modeStr;
if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_CHANNEL_MODES)) {
if (getServerType() == ServerType.DANCER) {
sDefaultModes.insert(0, "dqeI");
} else if (getServerType() == ServerType.AUSTIRC) {
sDefaultModes.insert(0, 'e');
}
modeStr = h005Info.get(IrcConstants.ISUPPORT_USER_CHANNEL_MODES);
for (int i = 0; i < modeStr.length(); ++i) {
final char mode = modeStr.charAt(i);
if (!prefixModes.isPrefixMode(mode)
&& sDefaultModes.indexOf(Character.toString(mode)) < 0) {
sDefaultModes.append(mode);
}
}
} else {
sDefaultModes.append("imnpstrc");
}
if (h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_MODES)) {
modeStr = h005Info.get(IrcConstants.ISUPPORT_CHANNEL_MODES);
} else {
modeStr = sDefaultModes.toString();
h005Info.put(IrcConstants.ISUPPORT_CHANNEL_MODES, modeStr);
}
String[] bits = modeStr.split(",", 5);
if (bits.length < 4) {
modeStr = sDefaultModes.toString();
callErrorInfo(new ParserError(ParserError.ERROR_ERROR, "CHANMODES String not valid. " +
"Using default string of \"" + modeStr + '"', getLastLine()));
h005Info.put(IrcConstants.ISUPPORT_CHANNEL_MODES, modeStr);
bits = modeStr.split(",", 5);
}
// resetState
chanModesOther.clear();
// List modes.
for (int i = 0; i < bits[0].length(); ++i) {
final Character cMode = bits[0].charAt(i);
callDebugInfo(DEBUG_INFO, "Found List Mode: %c", cMode);
if (!chanModesOther.containsKey(cMode)) {
chanModesOther.put(cMode, MODE_LIST);
}
}
// Param for Set and Unset.
final Byte nBoth = MODE_SET + MODE_UNSET;
for (int i = 0; i < bits[1].length(); ++i) {
final Character cMode = bits[1].charAt(i);
callDebugInfo(DEBUG_INFO, "Found Set/Unset Mode: %c", cMode);
if (!chanModesOther.containsKey(cMode)) {
chanModesOther.put(cMode, nBoth);
}
}
// Param just for Set
for (int i = 0; i < bits[2].length(); ++i) {
final Character cMode = bits[2].charAt(i);
callDebugInfo(DEBUG_INFO, "Found Set Only Mode: %c", cMode);
if (!chanModesOther.containsKey(cMode)) {
chanModesOther.put(cMode, MODE_SET);
}
}
// Boolean Mode
chanModesBool.set(bits[3]);
callDebugInfo(DEBUG_INFO, "Found boolean modes: %s", bits[3]);
}
@Override
public String getChannelUserModes() {
return prefixModes.getPrefixes();
}
@Override
public String getBooleanChannelModes() {
return chanModesBool.getModes();
}
@Override
public String getListChannelModes() {
return getOtherModeString(MODE_LIST);
}
@Override
public String getParameterChannelModes() {
return getOtherModeString(MODE_SET);
}
@Override
public String getDoubleParameterChannelModes() {
return getOtherModeString((byte) (MODE_SET + MODE_UNSET));
}
@Override
public String getChannelPrefixes() {
return chanPrefix;
}
/**
* Get modes from hChanModesOther that have a specific value.
* Modes are returned in alphabetical order
*
* @param value Value mode must have to be included
* @return All the currently known Set-Unset modes
*/
protected String getOtherModeString(final byte value) {
final char[] modes = new char[chanModesOther.size()];
int i = 0;
for (char cTemp : chanModesOther.keySet()) {
final Byte nTemp = chanModesOther.get(cTemp);
if (nTemp == value) {
modes[i] = cTemp;
i++;
}
}
// Alphabetically sort the array
Arrays.sort(modes);
return new String(modes).trim();
}
@Override
public String getUserModes() {
if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_MODES)) {
return h005Info.get(IrcConstants.ISUPPORT_USER_MODES);
} else {
return "";
}
}
/**
* Process USERMODES from 004.
*/
public void parseUserModes() {
final String modeStr;
if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_MODES)) {
modeStr = h005Info.get(IrcConstants.ISUPPORT_USER_MODES);
} else {
final String sDefaultModes = "nwdoi";
modeStr = sDefaultModes;
h005Info.put(IrcConstants.ISUPPORT_USER_MODES, sDefaultModes);
}
userModes.set(modeStr);
}
/**
* Resets the channel prefix property to the default, RFC specified value.
*/
public void resetChanPrefix() {
chanPrefix = DEFAULT_CHAN_PREFIX;
}
/**
* Sets the set of possible channel prefixes to those in the given value.
*
* @param value The new set of channel prefixes.
*/
public void setChanPrefix(final String value) {
chanPrefix = value;
}
/**
* Process PREFIX from 005.
*/
public void parsePrefixModes() {
final String sDefaultModes = "(ohv)@%+";
String modeStr;
if (h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES)) {
modeStr = h005Info.get(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES);
} else {
modeStr = sDefaultModes;
}
if ("(".equals(modeStr.substring(0, 1))) {
modeStr = modeStr.substring(1);
} else {
modeStr = sDefaultModes.substring(1);
h005Info.put(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES, sDefaultModes);
}
int closingIndex = modeStr.indexOf(')');
if (closingIndex * 2 + 1 != modeStr.length()) {
callErrorInfo(new ParserError(ParserError.ERROR_ERROR,
"PREFIX String not valid. Using default string of \"" + modeStr +
'"', getLastLine()));
h005Info.put(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES, sDefaultModes);
modeStr = sDefaultModes.substring(1);
closingIndex = modeStr.indexOf(')');
}
// The modes passed from the server are in descending order of importance, we want to
// store them in ascending, so reverse them:
final String reversedModes = new StringBuilder(modeStr).reverse().toString();
prefixModes.setModes(reversedModes.substring(closingIndex + 1),
reversedModes.substring(0, closingIndex));
}
@Override
public void joinChannels(final ChannelJoinRequest... channels) {
// We store a map from key->channels to allow intelligent joining of
// channels using as few JOIN commands as needed.
final Map<String, StringBuffer> joinMap = new HashMap<>();
for (ChannelJoinRequest channel : channels) {
// Make sure we have a list to put stuff in.
StringBuffer list = joinMap.get(channel.getPassword());
if (list == null) {
list = new StringBuffer();
joinMap.put(channel.getPassword(), list);
}
// Add the channel to the list. If the name is invalid and
// autoprefix is off we will just skip this channel.
if (!channel.getName().isEmpty()) {
if (list.length() > 0) {
list.append(',');
}
if (!isValidChannelName(channel.getName())) {
if (chanPrefix.isEmpty()) {
// TODO: This is wrong - empty chan prefix means the
// IRCd supports no channels.
list.append('
} else {
list.append(chanPrefix.charAt(0));
}
}
list.append(channel.getName());
}
}
for (Map.Entry<String, StringBuffer> entrySet : joinMap.entrySet()) {
final String thisKey = entrySet.getKey();
final String channelString = entrySet.getValue().toString();
if (!channelString.isEmpty()) {
if (thisKey == null || thisKey.isEmpty()) {
sendString("JOIN " + channelString);
} else {
sendString("JOIN " + channelString + ' ' + thisKey);
}
}
}
}
/**
* Leave a Channel.
*
* @param channel Name of channel to part
* @param reason Reason for leaving (Nothing sent if sReason is "")
*/
public void partChannel(final String channel, final String reason) {
if (getChannel(channel) == null) {
return;
}
sendString("PART " + channel, reason);
}
/**
* Set Nickname.
*
* @param nickname New nickname wanted.
*/
public void setNickname(final String nickname) {
if (getSocketState() == SocketState.OPEN) {
if (!myself.isFake() && myself.getRealNickname().equals(nickname)) {
return;
}
sendString("NICK " + nickname);
} else {
me.setNickname(nickname);
}
thinkNickname = nickname;
}
@Override
public int getMaxLength(final String type, final String target) {
// If my host is "nick!user@host" and we are sending "#Channel"
// a "PRIVMSG" this will find the length of ":nick!user@host PRIVMSG #channel :"
// and subtract it from the MAX_LINELENGTH. This should be sufficient in most cases.
// Lint = the 2 ":" at the start and end and the 3 separating " "s
int length = 0;
if (type != null) {
length += type.length();
}
if (target != null) {
length += target.length();
}
return getMaxLength(length);
}
/**
* Get the max length a message can be.
*
* @param length Length of stuff. (Ie "PRIVMSG"+"#Channel")
* @return Max Length message should be.
*/
public int getMaxLength(final int length) {
final int lineLint = 5;
if (myself.isFake()) {
callErrorInfo(new ParserError(ParserError.ERROR_ERROR + ParserError.ERROR_USER, "getMaxLength() called, but I don't know who I am?", getLastLine()));
return MAX_LINELENGTH - length - lineLint;
} else {
return MAX_LINELENGTH - myself.toString().length() - length - lineLint;
}
}
@Override
public int getMaxListModes(final char mode) {
// MAXLIST=bdeI:50
// MAXLIST=b:60,e:60,I:60
// MAXBANS=30
callDebugInfo(DEBUG_INFO, "Looking for maxlistmodes for: " + mode);
// Try in MAXLIST
int result = -2;
if (h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_LIST_MODES) != null) {
if (h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_BANS) == null) {
result = 0;
}
final String maxlist = h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_LIST_MODES);
callDebugInfo(DEBUG_INFO, "Found maxlist (" + maxlist + ')');
final String[] bits = maxlist.split(",");
for (String bit : bits) {
final String[] parts = bit.split(":", 2);
callDebugInfo(DEBUG_INFO, "Bit: " + bit + " | parts.length = " + parts.length + " ("
+ parts[0] + " -> " + parts[0].indexOf(mode) + ')');
if (parts.length == 2 && parts[0].indexOf(mode) > -1) {
callDebugInfo(DEBUG_INFO, "parts[0] = '" + parts[0] + "' | parts[1] = '"
+ parts[1] + '\'');
try {
result = Integer.parseInt(parts[1]);
break;
} catch (NumberFormatException nfe) {
result = -1;
}
}
}
}
// If not in max list, try MAXBANS
if (result == -2 && h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_BANS) != null) {
callDebugInfo(DEBUG_INFO, "Trying max bans");
try {
result = Integer.parseInt(h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_BANS));
} catch (NumberFormatException nfe) {
result = -1;
}
} else if (result == -2 && getServerType() == ServerType.WEIRCD) {
result = 50;
} else if (result == -2 && getServerType() == ServerType.OTHERNET) {
result = 30;
} else if (result == -2) {
result = -1;
callDebugInfo(DEBUG_INFO, "Failed");
callErrorInfo(new ParserError(ParserError.ERROR_ERROR + ParserError.ERROR_USER, "Unable to discover max list modes.", getLastLine()));
}
callDebugInfo(DEBUG_INFO, "Result: " + result);
return result;
}
@Override
public void sendMessage(final String target, final String message) {
if (target == null || message == null) {
return;
}
if (target.isEmpty()) {
return;
}
sendString("PRIVMSG " + target, message);
}
@Override
public void sendNotice(final String target, final String message) {
if (target == null || message == null) {
return;
}
if (target.isEmpty()) {
return;
}
sendString("NOTICE " + target, message);
}
@Override
public void sendAction(final String target, final String message) {
sendCTCP(target, "ACTION", message);
}
@Override
public void sendCTCP(final String target, final String type, final String message) {
if (target == null || message == null) {
return;
}
if (target.isEmpty() || type.isEmpty()) {
return;
}
final char char1 = (char) 1;
sendString("PRIVMSG " + target, char1 + type.toUpperCase() + ' ' + message + char1);
}
@Override
public void sendCTCPReply(final String target, final String type, final String message) {
if (target == null || message == null) {
return;
}
if (target.isEmpty() || type.isEmpty()) {
return;
}
final char char1 = (char) 1;
sendString("NOTICE " + target, char1 + type.toUpperCase() + ' ' + message + char1);
}
@Override
public void requestGroupList(final String searchTerms) {
sendString("LIST", searchTerms);
}
@Override
public void quit(final String reason) {
sendString("QUIT", reason);
}
@Override
public void disconnect(final String message) {
super.disconnect(message);
if (currentSocketState == SocketState.OPENING || currentSocketState == SocketState.OPEN) {
currentSocketState = SocketState.CLOSING;
if (got001) {
quit(message);
}
}
try {
// SSLSockets try to close nicely and read data from the socket,
// which seems to hang indefinitely in some circumstances. We don't
// like indefinite hangs, so just close the underlying socket
// direct.
if (rawSocket != null) {
rawSocket.close();
}
} catch (IOException e) {
/* Do Nothing */
} finally {
if (currentSocketState != SocketState.CLOSED) {
currentSocketState = SocketState.CLOSED;
callSocketClosed();
}
resetState();
}
}
/** {@inheritDoc}
*
* - Before channel prefixes are known (005/noMOTD/MOTDEnd), this checks
* that the first character is either #, &, ! or +
* - Assumes that any channel that is already known is valid, even if
* 005 disagrees.
*/
@Override
public boolean isValidChannelName(final String name) {
// Check sChannelName is not empty or null
if (name == null || name.isEmpty()) {
return false;
}
// Check its not ourself (PM recieved before 005)
if (getStringConverter().equalsIgnoreCase(getMyNickname(), name)) {
return false;
}
// Check if we are already on this channel
if (getChannel(name) != null) {
return true;
}
// Otherwise return true if:
// Channel equals "0"
// first character of the channel name is a valid channel prefix.
return chanPrefix.indexOf(name.charAt(0)) >= 0 || "0".equals(name);
}
@Override
public boolean isUserSettable(final char mode) {
final String validmodes;
if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_CHANNEL_MODES)) {
validmodes = h005Info.get(IrcConstants.ISUPPORT_USER_CHANNEL_MODES);
} else {
validmodes = "bklimnpstrc";
}
return validmodes.matches(".*" + mode + ".*");
}
/**
* Get the 005 info.
*
* @return 005Info hashtable.
*/
public Map<String, String> get005() {
return Collections.unmodifiableMap(h005Info);
}
/**
* Get the ServerType for this IRCD.
*
* @return The ServerType for this IRCD.
*/
public ServerType getServerType() {
return ServerType.findServerType(h005Info.get("004IRCD"), networkName, h005Info.get("003IRCD"), h005Info.get("002IRCD"));
}
@Override
public String getServerSoftware() {
final String version = h005Info.get("004IRCD");
return version == null ? "" : version;
}
@Override
public String getServerSoftwareType() {
return getServerType().getType();
}
/**
* Get the value of checkServerPing.
*
* @return value of checkServerPing.
* @see #setCheckServerPing
*/
public boolean getCheckServerPing() {
return checkServerPing;
}
/**
* Set the value of checkServerPing.
*
* @param newValue New value to use.
* @see #setCheckServerPing
*/
public void setCheckServerPing(final boolean newValue) {
checkServerPing = newValue;
if (checkServerPing) {
startPingTimer();
} else {
stopPingTimer();
}
}
@Override
public void setEncoder(final Encoder encoder) {
this.encoder = encoder;
}
@Override
public void setPingTimerInterval(final long newValue) {
super.setPingTimerInterval(newValue);
startPingTimer();
}
/**
* Start the pingTimer.
*/
public void startPingTimer() {
pingTimerSem.acquireUninterruptibly();
try {
setPingNeeded(false);
if (pingTimer != null) {
pingTimer.cancel();
}
pingTimer = new Timer("IRCParser pingTimer");
pingTimer.schedule(new PingTimer(this, pingTimer), 0, getPingTimerInterval());
pingCountDown = 1;
} finally {
pingTimerSem.release();
}
}
/**
* Stop the pingTimer.
*/
protected void stopPingTimer() {
pingTimerSem.acquireUninterruptibly();
if (pingTimer != null) {
pingTimer.cancel();
pingTimer = null;
}
pingTimerSem.release();
}
/**
* This is called when the ping Timer has been executed.
* As the timer is restarted on every incomming message, this will only be
* called when there has been no incomming line for 10 seconds.
*
* @param timer The timer that called this.
*/
protected void pingTimerTask(final Timer timer) {
// If user no longer wants server ping to be checked, or the socket is
// closed then cancel the time and do nothing else.
if (!getCheckServerPing() || getSocketState() != SocketState.OPEN) {
pingTimerSem.acquireUninterruptibly();
if (pingTimer != null && pingTimer.equals(timer)) {
pingTimer.cancel();
}
pingTimerSem.release();
return;
}
if (getPingNeeded()) {
callPingFailed();
} else {
--pingCountDown;
if (pingCountDown < 1) {
pingTime = System.currentTimeMillis();
setPingNeeded(true);
pingCountDown = getPingTimerFraction();
lastPingValue = String.valueOf(System.currentTimeMillis());
if (sendString("PING " + lastPingValue, QueuePriority.HIGH)) {
callPingSent();
}
}
}
}
@Override
public long getServerLatency() {
return serverLag;
}
/**
* Updates the name of the server that this parser is connected to.
*
* @param serverName The discovered server name
*/
public void updateServerName(final String serverName) {
setServerName(serverName);
}
/**
* Get the current server lag.
*
* @param actualTime if True the value returned will be the actual time the ping was sent
* else it will be the amount of time sinse the last ping was sent.
* @return Time last ping was sent
*/
public long getPingTime(final boolean actualTime) {
if (actualTime) {
return pingTime;
} else {
return System.currentTimeMillis() - pingTime;
}
}
@Override
public long getPingTime() {
return getPingTime(false);
}
/**
* Set if a ping is needed or not.
*
* @param newStatus new value to set pingNeeded to.
*/
private void setPingNeeded(final boolean newStatus) {
pingNeeded.set(newStatus);
}
/**
* Get if a ping is needed or not.
*
* @return value of pingNeeded.
*/
boolean getPingNeeded() {
return pingNeeded.get();
}
@Override
public IRCClientInfo getLocalClient() {
return myself;
}
/**
* Get the current nickname.
* After 001 this returns the exact same as getLocalClient().getRealNickname();
* Before 001 it returns the nickname that the parser Thinks it has.
*
* @return Current nickname.
*/
public String getMyNickname() {
if (myself.isFake()) {
return thinkNickname;
} else {
return myself.getRealNickname();
}
}
/**
* Retrieves the local user information that this parser was configured
* with.
*
* @return This parser's local user configuration
*/
public MyInfo getMyInfo() {
return me;
}
/**
* Get the current username (Specified in MyInfo on construction).
* Get the username given in MyInfo
*
* @return My username.
*/
public String getMyUsername() {
return me.getUsername();
}
/**
* Add a client to the ClientList.
*
* @param client Client to add
*/
public void addClient(final IRCClientInfo client) {
clientList.put(getStringConverter().toLowerCase(client.getRealNickname()), client);
}
/**
* Remove a client from the ClientList.
* This WILL NOT allow cMyself to be removed from the list.
*
* @param client Client to remove
*/
public void removeClient(final IRCClientInfo client) {
if (client != myself) {
forceRemoveClient(client);
}
}
/**
* Remove a client from the ClientList.
* This WILL allow cMyself to be removed from the list
*
* @param client Client to remove
*/
public void forceRemoveClient(final IRCClientInfo client) {
clientList.remove(getStringConverter().toLowerCase(client.getRealNickname()));
}
/**
* Get the number of known clients.
*
* @return Count of known clients
*/
public int knownClients() {
return clientList.size();
}
/**
* Get the known clients as a collection.
*
* @return Known clients as a collection
*/
public Collection<IRCClientInfo> getClients() {
return clientList.values();
}
/**
* Clear the client list.
*/
public void clearClients() {
clientList.clear();
addClient(getLocalClient());
}
/**
* Add a channel to the ChannelList.
*
* @param channel Channel to add
*/
public void addChannel(final IRCChannelInfo channel) {
synchronized (channelList) {
channelList.put(getStringConverter().toLowerCase(channel.getName()), channel);
}
}
/**
* Remove a channel from the ChannelList.
*
* @param channel Channel to remove
*/
public void removeChannel(final ChannelInfo channel) {
synchronized (channelList) {
channelList.remove(getStringConverter().toLowerCase(channel.getName()));
}
}
/**
* Get the number of known channel.
*
* @return Count of known channel
*/
public int knownChannels() {
synchronized (channelList) {
return channelList.size();
}
}
@Override
public Collection<IRCChannelInfo> getChannels() {
synchronized (channelList) {
return channelList.values();
}
}
/**
* Clear the channel list.
*/
public void clearChannels() {
synchronized (channelList) {
channelList.clear();
}
}
@Override
public String[] parseHostmask(final String hostmask) {
return IRCClientInfo.parseHostFull(hostmask);
}
@Override
public int getMaxTopicLength() {
if (h005Info.containsKey(IrcConstants.ISUPPORT_TOPIC_LENGTH)) {
try {
return Integer.parseInt(h005Info.get(IrcConstants.ISUPPORT_TOPIC_LENGTH));
} catch (NumberFormatException ex) {
// Do nothing
}
}
return 0;
}
@Override
public int getMaxLength() {
return MAX_LINELENGTH;
}
@Override
public void setCompositionState(final String host, final CompositionState state) {
// Do nothing
}
@Override
protected void handleSocketDebug(final String message) {
super.handleSocketDebug(message);
callDebugInfo(DEBUG_SOCKET, message);
}
}
|
package algorithms.imageProcessing.matching;
import algorithms.compGeometry.PerimeterFinder2;
import algorithms.connected.ConnectedPointsFinder;
import algorithms.FixedSizeSortedVector;
import algorithms.imageProcessing.GreyscaleImage;
import algorithms.imageProcessing.Image;
import algorithms.imageProcessing.ImageIOHelper;
import algorithms.imageProcessing.ImageProcessor;
import algorithms.imageProcessing.features.CorrespondenceList;
import algorithms.imageProcessing.features.HCPT;
import algorithms.imageProcessing.features.HGS;
import algorithms.imageProcessing.features.HOGs;
import algorithms.imageProcessing.features.ObjectMatcher.Settings;
import algorithms.imageProcessing.features.mser.Canonicalizer;
import algorithms.imageProcessing.features.mser.Canonicalizer.CRegion;
import algorithms.imageProcessing.features.mser.Canonicalizer.RegionPoints;
import algorithms.imageProcessing.features.mser.Region;
import algorithms.imageProcessing.util.PairIntWithIndex;
import algorithms.misc.MiscDebug;
import algorithms.misc.MiscMath;
import algorithms.util.PairInt;
import algorithms.util.PairIntArray;
import algorithms.util.PixelHelper;
import algorithms.util.QuadInt;
import com.climbwithyourfeet.clustering.ClusterFinder;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.iterator.TIntObjectIterator;
import gnu.trove.map.TIntIntMap;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.TLongIntMap;
import gnu.trove.map.hash.TIntIntHashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.map.hash.TLongIntHashMap;
import gnu.trove.set.TIntSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
*
* @author nichole
*/
public class MSERMatcher {
private boolean debug = false;
private int N_PIX_PER_CELL_DIM = 3;
private int N_CELLS_PER_BLOCK_DIM = 3;
public void setToDebug() {
debug = true;
}
private TIntObjectMap<CRegion> getOrCreate(
TIntObjectMap<TIntObjectMap<CRegion>> csrs,
int imgIdx, GreyscaleImage rgb, float scale) {
TIntObjectMap<CRegion> csrMap = csrs.get(imgIdx);
if (csrMap != null) {
return csrMap;
}
csrMap = new TIntObjectHashMap<CRegion>();
csrs.put(imgIdx, csrMap);
TIntObjectMap<CRegion> csrMap0 = csrs.get(0);
int w = rgb.getWidth();
int h = rgb.getHeight();
TIntObjectIterator<CRegion> iter = csrMap0.iterator();
for (int i = 0; i < csrMap0.size(); ++i) {
iter.advance();
int idx = iter.key();
CRegion csr = iter.value();
if (csr.offsetsToOrigCoords.size() < 9) {
continue;
}
// these are in scale of individual octave (not full reference frame)
Set<PairInt> scaledSet = extractScaledPts(csr, w, h, scale);
if (scaledSet.size() < 9) {
continue;
}
PairIntArray xy = new PairIntArray();
Region r = new Region();
for (PairInt pl : scaledSet) {
r.accumulate(pl.getX(), pl.getY());
xy.add(pl.getX(), pl.getY());
}
int[] xyCen = new int[2];
r.calculateXYCentroid(xyCen, w, h);
int x = xyCen[0];
int y = xyCen[1];
assert(x >= 0 && x < w);
assert(y >= 0 && y < h);
double[] m = r.calcParamTransCoeff();
double angle = Math.atan(m[0]/m[2]);
if (angle < 0) {
angle += Math.PI;
}
double major = 2. * m[4];
double minor = 2. * m[5];
double ecc = Math.sqrt(major * major - minor * minor)/major;
assert(!Double.isNaN(ecc));
Map<PairInt, PairInt> offsetMap = Canonicalizer.createOffsetToOrigMap(
x, y, xy, w, h, angle);
double autocorrel = Canonicalizer.calcAutoCorrel(rgb, x, y, offsetMap);
CRegion csRegion = new CRegion();
csRegion.ellipseParams.orientation = angle;
csRegion.ellipseParams.eccentricity = ecc;
csRegion.ellipseParams.major = major;
csRegion.ellipseParams.minor = minor;
csRegion.ellipseParams.xC = x;
csRegion.ellipseParams.yC = y;
csRegion.offsetsToOrigCoords = offsetMap;
csRegion.autocorrel = Math.sqrt(autocorrel)/255.;
csRegion.labels.addAll(csr.labels);
csRegion.dataIdx = idx;
csrMap.put(idx, csRegion);
}
return csrMap;
}
private GreyscaleImage combineImages(List<GreyscaleImage> rgb) {
GreyscaleImage r = rgb.get(0);
GreyscaleImage g = rgb.get(1);
GreyscaleImage b = rgb.get(2);
if (r.getWidth() != g.getWidth() || r.getWidth() != b.getWidth() ||
r.getHeight() != g.getHeight() || r.getHeight() != b.getHeight()) {
throw new IllegalArgumentException("r, g, and b must have same"
+ " width and height");
}
int w = r.getWidth();
int h = r.getHeight();
GreyscaleImage comb = new GreyscaleImage(w, h, r.getType());
for (int i = 0; i < r.getNPixels(); ++i) {
float v0 = r.getValue(i);
float v1 = g.getValue(i);
float v2 = b.getValue(i);
float avg = (v0 + v1 + v2)/3.f;
comb.setValue(i, Math.round(avg));
}
return comb;
}
private Set<PairInt> extractScaledPts(CRegion csr, int w, int h,
float scale) {
Set<PairInt> scaledSet = new HashSet<PairInt>();
for (Entry<PairInt, PairInt> entry : csr.offsetsToOrigCoords.entrySet()) {
PairInt p = entry.getValue();
int xScaled = Math.round((float) p.getX() / scale);
int yScaled = Math.round((float) p.getY() / scale);
if (xScaled == -1) {
xScaled = 0;
}
if (yScaled == -1) {
yScaled = 0;
}
if (xScaled == w) {
xScaled = w - 1;
}
if (yScaled == h) {
yScaled = h - 1;
}
PairInt pOrigScaled = new PairInt(xScaled, yScaled);
scaledSet.add(pOrigScaled);
}
return scaledSet;
}
private Set<PairInt> extractScaledPts(RegionPoints csr, int w, int h,
float scale) {
Set<PairInt> scaledSet = new HashSet<PairInt>();
for (PairInt p : csr.points) {
int xScaled = Math.round((float) p.getX() / scale);
int yScaled = Math.round((float) p.getY() / scale);
if (xScaled == -1) {
xScaled = 0;
}
if (yScaled == -1) {
yScaled = 0;
}
if (xScaled == w) {
xScaled = w - 1;
}
if (yScaled == h) {
yScaled = h - 1;
}
PairInt pOrigScaled = new PairInt(xScaled, yScaled);
scaledSet.add(pOrigScaled);
}
return scaledSet;
}
private TIntIntMap calculateLabelSizes(List<Set<PairInt>> sets) {
TIntIntMap map = new TIntIntHashMap();
for (int i = 0; i < sets.size(); ++i) {
int sz = MiscMath.calculateObjectSize(sets.get(i));
map.put(i, sz);
}
return map;
}
private int calculateObjectSize(Collection<PairInt> values) {
int[] minMaxXY = MiscMath.findMinMaxXY(values);
int diffX = minMaxXY[1] - minMaxXY[0];
int diffY = minMaxXY[3] - minMaxXY[2];
double xy = Math.sqrt(diffX * diffX + diffY * diffY);
return (int)Math.round(xy);
}
private int calculateObjectSizeByAvgDist(int x, int y,
Collection<PairInt> values) {
int sumD = 0;
for (PairInt p : values) {
int diffX = p.getX() - x;
int diffY = p.getY() - y;
sumD += (diffX * diffX + diffY * diffY);
}
sumD = (int)Math.ceil(Math.sqrt((double)sumD/(double)values.size()));
return sumD;
}
private void debugPrint3(List<List<Obj>> list, GreyscaleImage img0,
GreyscaleImage img1, float scale0, float scale1, String lbl) {
for (int i = 0; i < list.size(); ++i) {
List<Obj> objs = list.get(i);
Image im0 = img0.copyToColorGreyscale();
Image im1 = img1.copyToColorGreyscale();
for (int j = 0; j < objs.size(); ++j) {
int[] clr = ImageIOHelper.getNextRGB(j);
Obj obj = objs.get(j);
obj.cr0.drawEachPixel(im0, 0, clr[0], clr[1], clr[2]);
obj.cr1.drawEachPixel(im1, 0, clr[0], clr[1], clr[2]);
}
MiscDebug.writeImage(im0, lbl + "__0__" + i);
MiscDebug.writeImage(im1, lbl + "__1__" + i);
}
}
//chordDiffSum, nMatches, p.n
private double[] partialShapeCost(Obj obj,
float scale0, float scale1,
List<Set<PairInt>> labeledSets0,
List<Set<PairInt>> labeledSets1,
GreyscaleImage gsI0, GreyscaleImage gsI1) {
// TODO: use caching if keep this method
Set<PairInt> set0 = new HashSet<PairInt>();
TIntIterator iter = obj.cr0.labels.iterator();
while (iter.hasNext()) {
int label = iter.next();
Set<PairInt> s0 = labeledSets0.get(label);
for (PairInt p : s0) {
int x = Math.round((float)p.getX() / scale0);
int y = Math.round((float)p.getY() / scale0);
set0.add(new PairInt(x, y));
}
}
set0 = reduceToContiguous(set0, gsI0.getWidth(), gsI0.getHeight());
Set<PairInt> set1 = new HashSet<PairInt>();
iter = obj.cr1.labels.iterator();
while (iter.hasNext()) {
int label = iter.next();
Set<PairInt> s0 = labeledSets1.get(label);
for (PairInt p : s0) {
int x = Math.round((float)p.getX() / scale1);
int y = Math.round((float)p.getY() / scale1);
set1.add(new PairInt(x, y));
}
}
set1 = reduceToContiguous(set1, gsI1.getWidth(), gsI1.getHeight());
PerimeterFinder2 finder = new PerimeterFinder2();
PairIntArray p = finder.extractOrderedBorder(set0);
PairIntArray q = finder.extractOrderedBorder(set1);
int dp = 1;
if (p.getN() > 500 || q.getN() > 500) {
int dn = Math.max(p.getN(), q.getN());
dp += Math.ceil((float)dn/500.f);
}
PartialShapeMatcher2 matcher = new PartialShapeMatcher2();
matcher.overrideSamplingDistance(dp);
matcher.setToUseEuclidean();
matcher.setToRemoveOutliers();
PartialShapeMatcher2.Result result = matcher.match(p, q);
double[] out = new double[] {
result.chordDiffSum, result.getNumberOfMatches(), p.getN()
};
return out;
}
private Set<PairInt> reduceToContiguous(Set<PairInt> set, int width,
int height) {
//TODO: convert user of this method to pixels indexes
ImageProcessor imageProcessor = new ImageProcessor();
TIntSet pixSet = imageProcessor.convertPointsToIndexes(set, width);
ConnectedPointsFinder finder = new ConnectedPointsFinder(width, height);
finder.setMinimumNumberInCluster(1);
finder.findConnectedPointGroups(pixSet);
if (finder.getNumberOfGroups() == 1) {
return new HashSet<PairInt>(set);
}
int maxIdx = -1;
int nMax = Integer.MIN_VALUE;
for (int i = 0; i < finder.getNumberOfGroups(); ++i) {
int n = finder.getNumberofGroupMembers(i);
if (n > nMax) {
nMax = n;
maxIdx = i;
}
}
return imageProcessor.convertIndexesToPoints(
finder.getXY(maxIdx), width);
}
//double[]{intersection, f0, f1, count};
private double[] sumHOGCost2(HOGs hogs0, CRegion cr0,
HOGs hogs1, CRegion cr1) {
int orientation0 = cr0.hogOrientation;
int orientation1 = cr1.hogOrientation;
Map<PairInt, PairInt> offsetMap1 = cr1.offsetsToOrigCoords;
double sum = 0;
int count = 0;
int[] h0 = new int[hogs0.getNumberOfBins()];
int[] h1 = new int[h0.length];
// key = transformed offsets, value = coords in image ref frame,
// so, can compare dataset0 and dataset1 points with same
// keys
for (Entry<PairInt, PairInt> entry0 : cr0.offsetsToOrigCoords.entrySet()) {
PairInt pOffset0 = entry0.getKey();
PairInt xy1 = offsetMap1.get(pOffset0);
if (xy1 == null) {
continue;
}
PairInt xy0 = entry0.getValue();
hogs0.extractBlock(xy0.getX(), xy0.getY(), h0);
hogs1.extractBlock(xy1.getX(), xy1.getY(), h1);
// 1.0 is perfect similarity
float intersection = hogs0.intersection(h0, orientation0,
h1, orientation1);
sum += (intersection * intersection);
count++;
}
if (count == 0) {
return null;
}
sum /= (double)count;
sum = Math.sqrt(sum);
double area1 = cr1.offsetsToOrigCoords.size();
double f1 = 1. - ((double) count / area1);
double area0 = cr0.offsetsToOrigCoords.size();
double f0 = 1. - ((double) count / area0);
return new double[]{sum, f0, f1, count};
}
//double[]{intersection, f0, f1, count};
private double[] sumHOGCost3(HOGs hogs0, CRegion cr0,
HOGs hogs1, CRegion cr1) {
int orientation0 = cr0.hogOrientation;
int orientation1 = cr1.hogOrientation;
Map<PairInt, PairInt> offsetMap1 = cr1.offsetsToOrigCoords;
double sum = 0;
double sumErrSq = 0;
int count = 0;
int[] h0 = new int[hogs0.getNumberOfBins()];
int[] h1 = new int[h0.length];
float[] diffAndErr;
//NOTE: the coordinate set block could be changed to not visit
// every point, but to instead use a spacing of the HOG cell length
// which is what Dala & Trigg recommend for their detector windows.
// key = transformed offsets, value = coords in image ref frame,
// so, can compare dataset0 and dataset1 points with same
// keys
for (Entry<PairInt, PairInt> entry0 : cr0.offsetsToOrigCoords.entrySet()) {
PairInt pOffset0 = entry0.getKey();
PairInt xy1 = offsetMap1.get(pOffset0);
if (xy1 == null) {
continue;
}
PairInt xy0 = entry0.getValue();
hogs0.extractBlock(xy0.getX(), xy0.getY(), h0);
hogs1.extractBlock(xy1.getX(), xy1.getY(), h1);
// 1.0 is perfect similarity
diffAndErr = hogs0.diff(h0, orientation0, h1, orientation1);
sum += diffAndErr[0];
sumErrSq += (diffAndErr[1] * diffAndErr[1]);
count++;
}
if (count == 0) {
return null;
}
sum /= (double)count;
sumErrSq /= (double)count;
sumErrSq = Math.sqrt(sumErrSq);
double area1 = cr1.offsetsToOrigCoords.size();
double f1 = 1. - ((double) count / area1);
double area0 = cr0.offsetsToOrigCoords.size();
double f0 = 1. - ((double) count / area0);
return new double[]{sum, f0, f1, count, sumErrSq};
}
private HOGs getOrCreate(TIntObjectMap<HOGs> hogsMap, GreyscaleImage gs,
int idx) {
HOGs hogs = hogsMap.get(idx);
if (hogs != null) {
return hogs;
}
hogs = new HOGs(gs, N_PIX_PER_CELL_DIM, N_CELLS_PER_BLOCK_DIM);
hogsMap.put(idx, hogs);
return hogs;
}
private HCPT getOrCreate2(TIntObjectMap<HCPT> hcptMap, GreyscaleImage pt,
int idx) {
HCPT hcpt = hcptMap.get(idx);
if (hcpt != null) {
return hcpt;
}
hcpt = new HCPT(pt, N_PIX_PER_CELL_DIM, N_CELLS_PER_BLOCK_DIM, 12);
hcptMap.put(idx, hcpt);
return hcpt;
}
private HGS getOrCreate3(TIntObjectMap<HGS> hgsMap, GreyscaleImage img,
int idx) {
HGS hgs = hgsMap.get(idx);
if (hgs != null) {
return hgs;
}
hgs = new HGS(img, N_PIX_PER_CELL_DIM, N_CELLS_PER_BLOCK_DIM, 12);
hgsMap.put(idx, hgs);
return hgs;
}
private void calculateDominantOrientations(
TIntObjectMap<RegionPoints> regionPoints, HOGs hogs) {
TIntObjectIterator<RegionPoints> iter = regionPoints.iterator();
for (int i = 0; i < regionPoints.size(); ++i) {
iter.advance();
RegionPoints r = iter.value();
TIntSet orientations = hogs.calculateDominantOrientations(r.points);
r.hogOrientations.addAll(orientations);
}
}
/* NOTE: recalculating this worsens the solutions.
Using the MSER originally determined ellipse parameters has better
results for the small number of tests here
private void recalcOrientationAndTrans(HOGs hogs,
TIntObjectMap<CRegion> regions, GreyscaleImage gsImg, float scale) {
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
TIntObjectIterator<CRegion> iter = regions.iterator();
for (int i = 0; i < regions.size(); ++i) {
iter.advance();
int rIdx = iter.key();
CRegion cr = iter.value();
int orientation = hogs.calculateDominantOrientation(
cr.offsetsToOrigCoords.values());
Collection<PairInt> xyp = cr.offsetsToOrigCoords.values();
PairIntArray xy = Misc.convertWithoutOrder(xyp);
PairInt xyCen = ch.calculateXYCentroids2(xyp);
cr.ellipseParams.orientation = Math.PI * orientation/180.;
cr.ellipseParams.xC = xyCen.getX();
cr.ellipseParams.yC = xyCen.getY();
Map<PairInt, PairInt> offsetToOrigMap =
Canonicalizer.createOffsetToOrigMap(
xyCen.getX(), xyCen.getY(),
xy, gsImg.getWidth(), gsImg.getHeight(), orientation);
cr.offsetsToOrigCoords = offsetToOrigMap;
}
}
*/
private class Obj implements Comparable<Obj>{
CRegion cr0;
CRegion cr1;
int imgIdx0;
int imgIdx1;
int nMatched;
double cost = Double.MAX_VALUE;
double[] costs;
double f;
// might not be populatated:
int r0Idx = -1;
int r1Idx = -1;
@Override
public int compareTo(Obj other) {
double diffCost = Math.abs(other.cost - cost);
if (diffCost < 0.01) {//0.001
// NOTE: may revise this. wanting to choose smallest scale
// or smaller fraction of whole
if (imgIdx0 < other.imgIdx0 && imgIdx1 < other.imgIdx1) {
return -1;
} else if (imgIdx0 > other.imgIdx0 && imgIdx1 > other.imgIdx1) {
return 1;
}
if (f < other.f) {
return -1;
} else if (f > other.f) {
return 1;
}
return 0;
} else if (cost < other.cost) {
return -1;
} else if (cost > other.cost) {
return 1;
}
return 0;
}
}
public static int distance(PairInt p1, PairInt p2) {
int diffX = p1.getX() - p2.getX();
int diffY = p1.getY() - p2.getY();
return (int) Math.sqrt(diffX * diffX + diffY * diffY);
}
public static int distance(float x0, float y0, float x1, float y1) {
float diffX = x0 - x1;
float diffY = y0 - y1;
return (int) Math.sqrt(diffX * diffX + diffY * diffY);
}
private void debugPrint2(TIntObjectMap<CRegion> cRegions,
List<GreyscaleImage> rgb, String label) {
Image img1 = rgb.get(1).copyToColorGreyscale();
Image img2 = rgb.get(1).copyToColorGreyscale();
TIntObjectIterator<CRegion> iter = cRegions.iterator();
int nExtraDot = 0;
for (int ii = 0; ii < cRegions.size(); ++ii) {
iter.advance();
int idx = iter.key();
CRegion cr = iter.value();
int[] clr = ImageIOHelper.getNextRGB(ii);
cr.draw(img1, nExtraDot, clr[0], clr[1], clr[2]);
cr.drawEachPixel(img2, nExtraDot, clr[0], clr[1], clr[2]);
}
MiscDebug.writeImage(img1, label + "_" + "_csrs_");
MiscDebug.writeImage(img2, label + "_" + "_csrs_pix_");
System.out.println(cRegions.size() + " labeled regions for " + label);
}
/**
* This method is a work in progress.
* It uses Histogram of Oriented Gradients, histograms of
* images of cie luv converted to the polar angle, and
* histograms of greyscale intensity to find the object in
* regionPoints0 in the MSER regions of regionPoints1.
*
* The method uses a cell size for the histograms and the results
* are sensitive to that.
* The input images have been pre-processed in several ways.
* The images are binned down with preserved aspect ratios to an image
* size such that the largest of width or height is 256 or smaller.
*
* Then ObjectMatcher.findObject12 is used.
* ObjectMatcher.findObject12 creates the polar theta images and
* then looks at the general black, white or other characteristics
* of the template object in dataset0 to determine which MSER
* methods should be used (MSER has a positive and negative image
* search and several parameters that affect the threshold of the
* results).
* The dataset1 MSER regions are filtered to remove those very
* different in color than the template object.
* Both MSER regions are then filtered to keep the strongest mser
* when there are overlapping mser regions.
* The results given to this method here are 3 or so mser for dataset0
* and about 40 or less MSER for dataset1.
*
* The sensitivity of ObjectMatcher.findObject12 and this method to image
* resolution and size mean that use of this method should probably be
* wrapped in a class that handles resolution and size logic in
* pre-processing steps.
* Note that there may also be some color filter properties that would
* need to change for extreme cases.
*
* @param pyrRGB0
* @param pyrPT0
* @param regionPoints0
* @param pyrRGB1
* @param pyrPT1
* @param regionPoints1
* @param settings
* @return
*/
public List<CorrespondenceList> matchObject0(
List<List<GreyscaleImage>> pyrRGB0, List<GreyscaleImage> pyrPT0,
TIntObjectMap<Canonicalizer.RegionPoints> regionPoints0,
List<List<GreyscaleImage>> pyrRGB1, List<GreyscaleImage> pyrPT1,
TIntObjectMap<Canonicalizer.RegionPoints> regionPoints1,
Settings settings) {
TIntObjectMap<HOGs> hogsMap0 = new TIntObjectHashMap<HOGs>();
TIntObjectMap<HOGs> hogsMap1 = new TIntObjectHashMap<HOGs>();
TIntObjectMap<HCPT> hcptMap0 = new TIntObjectHashMap<HCPT>();
TIntObjectMap<HGS> hgsMap0 = new TIntObjectHashMap<HGS>();
TIntObjectMap<HCPT> hcptMap1 = new TIntObjectHashMap<HCPT>();
TIntObjectMap<HGS> hgsMap1 = new TIntObjectHashMap<HGS>();
// use hogs to calculate the dominant orientations
calculateDominantOrientations(regionPoints0,
getOrCreate(hogsMap0, combineImages(pyrRGB0.get(0)), 0));
calculateDominantOrientations(regionPoints1,
getOrCreate(hogsMap1, combineImages(pyrRGB1.get(0)), 0));
Canonicalizer canonicalizer = new Canonicalizer();
// create the CRegion objects which have the rotated points and
// offsets in them
TIntObjectMap<CRegion> cRegions0 = canonicalizer.canonicalizeRegions4(
regionPoints0, pyrRGB0.get(0).get(1));
TIntObjectMap<CRegion> cRegions1 = canonicalizer.canonicalizeRegions4(
regionPoints1, pyrRGB1.get(0).get(1));
// populated on demand, some are skipped for large size differences
TIntObjectMap<TIntObjectMap<CRegion>> csr0
= new TIntObjectHashMap<TIntObjectMap<CRegion>>();
csr0.put(0, cRegions0);
TIntObjectMap<TIntObjectMap<CRegion>> csr1
= new TIntObjectHashMap<TIntObjectMap<CRegion>>();
csr1.put(0, cRegions1);
// key = region index, value = Obj w/ cost being hog intersection
TIntObjectMap<FixedSizeSortedVector<Obj>> rIndexHOGMap1
= new TIntObjectHashMap<FixedSizeSortedVector<Obj>>();
int n0 = pyrPT0.size();
int n1 = pyrPT1.size();
int w0 = pyrPT0.get(0).getWidth();
int h0 = pyrPT0.get(0).getHeight();
int w1 = pyrPT1.get(0).getWidth();
int h1 = pyrPT1.get(0).getHeight();
float sizeFactor = 1.2f;//2;//1.2f;
FixedSizeSortedVector<Obj> bestOverallA =
//new FixedSizeSortedVector<Obj>(100, Obj.class);
new FixedSizeSortedVector<Obj>(n0, Obj.class);
for (int pyrIdx0 = 0; pyrIdx0 < n0; ++pyrIdx0) {
GreyscaleImage gsI0 = combineImages(pyrRGB0.get(pyrIdx0));
GreyscaleImage ptI0 = pyrPT0.get(pyrIdx0);
int w0_i = ptI0.getWidth();
int h0_i = ptI0.getHeight();
float scale0 = (((float) w0 / (float) w0_i)
+ ((float) h0 / (float) h0_i)) / 2.f;
HOGs hogs0 = getOrCreate(hogsMap0, gsI0, pyrIdx0);
HCPT hcpt0 = getOrCreate2(hcptMap0, ptI0, pyrIdx0);
HGS hgs0 = getOrCreate3(hgsMap0, gsI0, pyrIdx0);
TIntObjectMap<CRegion> regions0 = getOrCreate(csr0, pyrIdx0, gsI0,
scale0);
FixedSizeSortedVector<Obj> bestPerOctave =
//new FixedSizeSortedVector<Obj>(100, Obj.class);
new FixedSizeSortedVector<Obj>(1, Obj.class);
for (int pyrIdx1 = 0; pyrIdx1 < n1; ++pyrIdx1) {
GreyscaleImage gsI1 = combineImages(pyrRGB1.get(pyrIdx1));
GreyscaleImage ptI1 = pyrPT1.get(pyrIdx1);
int w1_i = ptI1.getWidth();
int h1_i = ptI1.getHeight();
float scale1 = (((float) w1 / (float) w1_i)
+ ((float) h1 / (float) h1_i)) / 2.f;
TIntObjectMap<CRegion> regions1 = getOrCreate(csr1, pyrIdx1,
gsI1, scale1);
HOGs hogs1 = getOrCreate(hogsMap1, gsI1, pyrIdx1);
HCPT hcpt1 = getOrCreate2(hcptMap1, ptI1, pyrIdx1);
HGS hgs1 = getOrCreate3(hgsMap1, gsI1, pyrIdx1);
TIntObjectIterator<CRegion> iter0 = regions0.iterator();
for (int i0 = 0; i0 < regions0.size(); ++i0) {
iter0.advance();
int rIdx0 = iter0.key();
CRegion cr0 = iter0.value();
int sz0 = calculateObjectSizeByAvgDist(
cr0.ellipseParams.xC, cr0.ellipseParams.yC,
cr0.offsetsToOrigCoords.values());
//int area0_full = csr0.get(0).get(rIdx0).offsetsToOrigCoords.size();
TIntObjectIterator<CRegion> iter1 = regions1.iterator();
for (int i1 = 0; i1 < regions1.size(); ++i1) {
iter1.advance();
// because these regions were made w/ hog orientations,
// there may be multiple regions with the same
// original rIdx1 stored as cr.dataIdx, but having
// a different rIdx1 here.
// so cr.dataIdx is used below for the identity to keep
// the best match for the cr.dataIdx (== original rIdx)
int rIdx1 = iter1.key();
CRegion cr1 = iter1.value();
int sz1 = calculateObjectSizeByAvgDist(
cr1.ellipseParams.xC, cr1.ellipseParams.yC,
cr1.offsetsToOrigCoords.values());
/*
int xp0 = -1; int yp0 = -1; int xp1 = -1; int yp1 = -1;
if (debug) {
float scale00 = (((float) w0 / (float) w0_i) + ((float) h0 / (float) h0_i)) / 2.f;
float scale01 = (((float) w1 / (float) w1_i) + ((float) h1 / (float) h1_i)) / 2.f;
xp0 = (int)Math.round(scale00 * cr0.ellipseParams.xC);
yp0 = (int)Math.round(scale00 * cr0.ellipseParams.yC);
xp1 = (int)Math.round(scale01 * cr1.ellipseParams.xC);
yp1 = (int)Math.round(scale01 * cr1.ellipseParams.yC);
}*/
// size filter
if ((sz1 > sz0 && ((sz1 / sz0) > sizeFactor))
|| (sz0 > sz1 && ((sz0 / sz1) > sizeFactor))) {
//System.out.format(
// " REMOVING (%d,%d) where sz0=%d sz1=%d\n",
// xp1, yp1, sz0, sz1);
continue;
}
double[] hogCosts;
float hogCost;
if (false) {// use intersection
//double[]{intersection, f0, f1, count};
hogCosts = sumHOGCost2(hogs0, cr0, hogs1, cr1);
if (hogCosts == null) {
continue;
}
hogCost = 1.f - (float) hogCosts[0];
} else {// use mean difference
//double[]{diff, f0, f1, count, error};
hogCosts = sumHOGCost3(hogs0, cr0, hogs1, cr1);
if (hogCosts == null) {
continue;
}
hogCost = (float)hogCosts[0];
}
// 1 - fraction of whole (is coverage expressed as a cost)
double f0 = Math.max(0, hogCosts[1]);
double f1 = Math.max(0, hogCosts[2]);
double f = (f0 + f1)/2;
Obj obj = new Obj();
obj.cr0 = cr0;
obj.cr1 = cr1;
obj.r0Idx = rIdx0;
obj.r1Idx = rIdx1;
obj.imgIdx0 = pyrIdx0;
obj.imgIdx1 = pyrIdx1;
obj.nMatched = (int) hogCosts[3];
double cost;
double[] costs2;
double hcptHgsCost;
double hcptCost;
double hgsCost;
if (true) {
//double[]{combIntersection, f0, f1,
// intersectionHCPT, intersectionHGS, count}
costs2 = sumCost2(hcpt0, hgs0, cr0, hcpt1, hgs1, cr1);
hcptHgsCost = 1.f - costs2[3];//costs2[0];
hcptCost = 1.f - costs2[3];
hgsCost = 1.f - costs2[4];
} else {
costs2 = sumCost3(hcpt0, hgs0, cr0, hcpt1, hgs1, cr1);
hcptHgsCost = costs2[3];//costs2[0];
hcptCost = costs2[3];
hgsCost = costs2[4];
}
cost = (float) Math.sqrt(
2. * hogCost * hogCost
+ 2. * f * f
+ hcptHgsCost * hcptHgsCost
);
obj.costs = new double[]{
hogCost, f, hcptHgsCost, f0, f1, hcptCost, hgsCost
};
obj.cost = cost;
obj.f = f;
int x0 = Math.round(scale0 * obj.cr0.ellipseParams.xC);
int y0 = Math.round(scale0 * obj.cr0.ellipseParams.yC);
int x1 = Math.round(scale1 * obj.cr1.ellipseParams.xC);
int y1 = Math.round(scale1 * obj.cr1.ellipseParams.yC);
//NOTE: may need to consider the best match
// for each rIdx, that is, consider multiple
// orientations for a region rather than keeping
// the best orienation for a region only
// add to r1 map (which is actually cr.dataIdx)
FixedSizeSortedVector<Obj> objVec = rIndexHOGMap1.get(
cr1.dataIdx);
if (objVec == null) {
objVec = new FixedSizeSortedVector<Obj>(
n0, Obj.class);
rIndexHOGMap1.put(cr1.dataIdx, objVec);
}
boolean added = objVec.add(obj);
added = bestPerOctave.add(obj);
/*if (debug) {
double cost2 = (float) Math.sqrt(
obj.costs[0]*obj.costs[0] +
obj.costs[1]*obj.costs[1] +
obj.costs[2]*obj.costs[2]
);
System.out.format("%s octave %d %d] (%d,%d) best: %.4f (%d,%d) [%.3f,%.3f,%.3f] n=%d c2=%.3f\n",
settings.getDebugLabel(), pyrIdx0, pyrIdx1,
x1, y1, (float) obj.cost,
Math.round(scale0 * obj.cr0.ellipseParams.xC),
Math.round(scale0 * obj.cr0.ellipseParams.yC),
(float) obj.costs[0], (float) obj.costs[1], (float) obj.costs[2],
obj.cr0.offsetsToOrigCoords.size(),
(float)cost2
);
}*/
}
}
} // end over dataset1 octaves
// temporarily print the best of each octave0 to look at
// scale biases
for (int k = 0; k < bestPerOctave.getNumberOfItems(); ++k) {
Obj obj0 = bestPerOctave.getArray()[k];
int imgIdx1 = obj0.imgIdx1;
GreyscaleImage gsI1 = pyrRGB1.get(imgIdx1).get(1);
int w1_i = gsI1.getWidth();
int h1_i = gsI1.getHeight();
float scale1 = (((float) w1 / (float) w1_i) + ((float) h1 / (float) h1_i)) / 2.f;
int or0 = obj0.cr0.hogOrientation;
int or1 = obj0.cr1.hogOrientation;
//String str1 = String.format("angles=(%d,%d) s=(%.1f,%.1f)",
// or0, or1, scale0, scale1);
double cost2 = (float) Math.sqrt(
obj0.costs[0]*obj0.costs[0] +
obj0.costs[1]*obj0.costs[1] +
obj0.costs[2]*obj0.costs[2]
);
bestOverallA.add(obj0);
}
}
System.out.println("r1 points size = " + regionPoints1.size()
+ " r1 map size filtered = " + rIndexHOGMap1.size());
if (debug) {
//if (true) {
Map<QuadInt, Obj> bestMap = new HashMap<QuadInt, Obj>();
// re-ordering the best for each rIdx1:
FixedSizeSortedVector<Obj> tmp1 = new FixedSizeSortedVector<Obj>(
//rIndexHOGMap.size(),
5, Obj.class);
// printing range of hog values for a region1
TIntObjectIterator<FixedSizeSortedVector<Obj>> iter2 = rIndexHOGMap1.iterator();
StringBuilder sb = new StringBuilder();
for (int i3 = 0; i3 < rIndexHOGMap1.size(); ++i3) {
iter2.advance();
//int rIdx = iter2.key();
FixedSizeSortedVector<Obj> vec = iter2.value();
int n = vec.getNumberOfItems();
if (n == 0) {
continue;
}
Obj obj0 = vec.getArray()[0];
tmp1.add(obj0);
}
System.out.println(sb.toString());
StringBuilder sb2 = new StringBuilder();
for (int i = 0; i < tmp1.getNumberOfItems(); ++i) {
Obj obj0 = tmp1.getArray()[i];
int imgIdx0 = obj0.imgIdx0;
int imgIdx1 = obj0.imgIdx1;
GreyscaleImage gsI0 = pyrRGB0.get(imgIdx0).get(1);
GreyscaleImage gsI1 = pyrRGB1.get(imgIdx1).get(1);
float scale00, scale01;
{
int w0_i = gsI0.getWidth();
int h0_i = gsI0.getHeight();
scale00 = (((float) w0 / (float) w0_i) + ((float) h0 / (float) h0_i)) / 2.f;
int w1_i = gsI1.getWidth();
int h1_i = gsI1.getHeight();
scale01 = (((float) w1 / (float) w1_i) + ((float) h1 / (float) h1_i)) / 2.f;
}
String lbl = "_" + obj0.imgIdx0 + "_" + obj0.imgIdx1 + "_"
+ obj0.r0Idx + "_" + obj0.r1Idx;
int or0 = (int) Math.round(
obj0.cr0.ellipseParams.orientation * 180. / Math.PI);
int or1 = (int) Math.round(
obj0.cr1.ellipseParams.orientation * 180. / Math.PI);
String str1 = String.format("angles=(%d,%d ; %d,%d)",
or0, or1, obj0.cr0.hogOrientation,
obj0.cr1.hogOrientation);
int x1 = Math.round(scale01 * obj0.cr1.ellipseParams.xC);
int y1 = Math.round(scale01 * obj0.cr1.ellipseParams.yC);
int x0 = Math.round(scale00 * obj0.cr0.ellipseParams.xC);
int y0 = Math.round(scale00 * obj0.cr0.ellipseParams.yC);
//hogCost, f, hcptHgsCost, f0, f1, costHCPT, costHGS
sb2.append(String.format(
"2] r1 %s %d (%d,%d) best: %.4f (%d,%d) %s [%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f] %s n=%d\n",
settings.getDebugLabel(), i,
x1, y1,
(float) obj0.cost, x0, y0, lbl,
(float) obj0.costs[0], (float) obj0.costs[1],
(float) obj0.costs[2], (float) obj0.costs[3],
(float) obj0.costs[4], (float) obj0.costs[5], (float) obj0.costs[6],
str1, obj0.cr0.offsetsToOrigCoords.size()
));
QuadInt q = new QuadInt(x0, y0, x1, y1);
Obj obj = bestMap.get(q);
if (obj != null) {
if (obj0.compareTo(obj) < 0) {
bestMap.put(q, obj0);
}
} else {
bestMap.put(q, obj0);
}
/*
Image im0 = gsI0.copyToColorGreyscale();
Image im1 = gsI1.copyToColorGreyscale();
int[] clr = new int[]{255,0,0};
obj0.cr0.drawEachPixel(im0, 0, clr[0], clr[1], clr[2]);
obj0.cr1.drawEachPixel(im1, 0, clr[0], clr[1], clr[2]);
//obj0.cr1.draw(im1, 1, 0, 0, 0);
MiscDebug.writeImage(im0, debugLabel + "_" + lbl);
MiscDebug.writeImage(im1, debugLabel + "_" + lbl);
*/
}
System.out.println(sb2.toString());
// bestOverallA = new FixedSizeSortedVector<Obj>(5, Obj.class);
// for (Entry<QuadInt, Obj> entry : bestMap.entrySet()) {
// bestOverallA.add(entry.getValue());
}
if (bestOverallA.getNumberOfItems() == 0) {
return null;
}
/*
TODO: revisit with more tests.
a few tests suggest that the correct answer is to order by cost,
then walk down the array if hogs cost is lower for 2nd best
*/
if (debug) {
System.out.println("looking for smallest hogs cost:");
}
List<Obj> bestOverall = new ArrayList<Obj>(bestOverallA.getNumberOfItems());
for (int i = 0; i < bestOverallA.getNumberOfItems(); ++i) {
Obj objB = bestOverallA.getArray()[i];
bestOverall.add(objB);
}
Set<PairInt> pairs = new HashSet<PairInt>();
// storing top 5 of r1 matches
List<CorrespondenceList> out = new ArrayList<CorrespondenceList>();
for (int i = 0; i < bestOverall.size(); ++i) {
List<QuadInt> qs = new ArrayList<QuadInt>();
Obj obj = bestOverall.get(i);
PairInt pair = new PairInt(obj.r0Idx, obj.r1Idx);
if (!pairs.add(pair)) {
continue;
}
int imgIdx0 = obj.imgIdx0;
int imgIdx1 = obj.imgIdx1;
GreyscaleImage gsI0 = pyrRGB0.get(imgIdx0).get(1);
GreyscaleImage gsI1 = pyrRGB1.get(imgIdx1).get(1);
float scale0, scale1;
{
int w0_i = gsI0.getWidth();
int h0_i = gsI0.getHeight();
scale0 = (((float)w0/(float)w0_i) + ((float)h0/(float)h0_i))/2.f;
int w1_i = gsI1.getWidth();
int h1_i = gsI1.getHeight();
scale1 = (((float)w1/(float)w1_i) + ((float)h1/(float)h1_i))/2.f;
}
// NOTE: for now, just mser centers,
// but should fill out more than this, including centroid of points
int x0 = Math.round(scale0 * obj.cr0.ellipseParams.xC);
int y0 = Math.round(scale0 * obj.cr0.ellipseParams.yC);
int x1 = Math.round(scale1 * obj.cr1.ellipseParams.xC);
int y1 = Math.round(scale1 * obj.cr1.ellipseParams.yC);
QuadInt q = new QuadInt(x0, y0, x1, y1);
qs.add(q);
CorrespondenceList cor = new CorrespondenceList(qs);
out.add(cor);
if (debug) {
//hogCost, f, hcptHgsCost, f0, f1, costHCPT, costHGS
String lbl = "_" + obj.imgIdx0 + "_" + obj.imgIdx1 + "_"
+ obj.r0Idx + "_" + obj.r1Idx;
System.out.format(
"final) %s %d (%d,%d) best: %.4f (%d,%d) %s [%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f] n=%d\n",
settings.getDebugLabel(), i, x1, y1,
(float) obj.cost, x0, y0, lbl,
(float) obj.costs[0], (float) obj.costs[1],
(float) obj.costs[2], (float) obj.costs[3],
(float) obj.costs[4], (float) obj.costs[5], (float) obj.costs[6],
obj.cr0.offsetsToOrigCoords.size()
);
}
}
return out;
}
private void _debugPrint(Obj obj, GreyscaleImage gsI0, GreyscaleImage gsI1,
int w0, int h0, int w1, int h1, String debugLabel) {
if (debug) {
StringBuilder sb2 = new StringBuilder();
float scale00, scale01;
{
int w0_i = gsI0.getWidth();
int h0_i = gsI0.getHeight();
scale00 = (((float) w0 / (float) w0_i) + ((float) h0 / (float) h0_i)) / 2.f;
int w1_i = gsI1.getWidth();
int h1_i = gsI1.getHeight();
scale01 = (((float) w1 / (float) w1_i) + ((float) h1 / (float) h1_i)) / 2.f;
}
String lbl = "_" + obj.imgIdx0 + "_" + obj.imgIdx1 + "_"
+ obj.r0Idx + "_" + obj.r1Idx;
int or0 = (int) Math.round(
obj.cr0.ellipseParams.orientation * 180. / Math.PI);
int or1 = (int) Math.round(
obj.cr1.ellipseParams.orientation * 180. / Math.PI);
String str1 = String.format("angles=(%d,%d ; %d,%d)",
or0, or1, obj.cr0.hogOrientation, obj.cr1.hogOrientation);
//hogCost, f, hcptHgsCost, f0, f1, costHCPT, costHGS
sb2.append(String.format(
" %s (%d,%d) best: %.4f (%d,%d) %s [%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f] %s n=%d",
debugLabel,
Math.round(scale01 * obj.cr1.ellipseParams.xC),
Math.round(scale01 * obj.cr1.ellipseParams.yC),
(float) obj.cost,
Math.round(scale00 * obj.cr0.ellipseParams.xC),
Math.round(scale00 * obj.cr0.ellipseParams.yC), lbl,
(float) obj.costs[0], (float) obj.costs[1],
(float) obj.costs[2], (float) obj.costs[3],
(float) obj.costs[4], (float) obj.costs[5], (float) obj.costs[6],
str1, obj.cr0.offsetsToOrigCoords.size()
));
/*
Image im0 = gsI0.copyToColorGreyscale();
Image im1 = gsI1.copyToColorGreyscale();
int[] clr = new int[]{255,0,0};
obj0.cr0.drawEachPixel(im0, 0, clr[0], clr[1], clr[2]);
obj0.cr1.drawEachPixel(im1, 0, clr[0], clr[1], clr[2]);
//obj0.cr1.draw(im1, 1, 0, 0, 0);
MiscDebug.writeImage(im0, debugLabel + "_" + lbl);
MiscDebug.writeImage(im1, debugLabel + "_" + lbl);
*/
System.out.println(sb2.toString());
}
}
//double[]{combIntersection, f0, f1, intersectionHCPT, intersectionHGS, count}
private double[] sumCost2(HCPT hcpt0, HGS hgs0, CRegion cr0,
HCPT hcpt1, HGS hgs1, CRegion cr1) {
Map<PairInt, PairInt> offsetMap1 = cr1.offsetsToOrigCoords;
double sumCombined = 0;
double sumHCPT = 0;
double sumHGS = 0;
int count = 0;
int[] h0 = new int[hcpt0.getNumberOfBins()];
int[] h1 = new int[h0.length];
// key = transformed offsets, value = coords in image ref frame,
// so, can compare dataset0 and dataset1 points with same
// keys
for (Entry<PairInt, PairInt> entry0 : cr0.offsetsToOrigCoords.entrySet()) {
PairInt pOffset0 = entry0.getKey();
PairInt xy1 = offsetMap1.get(pOffset0);
if (xy1 == null) {
continue;
}
PairInt xy0 = entry0.getValue();
hcpt0.extractBlock(xy0.getX(), xy0.getY(), h0);
hcpt1.extractBlock(xy1.getX(), xy1.getY(), h1);
float intersection = hcpt0.intersection(h0, h1);
sumCombined += (intersection * intersection);
sumHCPT += (intersection * intersection);
hgs0.extractBlock(xy0.getX(), xy0.getY(), h0);
hgs1.extractBlock(xy1.getX(), xy1.getY(), h1);
intersection = hgs0.intersection(h0, h1);
sumCombined += (intersection * intersection);
sumHGS += (intersection * intersection);
count++;
}
if (count == 0) {
return null;
}
sumCombined /= (2.*count);
sumCombined = Math.sqrt(sumCombined);
sumHCPT /= (double)count;
sumHCPT = Math.sqrt(sumHCPT);
sumHGS /= (double)count;
sumHGS = Math.sqrt(sumHGS);
double area1 = cr1.offsetsToOrigCoords.size();
double f1 = 1. - ((double) count / area1);
double area0 = cr0.offsetsToOrigCoords.size();
double f0 = 1. - ((double) count / area0);
return new double[]{sumCombined, f0, f1, sumHCPT, sumHGS, count};
}
//double[]{combIntersection, f0, f1, intersectionHCPT, intersectionHGS, count};
private double[] sumCost3(HCPT hcpt0, HGS hgs0, CRegion cr0,
HCPT hcpt1, HGS hgs1, CRegion cr1) {
int orientation0 = cr0.hogOrientation;
int orientation1 = cr1.hogOrientation;
Map<PairInt, PairInt> offsetMap1 = cr1.offsetsToOrigCoords;
double sum = 0;
double sumHCPT = 0;
double sumHGS = 0;
double sumErrSq = 0;
int count = 0;
int[] h0 = new int[hcpt0.getNumberOfBins()];
int[] h1 = new int[h0.length];
float[] diffAndErr;
//NOTE: the coordinate set block could be changed to not visit
// every point, but to instead use a spacing of the HOG cell length
// which is what Dala & Trigg recommend for their detector windows.
// key = transformed offsets, value = coords in image ref frame,
// so, can compare dataset0 and dataset1 points with same
// keys
for (Entry<PairInt, PairInt> entry0 : cr0.offsetsToOrigCoords.entrySet()) {
PairInt pOffset0 = entry0.getKey();
PairInt xy1 = offsetMap1.get(pOffset0);
if (xy1 == null) {
continue;
}
PairInt xy0 = entry0.getValue();
hcpt0.extractBlock(xy0.getX(), xy0.getY(), h0);
hcpt1.extractBlock(xy1.getX(), xy1.getY(), h1);
// 1.0 is perfect similarity
diffAndErr = hcpt0.diff(h0, h1);
sum += diffAndErr[0];
sumHCPT += diffAndErr[0];
sumErrSq += (diffAndErr[1] * diffAndErr[1]);
hgs0.extractBlock(xy0.getX(), xy0.getY(), h0);
hgs1.extractBlock(xy1.getX(), xy1.getY(), h1);
// 1.0 is perfect similarity
diffAndErr = hgs0.diff(h0, h1);
sum += diffAndErr[0];
sumHGS += diffAndErr[0];
sumErrSq += (diffAndErr[1] * diffAndErr[1]);
count++;
}
if (count == 0) {
return null;
}
sum /= (2.*count);
sumHCPT /= (double)count;
sumHGS /= (double)count;
sumErrSq /= (2.*count);
sumErrSq = Math.sqrt(sumErrSq);
double area1 = cr1.offsetsToOrigCoords.size();
double f1 = 1. - ((double) count / area1);
double area0 = cr0.offsetsToOrigCoords.size();
double f0 = 1. - ((double) count / area0);
return new double[]{sum, f0, f1, count, sumErrSq};
}
}
|
package org.knoxcraft.serverturtle;
import static org.knoxcraft.database.DatabaseConfiguration.convert;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import org.knoxcraft.database.DataAccess;
import org.knoxcraft.database.Database;
import org.knoxcraft.database.exceptions.DatabaseReadException;
import org.knoxcraft.database.exceptions.DatabaseWriteException;
import org.knoxcraft.database.tables.KCTScriptAccess;
import org.knoxcraft.hooks.KCTUploadHook;
import org.knoxcraft.jetty.server.JettyServer;
import org.knoxcraft.turtle3d.KCTJobQueue;
import org.knoxcraft.turtle3d.KCTScript;
import org.knoxcraft.turtle3d.TurtleCompiler;
import org.knoxcraft.turtle3d.TurtleDirection;
import org.knoxcraft.turtle3d.TurtleException;
import org.slf4j.Logger;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.block.ChangeBlockEvent;
import org.spongepowered.api.event.command.SendCommandEvent;
import org.spongepowered.api.event.game.state.GameConstructionEvent;
import org.spongepowered.api.event.game.state.GameStartedServerEvent;
import org.spongepowered.api.event.game.state.GameStoppedServerEvent;
import org.spongepowered.api.event.network.ClientConnectionEvent.Join;
import org.spongepowered.api.event.world.ChangeWorldWeatherEvent;
import org.spongepowered.api.event.world.LoadWorldEvent;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.scheduler.SpongeExecutorService;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.world.DimensionTypes;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.weather.Weather;
import org.spongepowered.api.world.weather.Weathers;
import com.flowpowered.math.vector.Vector3d;
import com.flowpowered.math.vector.Vector3i;
import com.google.inject.Inject;
/**
* Sponge Knoxcraft plugin to run when the Minecraft server starts up.
* @author mrmoeee jspacco kakoijohn
*
*/
@Plugin(id = TurtlePlugin.ID, name = "TurtlePlugin", version = "0.2", description = "Knoxcraft Turtles Plugin for Minecraft", authors = {
"kakoijohn", "mrmoeee", "stringnotfound", "emhastings", "ppypp", "jspacco" })
public class TurtlePlugin {
private static final String SLEEP_TIME = "knoxcraft.sleepTime";
private static final String WORK_CHUNK_SIZE = "knoxcraft.workChunkSize";
private static final String MIN_BUILD_HEIGHT = "knoxcraft.minBuildHeight";
private static final String MAX_BUILD_HEIGHT = "knoxcraft.maxBuildHeight";
private static final String MAX_JOB_SIZE = "knoxcraft.maxJobSize";
public static final String ID = "knoxcraft";
private static final String PLAYER_NAME = "playerName";
private static final String SCRIPT_NAME = "scriptName";
private static final String NUM_UNDO = "numUndo";
private static final String ARE_YOU_SURE = "no";
private JettyServer jettyServer;
@Inject
private Logger log;
private ScriptManager scripts;
private KCTJobQueue jobQueue;
private World world;
private SpongeExecutorService minecraftSyncExecutor;
@Inject
private PluginContainer container;
// The configuration folder for this plugin
@Inject
@ConfigDir(sharedRoot = true)
private File configDir;
// The in-memory version of the knoxcraft configuration file
private CommentedConfigurationNode knoxcraftConfig;
// configured in config/knoxcraft.conf
private long sleepTime;
private int workChunkSize;
private int minBuildHeight;
private int maxBuildHeight;
private int maxJobSize;
private int jobNum = 0;
/**
* Constructor.
*/
public TurtlePlugin() {
scripts = new ScriptManager();
}
/**
* Listener for when the server stop event is called.
* We must safely shutdown the Jetty server, the Minecraft Executor, and the WorkThread.
*/
@Listener
public void onServerStop(GameStoppedServerEvent event) {
if (jettyServer != null) {
jettyServer.shutdown();
}
jobQueue.shutdown();
}
/**
* Game Construction Event. Checks to see if the proper server.properties file exists.
* If it isn't correct, we must replace it with our own configurations.
* @param event
*/
@Listener
public void gameConstructionEvent(GameConstructionEvent event) {
//first event in the plugin lifecycle
KCServerProperties kcProperties = new KCServerProperties();
//If the server.properties file does not exist or is not in the correct format,
//we must change the file to the correct format.
int result = kcProperties.loadServerProperties();
if (result == 1)
log.debug("Correct server.properties file loaded.");
else if (result == 0) {
log.debug("Incorrect server.properties file. Replacing with new file.");
kcProperties.createPropertiesFile();
} else if (result == -1) {
log.debug("No server.properties file found. Creating new one.");
kcProperties.createPropertiesFile();
}
// read configuration parameters
try {
loadOrCreateConfigFile();
} catch (IOException e) {
log.error("Unable to create or load knoxcraft config file!");
// TODO: set up a default
}
}
/**
* On Server Start Event. We must start the Jetty server and set up the user commands.
* @param event
*/
@Listener
public void onServerStart(GameStartedServerEvent event) {
// Hey! The server has started!
log.info("Registering Knoxcraft Turtles plugin");
try {
jettyServer = new JettyServer();
jettyServer.startup();
} catch (Exception e) {
if (jettyServer != null) {
jettyServer.shutdown();
}
log.error("Cannot initialize TurtlePlugin: JettyServer failed to start", e);
}
log.info("Enabling " + container.getName() + " Version " + container.getVersion());
log.info("Authored by " + container.getAuthors());
// Look up previously submitted scripts from the DB
lookupFromDB();
// set up commands
setupCommands();
}
/**
* Load the configuration properties from config/knoxcraft.conf in HOCON format.
*
* If no config file exists, create one with default values.
*
* XXX NOTE: this method also configured the database, which is a bit sloppy.
*
*/
private void loadOrCreateConfigFile() throws IOException
{
// Check for config file config/knoxcraft.conf
File knoxcraftConfigFile = new File(this.configDir, "knoxcraft.conf");
ConfigurationLoader<CommentedConfigurationNode> knoxcraftConfigLoader =
HoconConfigurationLoader.builder().setFile(knoxcraftConfigFile).build();
// Create the folder if it does not exist
if (!this.configDir.isDirectory()) {
this.configDir.mkdirs();
}
// Create the config file if it does not exist
if (!knoxcraftConfigFile.isFile()) {
knoxcraftConfigFile.createNewFile();
}
// now load the knoxcraft config file
this.knoxcraftConfig = knoxcraftConfigLoader.load();
// ensure we have correct database defaults
// will add any config values that are missing
Database.configure(knoxcraftConfig);
// set other default configuration settings using this syntax:
// if a node with the given value already exists, it will NOT overwrite it
addConfigSetting(WORK_CHUNK_SIZE, 500, "Number of blocks to build at a time. Larger values will lag and eventually crash the server. 500 seems to work.");
addConfigSetting(SLEEP_TIME, 200, "Number of millis to wait between building chunks of blocks. Shorter values are more likely to lag and eventually crash the server. 200 seems to work.");
addConfigSetting(MIN_BUILD_HEIGHT, 3, "Minimum build height for a flat world. This prevents structures being built underneath the ground and breaking through the bedrock. 3 seems to work.");
addConfigSetting(MAX_BUILD_HEIGHT, 256, "Maximum build height allowed. 256 is the default for Minecraft build height.");
addConfigSetting(MAX_JOB_SIZE, -1, "Maximum number of blocks allowed to be built by invoking a single script. If you do not want a limit, set this value to -1.");
// now save the configuration file, in case we changed anything
knoxcraftConfigLoader.save(this.knoxcraftConfig);
// finally, load our values into instance variables
this.workChunkSize = readIntConfigSetting(WORK_CHUNK_SIZE);
this.sleepTime = readIntConfigSetting(SLEEP_TIME);
this.minBuildHeight = readIntConfigSetting(MIN_BUILD_HEIGHT);
this.maxBuildHeight = readIntConfigSetting(MAX_BUILD_HEIGHT);
this.maxJobSize = readIntConfigSetting(MAX_JOB_SIZE);
log.info(WORK_CHUNK_SIZE+" = "+workChunkSize);
log.info(SLEEP_TIME+" = "+sleepTime);
log.info(MIN_BUILD_HEIGHT+" = "+minBuildHeight);
log.info(MAX_BUILD_HEIGHT+" = "+maxBuildHeight);
log.info(MAX_JOB_SIZE+" = "+maxJobSize);
}
private int readIntConfigSetting(String path) {
return knoxcraftConfig.getNode(convert(path)).getInt();
}
private String readStringConfigSetting(String path) {
return knoxcraftConfig.getNode(convert(path)).getString();
}
private void addConfigSetting(String path, Object value) {
addConfigSetting(path, value, null);
}
private void addConfigSetting(String path, Object value, String comment) {
CommentedConfigurationNode node=knoxcraftConfig.getNode(convert(path));
if (node.isVirtual()) {
log.trace("it's virtual! "+path+" "+value);
node=node.setValue(value);
if (comment!=null){
node.setComment(comment);
}
} else {
log.trace("NOT virtual! "+path+" "+value);
}
}
/**
* On World Load Event. During this time, the weather of the world is set to clear,
* the time is reset to 0, and an event is scheduled to happen every 1/2 of a Minecraft day
* to reset the time so it will never become nighttime.
* The KCTJobQueue is also initialized in this step creating a Worker thread that waits on the
* consumer to put work on the queue.
* @param event
*/
@Listener
public void onWorldLoad(LoadWorldEvent event) {
if (event.getTargetWorld().getDimension().getType() == DimensionTypes.OVERWORLD) {
world = event.getTargetWorld();
// CLEAR SKIES
world.setWeather(Weathers.CLEAR);
// BRIGHT SUNNY DAY (12000 = sun set)
world.getProperties().setWorldTime(0);
log.debug(String.format("Currenttime: " + world.getProperties().getWorldTime()));
// TIME CHANGE SCHEDULER
minecraftSyncExecutor = Sponge.getScheduler().createSyncExecutor(this);
minecraftSyncExecutor.scheduleWithFixedDelay(new Runnable() {
public void run() {
world.getProperties().setWorldTime(0);
log.debug(String.format("Timechange: " + world.getProperties().getWorldTime()));
}
// change minecraftWorld time every 10 minutes
}, 0, 10, TimeUnit.MINUTES);
//SETUP JOBQUEUE FOR TURTLE SCRIPT EXECUTOR
jobQueue = new KCTJobQueue(minecraftSyncExecutor, log, world, sleepTime, minBuildHeight, maxBuildHeight);
}
}
/**
* All of the Commands available in game for the players.
* List of all commands and what they do:
* - /scripts /ls
* lists all of the scripts available to the player to invoke.
* - /invoke /in [script name] (optional [player name])
* Invokes a turtle script. Creates a new turtle, executes the script, and adds the
* work to the work queue.
* - /undo /un (optional [number to undo])
* Undoes the previous script or the last [x] number of scripts if specified.
* - /cancel /cn
* Cancels the currently queued work for the player that called the command.
*/
private void setupCommands() {
// List all the scripts
CommandSpec listScripts = CommandSpec.builder().description(Text.of("List Knoxcraft Turtle Scripts"))
.permission("minecraft.command.me").arguments(GenericArguments.optional(GenericArguments.string(Text.of(PLAYER_NAME))))
.executor(new CommandExecutor() {
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
log.debug(String.format("name of sender is: %s", src.getName().toLowerCase()));
src.sendMessage(Text.of(
String.format("%s is listing turtle scripts (programs)", src.getName().toLowerCase())));
Optional<String> optName = args.<String>getOne(PLAYER_NAME);
if (optName.isPresent()) {
String playerName = optName.get();
if (playerName.equalsIgnoreCase("all")) {
// List all scripts for all players
Map<String, Map<String, KCTScript>> allScriptMap = scripts.getAllScripts();
for (Entry<String, Map<String, KCTScript>> entry : allScriptMap.entrySet()) {
playerName = entry.getKey();
for (Entry<String, KCTScript> entry2 : entry.getValue().entrySet()) {
src.sendMessage(Text.of(
String.format("%s has the script %s", playerName, entry2.getKey())));
}
}
} else {
// List only scripts for the given player
Map<String, KCTScript> map = scripts.getAllScriptsForPlayer(playerName);
for (Entry<String, KCTScript> entry : map.entrySet()) {
src.sendMessage(
Text.of(String.format("%s has script %s"), playerName, entry.getKey()));
}
}
} else {
Map<String, KCTScript> map = scripts.getAllScriptsForPlayer(src.getName().toLowerCase());
if (map == null) {
// hacky way to use a case-insensitive key in a
// map
// in the future, be sure to make all keys
// lower-case
map = scripts.getAllScriptsForPlayer(src.getName());
}
if (map == null) {
src.sendMessage(
Text.of(String.format("We cannot find any scripts for %s", src.getName())));
} else {
for (Entry<String, KCTScript> entry : map.entrySet()) {
log.debug(String.format("%s => %s", entry.getKey(), entry.getValue().getLanguage()));
src.sendMessage(Text
.of(String.format("%s => %s", entry.getKey(), entry.getValue().getLanguage())));
}
}
}
return CommandResult.success();
}
}).build();
Sponge.getCommandManager().register(this, listScripts, "scripts", "ls");
// Invoke a script
CommandSpec invokeScript = CommandSpec.builder().description(Text.of("Invoke a Knoxcraft Turtle Script"))
.permission("minecraft.command.me")
.arguments(GenericArguments.onlyOne(GenericArguments.string(Text.of(SCRIPT_NAME))),
GenericArguments.optional(GenericArguments.string(Text.of(PLAYER_NAME))))
.executor(new CommandExecutor() {
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
Optional<String> optScriptName = args.getOne(SCRIPT_NAME);
if (!optScriptName.isPresent()) {
src.sendMessage(Text.of("No script name provided! You must invoke a script by name"));
return CommandResult.success();
}
String scriptName = optScriptName.get();
String playerName = src.getName().toLowerCase();
log.debug("playername ==" + playerName);
Optional<String> optPlayerName = args.getOne(PLAYER_NAME);
if (optPlayerName.isPresent()) {
playerName = optPlayerName.get();
}
log.debug(String.format("%s invokes script %s from player %s", src.getName(), scriptName,
playerName));
// log.info("scripts == null" + (scripts == null));
// log.info("playerName ==" + playerName);
// log.info("scriptName== " + scriptName);
KCTScript script = scripts.getScript(playerName, scriptName);
if (script == null) {
log.warn(String.format("player %s cannot find script %s", playerName, scriptName));
src.sendMessage(
Text.of(String.format("%s, you have no script named %s", playerName, scriptName)));
return CommandResult.success();
}
SpongeTurtle turtle = new SpongeTurtle(log);
// location of turtle = location of player
if (src instanceof Player) {
Player player = (Player) src;
Location<World> loc = player.getLocation();
Vector3i pos = loc.getBlockPosition();
// get world from setter in spongeTurtle
World w = player.getWorld();
// rotation in degrees = direction
Vector3d headRotation = player.getHeadRotation();
Vector3d rotation = player.getRotation();
log.debug("headRotation=" + headRotation);
log.debug("rotation=" + rotation);
TurtleDirection d = TurtleDirection.getTurtleDirection(rotation);
log.debug("pos= " + pos);
// FIXME make a constructor instead of a bunch of setter methods?
turtle.setPlayer(player);
turtle.setSenderName(playerName);
turtle.setLoc(pos);
turtle.setWorld(w);
turtle.setWorkChunkSize(workChunkSize);
turtle.setJobNum(jobNum++);
turtle.setTurtleDirection(d);
turtle.setScript(script);
turtle.executeScript();
if (maxJobSize == -1 || turtle.getJobSize() < maxJobSize) {
jobQueue.add(turtle);
src.sendMessage(Text.of("Building " + script.getScriptName() + "!"));
log.debug("Job Size: " + turtle.getJobSize());
} else {
src.sendMessage(Text.of("Your script places too many blocks!"));
src.sendMessage(Text.of("Max number of blocks: " + maxJobSize + ", Your block count: " + turtle.getJobSize()));
}
}
return CommandResult.success();
}
}).build();
Sponge.getCommandManager().register(this, invokeScript, "invoke", "in");
CommandSpec undo = CommandSpec.builder().description(Text.of("Undo the previous script"))
.permission("minecraft.command.me")
.arguments(GenericArguments.optional(GenericArguments.integer(Text.of(NUM_UNDO))))
.executor(new CommandExecutor() {
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
Optional<Integer> optNumUndo = args.getOne(NUM_UNDO);
int numUndo = 1;
if (optNumUndo.isPresent()) {
numUndo = optNumUndo.get();
}
log.debug("Undo invoked!");
jobQueue.undoScript(src, numUndo);
return CommandResult.success();
}
}).build();
Sponge.getCommandManager().register(this, undo, "undo", "un");
CommandSpec cancel = CommandSpec.builder().description(Text.of("Cancel currently queued work"))
.permission("minecraft.command.me")
.executor(new CommandExecutor() {
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
log.debug("Cancel invoked!");
jobQueue.cancelScript(src);
return CommandResult.success();
}
}).build();
Sponge.getCommandManager().register(this, cancel, "cancel", "cn");
CommandSpec killAll = CommandSpec.builder().description(Text.of("Kill all queued work"))
.permission("minecraft.command.op")
.arguments(GenericArguments.onlyOne(GenericArguments.string(Text.of(ARE_YOU_SURE))))
.executor(new CommandExecutor() {
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
Optional<String> optAreYouSure = args.getOne(ARE_YOU_SURE);
if (optAreYouSure.isPresent() && optAreYouSure.get().equals("yes")) {
log.warn("Killing all invoked scripts, and emptying the undo stack.");
src.sendMessage(Text.of("Clearing the entire build queue, and the undo queue!"));
jobQueue.killAll();
} else {
src.sendMessage(Text.of("You must say \"/killall yes\" in order to confirm clearing the entire queue!"));
src.sendMessage(Text.of("Once you have cleared the queue, you cannot take this back!"));
}
return CommandResult.success();
}
}).build();
Sponge.getCommandManager().register(this, killAll, "killAll", "killall");
}
/**
* Load the latest version of each script from the DB for each player on
* this world
*
* TODO low priority: Check how Sponge handles worlds; do we have only one
* XML file of scripts for worlds and should we include the world name or
* world ID with the script?
*/
private void lookupFromDB() {
// FIXME translate to Sponge
KCTScriptAccess data = new KCTScriptAccess();
List<DataAccess> results = new LinkedList<DataAccess>();
Map<String, KCTScriptAccess> mostRecentScripts = new HashMap<String, KCTScriptAccess>();
try {
Map<String, Object> filters = new HashMap<String, Object>();
Database.get().loadAll(data, results, filters);
for (DataAccess d : results) {
KCTScriptAccess scriptAccess = (KCTScriptAccess) d;
// Figure out the most recent script for each player-scriptname
// combo
String key = scriptAccess.playerName + "-" + scriptAccess.scriptName;
if (!mostRecentScripts.containsKey(key)) {
mostRecentScripts.put(key, scriptAccess);
} else {
if (scriptAccess.timestamp > mostRecentScripts.get(key).timestamp) {
mostRecentScripts.put(key, scriptAccess);
}
}
log.trace(String.format("from DB: player %s has script %s at time %d%n", scriptAccess.playerName,
scriptAccess.scriptName, scriptAccess.timestamp));
}
TurtleCompiler turtleCompiler = new TurtleCompiler();
for (KCTScriptAccess scriptAccess : mostRecentScripts.values()) {
try {
KCTScript script = turtleCompiler.parseFromJson(scriptAccess.json);
script.setLanguage(scriptAccess.language);
script.setScriptName(scriptAccess.scriptName);
script.setSourceCode(scriptAccess.source);
script.setPlayerName(scriptAccess.playerName);
scripts.putScript(scriptAccess.playerName, script);
log.info(String.format("Loaded script %s for player %s", scriptAccess.scriptName,
scriptAccess.playerName));
} catch (TurtleException e) {
log.error("Internal Server error", e);
}
}
} catch (DatabaseReadException e) {
log.error("cannot read DB", e);
}
}
// Listeners
@Listener
public void onSendCommand(SendCommandEvent event) {
log.info(String.format("Command event listener: %s %s", event.getCommand(), event.getArguments()));
}
/**
* @param loginEvent
*/
@Listener
public void onJoin(Join joinEvent) {
// TODO: verify that this hook related to logging in
// TODO prevent breaking blocks, by figuring out equivalent of
// setCanBuild(false);
log.info("Logging in; checking to see if debug level log works");
log.debug(String.format("player " + joinEvent.getTargetEntity().getName()));
}
/**
* Weather Change Event Listener
* Changes weather to clear any time the weather change event is called.
*
* @param hook
*/
@Listener
public void onWeatherChange(ChangeWorldWeatherEvent worldWeatherListener) {
// TODO turn off weather(weather set clear onWeatherChange
Weather curWeather;
worldWeatherListener.setWeather(Weathers.CLEAR);
curWeather = worldWeatherListener.getWeather();
log.debug(String.format("Weather listener called"));
log.debug(String.format("current weather = %s ", curWeather.getName()));
}
/**
* Block Change Event Listener
* Stop any non-op player from breaking blocks in the world.
* @param event
*/
@Listener
public void blockChangeEvent(ChangeBlockEvent event) {
log.trace("Block Changed: " + event.getCause().root().toString());
if (event.getCause().root() instanceof Player) {
Player player = (Player) event.getCause().root();
if (!player.hasPermission("minecraft.command.op")) {
log.trace("Player: " + player.getName() + " blocked.");
event.setCancelled(true);
}
}
}
/**
* Listener called when scripts are uploaded to the server
*
* @param event
*/
@Listener
public void uploadJSON(KCTUploadHook event) {
log.debug("KCTUploadHook called!");
// add scripts to manager and db
Collection<KCTScript> list = event.getScripts();
for (KCTScript script : list) {
scripts.putScript(event.getPlayerName().toLowerCase(), script);
// This will create the table if it doesn't exist
// and then insert data for the script into a new row
KCTScriptAccess data = new KCTScriptAccess();
data.json = script.toJSONString();
data.source = script.getSourceCode();
data.playerName = event.getPlayerName();
data.scriptName = script.getScriptName();
data.language = script.getLanguage();
try {
Database.get().insert(data);
} catch (DatabaseWriteException e) {
// TODO how to log the full stack trace?
log.error(e.toString());
}
}
}
}
|
package net.fortuna.ical4j.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.ConstraintViolationException;
import net.fortuna.ical4j.model.IndexedComponentList;
import net.fortuna.ical4j.model.Parameter;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.component.VTimeZone;
import net.fortuna.ical4j.model.parameter.TzId;
import net.fortuna.ical4j.model.property.Uid;
/**
* Utility method for working with {@link Calendar}s.
* @author Ben Fortuna
*/
public final class Calendars {
/**
* Constructor made private to enforce static nature.
*/
private Calendars() {
}
/**
* Loads a calendar from the specified file.
* @param filename the name of the file from which to load calendar data
* @return returns a new calendar instance initialised from the specified file
* @throws IOException occurs when there is an error reading the specified file
* @throws ParserException occurs when the data in the specified file is invalid
*/
public static Calendar load(final String filename) throws IOException, ParserException {
FileInputStream fin = new FileInputStream(filename);
CalendarBuilder builder = new CalendarBuilder();
return builder.build(fin);
}
/**
* Loads a calendar from the specified URL.
* @param url the URL from which to load calendar data
* @return returns a new calendar instance initialised from the specified URL
* @throws IOException occurs when there is an error reading from the specified URL
* @throws ParserException occurs when the data in the specified URL is invalid
*/
public static Calendar load(final URL url) throws IOException, ParserException {
CalendarBuilder builder = new CalendarBuilder();
return builder.build(url.openStream());
}
/**
* Merge all properties and components from two specified calendars into one instance.
* Note that the merge process is not very sophisticated, and may result in invalid calendar
* data (e.g. multiple properties of a type that should only be specified once).
* @param c1 the first calendar to merge
* @param c2 the second calendar to merge
* @return a Calendar instance containing all properties and components from both of the specified calendars
*/
public static Calendar merge(final Calendar c1, final Calendar c2) {
Calendar result = new Calendar();
result.getProperties().addAll(c1.getProperties());
for (Iterator i = c2.getProperties().iterator(); i.hasNext();) {
Property p = (Property) i.next();
if (!result.getProperties().contains(p)) {
result.getProperties().add(p);
}
}
result.getComponents().addAll(c1.getComponents());
for (Iterator i = c2.getComponents().iterator(); i.hasNext();) {
Component c = (Component) i.next();
if (!result.getComponents().contains(c)) {
result.getComponents().add(c);
}
}
return result;
}
/**
* Wraps a component in a calendar.
* @param component the component to wrap with a calendar
* @return a calendar containing the specified component
*/
public static Calendar wrap(final Component component) {
ComponentList components = new ComponentList();
components.add(component);
return new Calendar(components);
}
/**
* Splits a calendar object into distinct calendar objects for unique
* identifers (UID).
* @param calendar
* @return
*/
public static Calendar[] split(Calendar calendar) {
// if calendar contains one component or less, or is composed entirely of timezone
// definitions, return the original calendar unmodified..
if (calendar.getComponents().size() <= 1
|| calendar.getComponents(Component.VTIMEZONE).size() == calendar.getComponents().size()) {
return new Calendar[] {calendar};
}
IndexedComponentList timezones = new IndexedComponentList(calendar.getComponents(Component.VTIMEZONE),
Property.TZID);
Map calendars = new HashMap();
for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) {
Component c = (Component) i.next();
if (c instanceof VTimeZone) {
continue;
}
Uid uid = (Uid) c.getProperty(Property.UID);
Calendar uidCal = (Calendar) calendars.get(uid);
if (uidCal == null) {
uidCal = new Calendar(calendar.getProperties(), new ComponentList());
// remove METHOD property for split calendars..
for (Iterator mp = uidCal.getProperties(Property.METHOD).iterator(); mp.hasNext();) {
uidCal.getProperties().remove(mp.next());
}
calendars.put(uid, uidCal);
}
for (Iterator j = c.getProperties().iterator(); j.hasNext();) {
Property p = (Property) j.next();
TzId tzid = (TzId) p.getParameter(Parameter.TZID);
if (tzid != null) {
VTimeZone timezone = (VTimeZone) timezones.getComponent(tzid.getValue());
if (!uidCal.getComponents().contains(timezone)) {
uidCal.getComponents().add(timezone);
}
}
}
uidCal.getComponents().add(c);
}
return (Calendar[]) calendars.values().toArray(new Calendar[calendars.values().size()]);
}
/**
* Returns a unique identifier as specified by components in the provided calendar.
* @param calendar
* @return
* @throws ConstraintViolationException if more than one unique identifer is found in the specified calendar
*/
public static Uid getUid(Calendar calendar) throws ConstraintViolationException {
Uid uid = null;
for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) {
Component c = (Component) i.next();
for (Iterator j = c.getProperties(Property.UID).iterator(); j.hasNext();) {
Uid foundUid = (Uid) j.next();
if (uid != null && !uid.equals(foundUid)) {
throw new ConstraintViolationException("More than one UID found in calendar");
}
uid = foundUid;
}
}
return uid;
}
}
|
package org.jfree.chart.axis;
import java.io.Serializable;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.jfree.chart.util.ObjectUtilities;
/**
* A tick unit for use by subclasses of {@link DateAxis}. Instances of this
* class are immutable.
*/
public class DateTickUnit extends TickUnit implements Serializable {
/** For serialization. */
private static final long serialVersionUID = -7289292157229621901L;
/** A constant for years. */
public static final int YEAR = 0;
/** A constant for months. */
public static final int MONTH = 1;
/** A constant for days. */
public static final int DAY = 2;
/** A constant for hours. */
public static final int HOUR = 3;
/** A constant for minutes. */
public static final int MINUTE = 4;
/** A constant for seconds. */
public static final int SECOND = 5;
/** A constant for milliseconds. */
public static final int MILLISECOND = 6;
/** The unit. */
private int unit;
/** The unit count. */
private int count;
/** The roll unit. */
private int rollUnit;
/** The roll count. */
private int rollCount;
/** The date formatter. */
private DateFormat formatter;
/**
* Creates a new date tick unit. The dates will be formatted using a
* SHORT format for the default locale.
*
* @param unit the unit.
* @param count the unit count.
*/
public DateTickUnit(int unit, int count) {
this(unit, count, null);
}
/**
* Creates a new date tick unit. You can specify the units using one of
* the constants YEAR, MONTH, DAY, HOUR, MINUTE, SECOND or MILLISECOND.
* In addition, you can specify a unit count, and a date format.
*
* @param unit the unit.
* @param count the unit count.
* @param formatter the date formatter (defaults to DateFormat.SHORT).
*/
public DateTickUnit(int unit, int count, DateFormat formatter) {
this(unit, count, unit, count, formatter);
}
/**
* Creates a new unit.
*
* @param unit the unit.
* @param count the count.
* @param rollUnit the roll unit.
* @param rollCount the roll count.
* @param formatter the date formatter (defaults to DateFormat.SHORT).
*/
public DateTickUnit(int unit, int count, int rollUnit, int rollCount,
DateFormat formatter) {
super(DateTickUnit.getMillisecondCount(unit, count));
this.unit = unit;
this.count = count;
this.rollUnit = rollUnit;
this.rollCount = rollCount;
this.formatter = formatter;
if (formatter == null) {
this.formatter = DateFormat.getDateInstance(DateFormat.SHORT);
}
}
/**
* Returns the date unit. This will be one of the constants
* <code>YEAR</code>, <code>MONTH</code>, <code>DAY</code>,
* <code>HOUR</code>, <code>MINUTE</code>, <code>SECOND</code> or
* <code>MILLISECOND</code>, defined by this class. Note that these
* constants do NOT correspond to those defined in Java's
* <code>Calendar</code> class.
*
* @return The date unit.
*/
public int getUnit() {
return this.unit;
}
/**
* Returns the unit count.
*
* @return The unit count.
*/
public int getCount() {
return this.count;
}
/**
* Returns the roll unit. This is the amount by which the tick advances if
* it is "hidden" when displayed on a segmented date axis. Typically the
* roll will be smaller than the regular tick unit (for example, a 7 day
* tick unit might use a 1 day roll).
*
* @return The roll unit.
*/
public int getRollUnit() {
return this.rollUnit;
}
/**
* Returns the roll count.
*
* @return The roll count.
*/
public int getRollCount() {
return this.rollCount;
}
/**
* Formats a value.
*
* @param milliseconds date in milliseconds since 01-01-1970.
*
* @return The formatted date.
*/
public String valueToString(double milliseconds) {
return this.formatter.format(new Date((long) milliseconds));
}
/**
* Formats a date using the tick unit's formatter.
*
* @param date the date.
*
* @return The formatted date.
*/
public String dateToString(Date date) {
return this.formatter.format(date);
}
/**
* Calculates a new date by adding this unit to the base date.
*
* @param base the base date.
*
* @return A new date one unit after the base date.
*
* @see #addToDate(Date, TimeZone)
*/
public Date addToDate(Date base) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(base);
calendar.add(getCalendarField(this.unit), this.count);
return calendar.getTime();
}
/**
* Calculates a new date by adding this unit to the base date.
*
* @param base the base date.
* @param zone the time zone for the date calculation.
*
* @return A new date one unit after the base date.
*
* @since 1.0.6
* @see #addToDate(Date)
*/
public Date addToDate(Date base, TimeZone zone) {
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(base);
calendar.add(getCalendarField(this.unit), this.count);
return calendar.getTime();
}
/**
* Rolls the date forward by the amount specified by the roll unit and
* count.
*
* @param base the base date.
* @return The rolled date.
*
* @see #rollDate(Date, TimeZone)
*/
public Date rollDate(Date base) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(base);
calendar.add(getCalendarField(this.rollUnit), this.rollCount);
return calendar.getTime();
}
/**
* Rolls the date forward by the amount specified by the roll unit and
* count.
*
* @param base the base date.
* @param zone the time zone.
*
* @return The rolled date.
*
* @since 1.0.6
* @see #rollDate(Date)
*/
public Date rollDate(Date base, TimeZone zone) {
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(base);
calendar.add(getCalendarField(this.rollUnit), this.rollCount);
return calendar.getTime();
}
/**
* Returns a field code that can be used with the <code>Calendar</code>
* class.
*
* @return The field code.
*/
public int getCalendarField() {
return getCalendarField(this.unit);
}
/**
* Returns a field code (that can be used with the Calendar class) for a
* given 'unit' code. The 'unit' is one of: {@link #YEAR}, {@link #MONTH},
* {@link #DAY}, {@link #HOUR}, {@link #MINUTE}, {@link #SECOND} and
* {@link #MILLISECOND}.
*
* @param tickUnit the unit.
*
* @return The field code.
*/
private int getCalendarField(int tickUnit) {
switch (tickUnit) {
case (YEAR):
return Calendar.YEAR;
case (MONTH):
return Calendar.MONTH;
case (DAY):
return Calendar.DATE;
case (HOUR):
return Calendar.HOUR_OF_DAY;
case (MINUTE):
return Calendar.MINUTE;
case (SECOND):
return Calendar.SECOND;
case (MILLISECOND):
return Calendar.MILLISECOND;
default:
return Calendar.MILLISECOND;
}
}
/**
* Returns the (approximate) number of milliseconds for the given unit and
* unit count.
* <P>
* This value is an approximation some of the time (e.g. months are
* assumed to have 31 days) but this shouldn't matter.
*
* @param unit the unit.
* @param count the unit count.
*
* @return The number of milliseconds.
*/
private static long getMillisecondCount(int unit, int count) {
switch (unit) {
case (YEAR):
return (365L * 24L * 60L * 60L * 1000L) * count;
case (MONTH):
return (31L * 24L * 60L * 60L * 1000L) * count;
case (DAY):
return (24L * 60L * 60L * 1000L) * count;
case (HOUR):
return (60L * 60L * 1000L) * count;
case (MINUTE):
return (60L * 1000L) * count;
case (SECOND):
return 1000L * count;
case (MILLISECOND):
return count;
default:
throw new IllegalArgumentException(
"DateTickUnit.getMillisecondCount() : unit must "
+ "be one of the constants YEAR, MONTH, DAY, HOUR, MINUTE, "
+ "SECOND or MILLISECOND defined in the DateTickUnit "
+ "class. Do *not* use the constants defined in "
+ "java.util.Calendar."
);
}
}
/**
* Tests this unit for equality with another object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return <code>true</code> or <code>false</code>.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof DateTickUnit)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
DateTickUnit that = (DateTickUnit) obj;
if (this.unit != that.unit) {
return false;
}
if (this.count != that.count) {
return false;
}
if (!ObjectUtilities.equal(this.formatter, that.formatter)) {
return false;
}
return true;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
public int hashCode() {
int result = 19;
result = 37 * result + this.unit;
result = 37 * result + this.count;
result = 37 * result + this.formatter.hashCode();
return result;
}
/**
* Strings for use by the toString() method.
*/
private static final String[] units = {"YEAR", "MONTH", "DAY", "HOUR",
"MINUTE", "SECOND", "MILLISECOND"};
/**
* Returns a string representation of this instance, primarily used for
* debugging purposes.
*
* @return A string representation of this instance.
*/
public String toString() {
return "DateTickUnit[" + DateTickUnit.units[this.unit] + ", "
+ this.count + "]";
}
}
|
package traildb;
import traildb.filters.TrailDBEventFilter;
public class TrailDBTrail
{
private long timestamp;
private long numItems;
private long items;
private long db;
private long cur;
private long currentTrail;
private long numTrails;
public TrailDBTrail(TrailDB tdb, long trailId) {
currentTrail = trailId;
numTrails = tdb.numTrails();
init(tdb, trailId);
}
private native void init(TrailDB tdb, long trailId);
/**
* Get item i that trail cursor is currently pointing at
* @param i index of item to get
* @return The item value
*/
public String getItem(int i) {
if (i >= numItems || i < 0) {
throw new IndexOutOfBoundsException("getItem(" + i + ") but numItems in event is " + numItems);
}
return native_getItem(i);
}
private native String native_getItem(int i);
public String[] getItems() {
String[] output = new String[(int) numItems];
for (long i = 0; i < numItems; i++) {
output[(int) i] = getItem((int) i);
}
return output;
}
/**
* Set the cursor to a new trailId
* @param trailId
*/
public void getTrail(long trailId) {
currentTrail = trailId;
native_getTrail(trailId);
}
private native void native_getTrail(long trailId);
/**
* Set the cursor to the next trail.
* This is useful for processing all trails
* eg.
* do {
* <process trail>
* } while (trail.nextTrail());
*
* @return succeded in getting another trail
*/
public boolean nextTrail() {
currentTrail++;
if (currentTrail >= numTrails) {
return false;
}
native_getTrail(currentTrail);
return true;
}
/**
* Get the length of the trail. This exhausts the trail
* @return
*/
public native long getTrailLength();
public native void setEventFilter(TrailDBEventFilter filter);
public native void unsetEventFilter();
public native TrailDBTrail next();
public native TrailDBTrail peek();
public long getTimestamp() {
if (items == 0) {
throw new IllegalStateException("Cursor is not pointing at an event");
}
return timestamp;
}
/**
* Get number of items the event has
* @return number of items
*/
public long getNumItems() {
if (items == 0) {
throw new IllegalStateException("Cursor is not pointing at an event");
}
return numItems;
}
private static native void initIDs();
static {
System.loadLibrary("TraildbJavaNative");
initIDs();
}
}
|
package org.uma.jmetal.util.experiment.component;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.uma.jmetal.qualityindicator.QualityIndicator;
import org.uma.jmetal.qualityindicator.impl.GenericIndicator;
import org.uma.jmetal.solution.Solution;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.experiment.Experiment;
import org.uma.jmetal.util.experiment.ExperimentComponent;
import org.uma.jmetal.util.experiment.util.ExperimentAlgorithm;
import org.uma.jmetal.util.experiment.util.ExperimentProblem;
import org.uma.jmetal.util.front.Front;
import org.uma.jmetal.util.front.imp.ArrayFront;
import org.uma.jmetal.util.front.util.FrontNormalizer;
import org.uma.jmetal.util.front.util.FrontUtils;
import org.uma.jmetal.util.point.PointSolution;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
/**
* This class computes the {@link QualityIndicator}s of an experiment. Once the algorithms of an
* experiment have been executed through running an instance of class {@link ExecuteAlgorithms},
* the list of indicators in obtained from the {@link ExperimentComponent #getIndicatorsList()} method.
* Then, for every combination algorithm + problem, the indicators are applied to all the FUN files and
* the resulting values are store in a file called as {@link QualityIndicator #getName()}, which is located
* in the same directory of the FUN files.
*
* @author Antonio J. Nebro <antonio@lcc.uma.es>
*/
public class ComputeQualityIndicators<S extends Solution<?>, Result extends List<S>> implements ExperimentComponent {
private final Experiment<S, Result> experiment;
public ComputeQualityIndicators(Experiment<S, Result> experiment) {
this.experiment = experiment ;
}
@Override
public void run() throws IOException {
experiment.removeDuplicatedAlgorithms() ;
resetIndicatorFiles() ;
for (GenericIndicator<S> indicator : experiment.getIndicatorList()) {
JMetalLogger.logger.info("Computing indicator: " + indicator.getName()); ;
for (ExperimentAlgorithm<?, Result> algorithm : experiment.getAlgorithmList()) {
String algorithmDirectory;
algorithmDirectory = experiment.getExperimentBaseDirectory() + "/data/" + algorithm.getAlgorithmTag();
for (ExperimentProblem<?> problem : experiment.getProblemList()) {
String problemDirectory = algorithmDirectory + "/" + problem.getTag();
String referenceFrontDirectory = experiment.getReferenceFrontDirectory();
String referenceFrontName = referenceFrontDirectory + "/" + problem.getReferenceFront();
JMetalLogger.logger.info("RF: " + referenceFrontName);
Front referenceFront = new ArrayFront(referenceFrontName);
FrontNormalizer frontNormalizer = new FrontNormalizer(referenceFront);
Front normalizedReferenceFront = frontNormalizer.normalize(referenceFront);
String qualityIndicatorFile = problemDirectory + "/" + indicator.getName();
indicator.setReferenceParetoFront(normalizedReferenceFront);
for (int run = 0; run < experiment.getIndependentRuns(); run++) {
String frontFileName = problemDirectory + "/" +
experiment.getOutputParetoFrontFileName() + run + ".tsv";
Front front = new ArrayFront(frontFileName);
Front normalizedFront = frontNormalizer.normalize(front);
List<PointSolution> normalizedPopulation = FrontUtils.convertFrontToSolutionList(normalizedFront);
Double indicatorValue = (Double) indicator.evaluate((List<S>) normalizedPopulation);
JMetalLogger.logger.info(indicator.getName() + ": " + indicatorValue);
writeQualityIndicatorValueToFile(indicatorValue, qualityIndicatorFile);
}
}
}
}
findBestIndicatorFronts(experiment) ;
writeSummaryFile(experiment);
}
private void writeQualityIndicatorValueToFile(Double indicatorValue, String qualityIndicatorFile) {
try(FileWriter os = new FileWriter(qualityIndicatorFile, true)) {
os.write("" + indicatorValue + "\n");
} catch (IOException ex) {
throw new JMetalException("Error writing indicator file" + ex) ;
}
}
public void findBestIndicatorFronts(Experiment<?, Result> experiment) throws IOException {
for (GenericIndicator<?> indicator : experiment.getIndicatorList()) {
for (ExperimentAlgorithm<?, Result> algorithm : experiment.getAlgorithmList()) {
String algorithmDirectory;
algorithmDirectory = experiment.getExperimentBaseDirectory() + "/data/" +
algorithm.getAlgorithmTag();
for (ExperimentProblem<?> problem :experiment.getProblemList()) {
String indicatorFileName =
algorithmDirectory + "/" + problem.getTag() + "/" + indicator.getName();
Path indicatorFile = Paths.get(indicatorFileName) ;
if (indicatorFile == null) {
throw new JMetalException("Indicator file " + indicator.getName() + " doesn't exist") ;
}
List<String> fileArray;
fileArray = Files.readAllLines(indicatorFile, StandardCharsets.UTF_8);
List<Pair<Double, Integer>> list = new ArrayList<>() ;
for (int i = 0; i < fileArray.size(); i++) {
Pair<Double, Integer> pair = new ImmutablePair<>(Double.parseDouble(fileArray.get(i)), i) ;
list.add(pair) ;
}
Collections.sort(list, new Comparator<Pair<Double, Integer>>() {
@Override
public int compare(Pair<Double, Integer> pair1, Pair<Double, Integer> pair2) {
if (Math.abs(pair1.getLeft()) > Math.abs(pair2.getLeft())){
return 1;
} else if (Math.abs(pair1.getLeft()) < Math.abs(pair2.getLeft())) {
return -1;
} else {
return 0;
}
}
});
String bestFunFileName ;
String bestVarFileName ;
String medianFunFileName ;
String medianVarFileName ;
String outputDirectory = algorithmDirectory + "/" + problem.getTag() ;
bestFunFileName = outputDirectory + "/BEST_" + indicator.getName() + "_FUN.tsv" ;
bestVarFileName = outputDirectory + "/BEST_" + indicator.getName() + "_VAR.tsv" ;
medianFunFileName = outputDirectory + "/MEDIAN_" + indicator.getName() + "_FUN.tsv" ;
medianVarFileName = outputDirectory + "/MEDIAN_" + indicator.getName() + "_VAR.tsv" ;
if (indicator.isTheLowerTheIndicatorValueTheBetter()) {
String bestFunFile = outputDirectory + "/" +
experiment.getOutputParetoFrontFileName() + list.get(0).getRight() + ".tsv";
String bestVarFile = outputDirectory + "/" +
experiment.getOutputParetoSetFileName() + list.get(0).getRight() + ".tsv";
Files.copy(Paths.get(bestFunFile), Paths.get(bestFunFileName), REPLACE_EXISTING) ;
Files.copy(Paths.get(bestVarFile), Paths.get(bestVarFileName), REPLACE_EXISTING) ;
} else {
String bestFunFile = outputDirectory + "/" +
experiment.getOutputParetoFrontFileName() + list.get(list.size()-1).getRight() + ".tsv";
String bestVarFile = outputDirectory + "/" +
experiment.getOutputParetoSetFileName() + list.get(list.size()-1).getRight() + ".tsv";
Files.copy(Paths.get(bestFunFile), Paths.get(bestFunFileName), REPLACE_EXISTING) ;
Files.copy(Paths.get(bestVarFile), Paths.get(bestVarFileName), REPLACE_EXISTING) ;
}
int medianIndex = list.size() / 2 ;
String medianFunFile = outputDirectory + "/" +
experiment.getOutputParetoFrontFileName() + list.get(medianIndex).getRight() + ".tsv";
String medianVarFile = outputDirectory + "/" +
experiment.getOutputParetoSetFileName() + list.get(medianIndex).getRight() + ".tsv";
Files.copy(Paths.get(medianFunFile), Paths.get(medianFunFileName), REPLACE_EXISTING) ;
Files.copy(Paths.get(medianVarFile), Paths.get(medianVarFileName), REPLACE_EXISTING) ;
}
}
}
}
/**
* Deletes the files containing the indicator values if the exist.
*/
private void resetIndicatorFiles() {
for (GenericIndicator<S> indicator : experiment.getIndicatorList()) {
for (ExperimentAlgorithm<?, Result> algorithm : experiment.getAlgorithmList()) {
for (ExperimentProblem<?> problem: experiment.getProblemList()) {
String algorithmDirectory;
algorithmDirectory = experiment.getExperimentBaseDirectory() + "/data/" + algorithm.getAlgorithmTag();
String problemDirectory = algorithmDirectory + "/" + problem.getTag();
String qualityIndicatorFile = problemDirectory + "/" + indicator.getName();
resetFile(qualityIndicatorFile);
}
}
}
}
/**
* Deletes a file or directory if it does exist
*
* @param file
*/
private void resetFile(String file) {
File f = new File(file);
if (f.exists()) {
JMetalLogger.logger.info("Already existing file " + file);
if (f.isDirectory()) {
JMetalLogger.logger.info("Deleting directory " + file);
if (f.delete()) {
JMetalLogger.logger.info("Directory successfully deleted.");
} else {
JMetalLogger.logger.info("Error deleting directory.");
}
} else {
JMetalLogger.logger.info("Deleting file " + file);
if (f.delete()) {
JMetalLogger.logger.info("File successfully deleted.");
} else {
JMetalLogger.logger.info("Error deleting file.");
}
}
} else {
JMetalLogger.logger.info("File " + file + " does NOT exist.");
}
}
private void writeSummaryFile(Experiment<S, Result> experiment) {
JMetalLogger.logger.info("Writing experiment summary file");
String headerOfCSVFile = "Algorithm,Problem,IndicatorName,ExecutionId,IndicatorValue";
String csvFileName = this.experiment.getExperimentBaseDirectory() + "/QualityIndicatorSummary.csv";
resetFile(csvFileName);
try (FileWriter os = new FileWriter(csvFileName, true)) {
os.write("" + headerOfCSVFile + "\n");
for (GenericIndicator<?> indicator : experiment.getIndicatorList()) {
for (ExperimentAlgorithm<?, Result> algorithm : experiment.getAlgorithmList()) {
String algorithmDirectory;
algorithmDirectory = experiment.getExperimentBaseDirectory() + "/data/" +
algorithm.getAlgorithmTag();
for (ExperimentProblem<?> problem : experiment.getProblemList()) {
String indicatorFileName =
algorithmDirectory + "/" + problem.getTag() + "/" + indicator.getName();
Path indicatorFile = Paths.get(indicatorFileName);
if (indicatorFile == null) {
throw new JMetalException("Indicator file " + indicator.getName() + " doesn't exist");
}
System.out.println("
System.out.println(indicatorFileName) ;
List<String> fileArray;
fileArray = Files.readAllLines(indicatorFile, StandardCharsets.UTF_8);
System.out.println(fileArray) ;
System.out.println("++++++");
for (int i = 0; i < fileArray.size(); i++) {
String row = algorithm.getAlgorithmTag() + "," + problem.getTag() + "," + indicator.getName() + "," + i + "," + fileArray.get(i);
os.write("" + row + "\n");
}
}
}
}
} catch (IOException ex) {
throw new JMetalException("Error writing indicator file" + ex);
}
}
}
|
package org.eclipse.persistence.jpars.test.server;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.Persistence;
import javax.ws.rs.core.MediaType;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.dynamic.DynamicClassLoader;
import org.eclipse.persistence.jpa.rs.PersistenceContext;
import org.eclipse.persistence.jpa.rs.PersistenceFactoryBase;
import org.eclipse.persistence.jpars.test.model.traveler.Traveler;
import org.eclipse.persistence.jpars.test.util.ExamplePropertiesLoader;
import org.eclipse.persistence.jpars.test.util.RestUtils;
import org.junit.BeforeClass;
import org.junit.Test;
public class ServerTravelerTest {
private static final String DEFAULT_PU = "jpars_traveler-static";
private static PersistenceContext context = null;
private static PersistenceFactoryBase factory = null;
/**
* Setup.
*
* @throws Exception the exception
*/
@BeforeClass
public static void setup() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
ExamplePropertiesLoader.loadProperties(properties);
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, null);
properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.DROP_AND_CREATE);
properties.put(PersistenceUnitProperties.CLASSLOADER, new DynamicClassLoader(Thread.currentThread().getContextClassLoader()));
factory = new PersistenceFactoryBase();
context = factory.bootstrapPersistenceContext(DEFAULT_PU, Persistence.createEntityManagerFactory(DEFAULT_PU, properties), RestUtils.getServerURI(), null, true);
if (context == null) {
throw new Exception("Persistence context could not be created.");
}
}
/**
* Test update travel reservation json.
*
* @throws Exception the exception
*/
@Test
public void testUpdateTravelReservationJSON() throws Exception {
updateTravelReservation(MediaType.APPLICATION_JSON_TYPE);
}
/**
* Test update travel reservation xml.
*
* @throws Exception the exception
*/
@Test
public void testUpdateTravelReservationXML() throws Exception {
updateTravelReservation(MediaType.APPLICATION_XML_TYPE);
}
private void updateTravelReservation(MediaType mediaType) throws Exception {
String traveler = null;
if (mediaType == MediaType.APPLICATION_XML_TYPE) {
traveler = RestUtils.getXMLMessage("traveler.xml");
} else {
traveler = RestUtils.getJSONMessage("traveler.json");
}
String response = RestUtils.restUpdate(traveler, Traveler.class.getSimpleName(), DEFAULT_PU, null, mediaType);
assertNotNull(response);
if (mediaType == MediaType.APPLICATION_XML_TYPE) {
assertTrue(response.contains("<reservation>"));
} else {
assertTrue(response.contains("\"reservation\":"));
}
}
}
|
package be.ibridge.kettle.core.dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Props;
import be.ibridge.kettle.core.WindowProperty;
import be.ibridge.kettle.i18n.GlobalMessages;
import be.ibridge.kettle.trans.step.BaseStepDialog;
/**
* This dialog allows you to enter a number.
*
* @author Matt
* @since 19-06-2003
*/
public class EnterNumberDialog extends Dialog
{
private Label wlNumber;
private Text wNumber;
private FormData fdlNumber, fdNumber;
private Button wOK, wCancel;
private FormData fdOK, fdCancel;
private Listener lsOK, lsCancel;
private boolean hideCancelButton;
private Shell shell;
private SelectionAdapter lsDef;
private int samples;
private String shellText;
private String lineText;
private Props props;
/**
* @deprecated Use the CT without the <i>Props</i> parameter (at 2nd position)
*/
public EnterNumberDialog(Shell parent, Props props, int samples, String shellText, String lineText)
{
super(parent, SWT.NONE);
this.props = props;
this.samples = samples;
this.shellText = shellText;
this.lineText = lineText;
}
public EnterNumberDialog(Shell parent, int samples, String shellText, String lineText)
{
super(parent, SWT.NONE);
this.props = Props.getInstance();
this.samples = samples;
this.shellText = shellText;
this.lineText = lineText;
}
public int open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.RESIZE);
props.setLook(shell);
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(shellText);
int length = Const.LENGTH;
int margin = Const.MARGIN;
// From step line
wlNumber = new Label(shell, SWT.NONE);
wlNumber.setText(lineText);
props.setLook(wlNumber);
fdlNumber = new FormData();
fdlNumber.left = new FormAttachment(0, 0);
fdlNumber.top = new FormAttachment(0, margin);
wlNumber.setLayoutData(fdlNumber);
wNumber = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wNumber.setText("100");
props.setLook(wNumber);
fdNumber = new FormData();
fdNumber.left = new FormAttachment(0, 0);
fdNumber.top = new FormAttachment(wlNumber, margin);
fdNumber.right = new FormAttachment(0, length);
wNumber.setLayoutData(fdNumber);
// Some buttons
wOK = new Button(shell, SWT.PUSH);
wOK.setText(GlobalMessages.getSystemString("System.Button.OK"));
if (!hideCancelButton)
{
wCancel = new Button(shell, SWT.PUSH);
wCancel.setText(GlobalMessages.getSystemString("System.Button.Cancel"));
}
fdOK = new FormData();
fdOK.left = new FormAttachment(33, 0);
fdOK.top = new FormAttachment(wNumber, margin * 2);
wOK.setLayoutData(fdOK);
if (!hideCancelButton)
{
fdCancel = new FormData();
fdCancel.left = new FormAttachment(66, 0);
fdCancel.top = new FormAttachment(wNumber, margin * 2);
wCancel.setLayoutData(fdCancel);
}
// Add listeners
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
if (!hideCancelButton)
{
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
}
wOK.addListener (SWT.Selection, lsOK );
wCancel.addListener(SWT.Selection, lsCancel );
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wNumber.addSelectionListener(lsDef);
// Detect [X] or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
getData();
BaseStepDialog.setSize(shell);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return samples;
}
public void dispose()
{
props.setScreen(new WindowProperty(shell));
shell.dispose();
}
public void getData()
{
wNumber.setText(Integer.toString(samples));
wNumber.selectAll();
}
private void cancel()
{
samples = -1;
dispose();
}
private void ok()
{
try
{
samples = Integer.parseInt(wNumber.getText());
dispose();
}
catch (Exception e)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Dialog.Error.EnterInteger"));
mb.setText(Messages.getString("Dialog.Error.Header"));
mb.open();
wNumber.selectAll();
}
}
public void setHideCancel(boolean hideCancel)
{
hideCancelButton = hideCancel;
}
}
|
package cpw.mods.fml.common;
import java.io.File;
import java.io.FileInputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import cpw.mods.fml.common.Mod.CustomProperty;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.Metadata;
import cpw.mods.fml.common.discovery.ASMDataTable;
import cpw.mods.fml.common.discovery.ASMDataTable.ASMData;
import cpw.mods.fml.common.discovery.ModCandidate;
import cpw.mods.fml.common.event.FMLConstructionEvent;
import cpw.mods.fml.common.event.FMLEvent;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLInterModComms.IMCEvent;
import cpw.mods.fml.common.event.FMLFingerprintViolationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerAboutToStartEvent;
import cpw.mods.fml.common.event.FMLServerStartedEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.event.FMLServerStoppedEvent;
import cpw.mods.fml.common.event.FMLServerStoppingEvent;
import cpw.mods.fml.common.event.FMLStateEvent;
import cpw.mods.fml.common.network.FMLNetworkHandler;
import cpw.mods.fml.common.versioning.ArtifactVersion;
import cpw.mods.fml.common.versioning.DefaultArtifactVersion;
import cpw.mods.fml.common.versioning.VersionParser;
import cpw.mods.fml.common.versioning.VersionRange;
public class FMLModContainer implements ModContainer
{
private Mod modDescriptor;
private Object modInstance;
private File source;
private ModMetadata modMetadata;
private String className;
private Map<String, Object> descriptor;
private boolean enabled = true;
private String internalVersion;
private boolean overridesMetadata;
private EventBus eventBus;
private LoadController controller;
private DefaultArtifactVersion processedVersion;
private boolean isNetworkMod;
@SuppressWarnings("deprecation")
private static final BiMap<Class<? extends FMLEvent>, Class<? extends Annotation>> modAnnotationTypes = ImmutableBiMap.<Class<? extends FMLEvent>, Class<? extends Annotation>>builder()
.put(FMLPreInitializationEvent.class, Mod.PreInit.class)
.put(FMLInitializationEvent.class, Mod.Init.class)
.put(FMLPostInitializationEvent.class, Mod.PostInit.class)
.put(FMLServerAboutToStartEvent.class, Mod.ServerAboutToStart.class)
.put(FMLServerStartingEvent.class, Mod.ServerStarting.class)
.put(FMLServerStartedEvent.class, Mod.ServerStarted.class)
.put(FMLServerStoppingEvent.class, Mod.ServerStopping.class)
.put(FMLServerStoppedEvent.class, Mod.ServerStopped.class)
.put(IMCEvent.class,Mod.IMCCallback.class)
.put(FMLFingerprintViolationEvent.class, Mod.FingerprintWarning.class)
.build();
private static final BiMap<Class<? extends Annotation>, Class<? extends FMLEvent>> modTypeAnnotations = modAnnotationTypes.inverse();
private String annotationDependencies;
private VersionRange minecraftAccepted;
private boolean fingerprintNotPresent;
private Set<String> sourceFingerprints;
private Certificate certificate;
private String modLanguage;
private ILanguageAdapter languageAdapter;
private ListMultimap<Class<? extends FMLEvent>,Method> eventMethods;
private Map<String, String> customModProperties;
private ModCandidate candidate;
public FMLModContainer(String className, ModCandidate container, Map<String,Object> modDescriptor)
{
this.className = className;
this.source = container.getModContainer();
this.candidate = container;
this.descriptor = modDescriptor;
this.modLanguage = (String) modDescriptor.get("modLanguage");
this.languageAdapter = "scala".equals(modLanguage) ? new ILanguageAdapter.ScalaAdapter() : new ILanguageAdapter.JavaAdapter();
this.eventMethods = ArrayListMultimap.create();
}
private ILanguageAdapter getLanguageAdapter()
{
return languageAdapter;
}
@Override
public String getModId()
{
return (String) descriptor.get("modid");
}
@Override
public String getName()
{
return modMetadata.name;
}
@Override
public String getVersion()
{
return internalVersion;
}
@Override
public File getSource()
{
return source;
}
@Override
public ModMetadata getMetadata()
{
return modMetadata;
}
@Override
public void bindMetadata(MetadataCollection mc)
{
modMetadata = mc.getMetadataForId(getModId(), descriptor);
if (descriptor.containsKey("useMetadata"))
{
overridesMetadata = !((Boolean)descriptor.get("useMetadata")).booleanValue();
}
if (overridesMetadata || !modMetadata.useDependencyInformation)
{
Set<ArtifactVersion> requirements = Sets.newHashSet();
List<ArtifactVersion> dependencies = Lists.newArrayList();
List<ArtifactVersion> dependants = Lists.newArrayList();
annotationDependencies = (String) descriptor.get("dependencies");
Loader.instance().computeDependencies(annotationDependencies, requirements, dependencies, dependants);
modMetadata.requiredMods = requirements;
modMetadata.dependencies = dependencies;
modMetadata.dependants = dependants;
FMLLog.log(getModId(), Level.FINEST, "Parsed dependency info : %s %s %s", requirements, dependencies, dependants);
}
else
{
FMLLog.log(getModId(), Level.FINEST, "Using mcmod dependency info : %s %s %s", modMetadata.requiredMods, modMetadata.dependencies, modMetadata.dependants);
}
if (Strings.isNullOrEmpty(modMetadata.name))
{
FMLLog.log(getModId(), Level.INFO,"Mod %s is missing the required element 'name'. Substituting %s", getModId(), getModId());
modMetadata.name = getModId();
}
internalVersion = (String) descriptor.get("version");
if (Strings.isNullOrEmpty(internalVersion))
{
Properties versionProps = searchForVersionProperties();
if (versionProps != null)
{
internalVersion = versionProps.getProperty(getModId()+".version");
FMLLog.log(getModId(), Level.FINE, "Found version %s for mod %s in version.properties, using", internalVersion, getModId());
}
}
if (Strings.isNullOrEmpty(internalVersion) && !Strings.isNullOrEmpty(modMetadata.version))
{
FMLLog.log(getModId(), Level.WARNING, "Mod %s is missing the required element 'version' and a version.properties file could not be found. Falling back to metadata version %s", getModId(), modMetadata.version);
internalVersion = modMetadata.version;
}
if (Strings.isNullOrEmpty(internalVersion))
{
FMLLog.log(getModId(), Level.WARNING, "Mod %s is missing the required element 'version' and no fallback can be found. Substituting '1.0'.", getModId());
modMetadata.version = internalVersion = "1.0";
}
String mcVersionString = (String) descriptor.get("acceptedMinecraftVersions");
if (!Strings.isNullOrEmpty(mcVersionString))
{
minecraftAccepted = VersionParser.parseRange(mcVersionString);
}
else
{
minecraftAccepted = Loader.instance().getMinecraftModContainer().getStaticVersionRange();
}
}
public Properties searchForVersionProperties()
{
try
{
FMLLog.log(getModId(), Level.FINE,"Attempting to load the file version.properties from %s to locate a version number for %s", getSource().getName(), getModId());
Properties version = null;
if (getSource().isFile())
{
ZipFile source = new ZipFile(getSource());
ZipEntry versionFile = source.getEntry("version.properties");
if (versionFile!=null)
{
version = new Properties();
version.load(source.getInputStream(versionFile));
}
source.close();
}
else if (getSource().isDirectory())
{
File propsFile = new File(getSource(),"version.properties");
if (propsFile.exists() && propsFile.isFile())
{
version = new Properties();
FileInputStream fis = new FileInputStream(propsFile);
version.load(fis);
fis.close();
}
}
return version;
}
catch (Exception e)
{
Throwables.propagateIfPossible(e);
FMLLog.log(getModId(), Level.FINEST, "Failed to find a usable version.properties file");
return null;
}
}
@Override
public void setEnabledState(boolean enabled)
{
this.enabled = enabled;
}
@Override
public Set<ArtifactVersion> getRequirements()
{
return modMetadata.requiredMods;
}
@Override
public List<ArtifactVersion> getDependencies()
{
return modMetadata.dependencies;
}
@Override
public List<ArtifactVersion> getDependants()
{
return modMetadata.dependants;
}
@Override
public String getSortingRules()
{
return ((overridesMetadata || !modMetadata.useDependencyInformation) ? Strings.nullToEmpty(annotationDependencies) : modMetadata.printableSortingRules());
}
@Override
public boolean matches(Object mod)
{
return mod == modInstance;
}
@Override
public Object getMod()
{
return modInstance;
}
@Override
public boolean registerBus(EventBus bus, LoadController controller)
{
if (this.enabled)
{
FMLLog.log(getModId(), Level.FINE, "Enabling mod %s", getModId());
this.eventBus = bus;
this.controller = controller;
eventBus.register(this);
return true;
}
else
{
return false;
}
}
private Method gatherAnnotations(Class<?> clazz) throws Exception
{
Method factoryMethod = null;
for (Method m : clazz.getDeclaredMethods())
{
for (Annotation a : m.getAnnotations())
{
if (modTypeAnnotations.containsKey(a.annotationType()))
{
Class<?>[] paramTypes = new Class[] { modTypeAnnotations.get(a.annotationType()) };
if (Arrays.equals(m.getParameterTypes(), paramTypes))
{
m.setAccessible(true);
eventMethods.put(modTypeAnnotations.get(a.annotationType()), m);
}
else
{
FMLLog.log(getModId(), Level.SEVERE,"The mod %s appears to have an invalid method annotation %s. This annotation can only apply to methods with argument types %s -it will not be called", getModId(), a.annotationType().getSimpleName(), Arrays.toString(paramTypes));
}
}
else if (a.annotationType().equals(Mod.EventHandler.class))
{
if (m.getParameterTypes().length == 1 && modAnnotationTypes.containsKey(m.getParameterTypes()[0]))
{
m.setAccessible(true);
eventMethods.put((Class<? extends FMLEvent>) m.getParameterTypes()[0],m);
}
else
{
FMLLog.log(getModId(), Level.SEVERE,"The mod %s appears to have an invalid event annotation %s. This annotation can only apply to methods with recognized event arguments - it will not be called", getModId(), a.annotationType().getSimpleName());
}
}
else if (a.annotationType().equals(Mod.InstanceFactory.class))
{
if (Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0 && factoryMethod == null)
{
m.setAccessible(true);
factoryMethod = m;
}
else if (!(Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0))
{
FMLLog.log(getModId(), Level.SEVERE, "The InstanceFactory annotation can only apply to a static method, taking zero arguments - it will be ignored on %s(%s)", m.getName(), Arrays.asList(m.getParameterTypes()));
}
else if (factoryMethod != null)
{
FMLLog.log(getModId(), Level.SEVERE, "The InstanceFactory annotation can only be used once, the application to %s(%s) will be ignored", m.getName(), Arrays.asList(m.getParameterTypes()));
}
}
}
}
return factoryMethod;
}
private void processFieldAnnotations(ASMDataTable asmDataTable) throws Exception
{
SetMultimap<String, ASMData> annotations = asmDataTable.getAnnotationsFor(this);
parseSimpleFieldAnnotation(annotations, Instance.class.getName(), new Function<ModContainer, Object>()
{
public Object apply(ModContainer mc)
{
return mc.getMod();
}
});
parseSimpleFieldAnnotation(annotations, Metadata.class.getName(), new Function<ModContainer, Object>()
{
public Object apply(ModContainer mc)
{
return mc.getMetadata();
}
});
}
private void parseSimpleFieldAnnotation(SetMultimap<String, ASMData> annotations, String annotationClassName, Function<ModContainer, Object> retreiver) throws IllegalAccessException
{
String[] annName = annotationClassName.split("\\.");
String annotationName = annName[annName.length - 1];
for (ASMData targets : annotations.get(annotationClassName))
{
String targetMod = (String) targets.getAnnotationInfo().get("value");
Field f = null;
Object injectedMod = null;
ModContainer mc = this;
boolean isStatic = false;
Class<?> clz = modInstance.getClass();
if (!Strings.isNullOrEmpty(targetMod))
{
if (Loader.isModLoaded(targetMod))
{
mc = Loader.instance().getIndexedModList().get(targetMod);
}
else
{
mc = null;
}
}
if (mc != null)
{
try
{
clz = Class.forName(targets.getClassName(), true, Loader.instance().getModClassLoader());
f = clz.getDeclaredField(targets.getObjectName());
f.setAccessible(true);
isStatic = Modifier.isStatic(f.getModifiers());
injectedMod = retreiver.apply(mc);
}
catch (Exception e)
{
Throwables.propagateIfPossible(e);
FMLLog.log(getModId(), Level.WARNING, e, "Attempting to load @%s in class %s for %s and failing", annotationName, targets.getClassName(), mc.getModId());
}
}
if (f != null)
{
Object target = null;
if (!isStatic)
{
target = modInstance;
if (!modInstance.getClass().equals(clz))
{
FMLLog.log(getModId(), Level.WARNING, "Unable to inject @%s in non-static field %s.%s for %s as it is NOT the primary mod instance", annotationName, targets.getClassName(), targets.getObjectName(), mc.getModId());
continue;
}
}
f.set(target, injectedMod);
}
}
}
@Subscribe
public void constructMod(FMLConstructionEvent event)
{
try
{
ModClassLoader modClassLoader = event.getModClassLoader();
modClassLoader.addFile(source);
modClassLoader.clearNegativeCacheFor(candidate.getClassList());
Class<?> clazz = Class.forName(className, true, modClassLoader);
Certificate[] certificates = clazz.getProtectionDomain().getCodeSource().getCertificates();
int len = 0;
if (certificates != null)
{
len = certificates.length;
}
Builder<String> certBuilder = ImmutableList.<String>builder();
for (int i = 0; i < len; i++)
{
certBuilder.add(CertificateHelper.getFingerprint(certificates[i]));
}
ImmutableList<String> certList = certBuilder.build();
sourceFingerprints = ImmutableSet.copyOf(certList);
String expectedFingerprint = (String) descriptor.get("certificateFingerprint");
fingerprintNotPresent = true;
if (expectedFingerprint != null && !expectedFingerprint.isEmpty())
{
if (!sourceFingerprints.contains(expectedFingerprint))
{
Level warnLevel = Level.SEVERE;
if (source.isDirectory())
{
warnLevel = Level.FINER;
}
FMLLog.log(getModId(), warnLevel, "The mod %s is expecting signature %s for source %s, however there is no signature matching that description", getModId(), expectedFingerprint, source.getName());
}
else
{
certificate = certificates[certList.indexOf(expectedFingerprint)];
fingerprintNotPresent = false;
}
}
CustomProperty[] props = (CustomProperty[]) descriptor.get("customProperties");
if (props!=null && props.length > 0)
{
com.google.common.collect.ImmutableMap.Builder<String, String> builder = ImmutableMap.<String,String>builder();
for (CustomProperty p : props)
{
builder.put(p.k(),p.v());
}
customModProperties = builder.build();
}
else
{
customModProperties = EMPTY_PROPERTIES;
}
Method factoryMethod = gatherAnnotations(clazz);
modInstance = getLanguageAdapter().getNewInstance(this,clazz, modClassLoader, factoryMethod);
isNetworkMod = FMLNetworkHandler.instance().registerNetworkMod(this, clazz, event.getASMHarvestedData());
if (fingerprintNotPresent)
{
eventBus.post(new FMLFingerprintViolationEvent(source.isDirectory(), source, ImmutableSet.copyOf(this.sourceFingerprints), expectedFingerprint));
}
ProxyInjector.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide(), getLanguageAdapter());
processFieldAnnotations(event.getASMHarvestedData());
}
catch (Throwable e)
{
controller.errorOccurred(this, e);
Throwables.propagateIfPossible(e);
}
}
@Subscribe
public void handleModStateEvent(FMLEvent event)
{
if (!eventMethods.containsKey(event.getClass()))
{
return;
}
try
{
for (Method m : eventMethods.get(event.getClass()))
{
m.invoke(modInstance, event);
}
}
catch (Throwable t)
{
controller.errorOccurred(this, t);
}
}
@Override
public ArtifactVersion getProcessedVersion()
{
if (processedVersion == null)
{
processedVersion = new DefaultArtifactVersion(getModId(), getVersion());
}
return processedVersion;
}
@Override
public boolean isImmutable()
{
return false;
}
@Override
public boolean isNetworkMod()
{
return isNetworkMod;
}
@Override
public String getDisplayVersion()
{
return modMetadata.version;
}
@Override
public VersionRange acceptableMinecraftVersionRange()
{
return minecraftAccepted;
}
@Override
public Certificate getSigningCertificate()
{
return certificate;
}
@Override
public String toString()
{
return "FMLMod:"+getModId()+"{"+getVersion()+"}";
}
@Override
public Map<String, String> getCustomModProperties()
{
return customModProperties;
}
@Override
public Class<?> getCustomResourcePackClass()
{
try
{
return getSource().isDirectory() ? Class.forName("cpw.mods.fml.client.FMLFolderResourcePack", true, getClass().getClassLoader()) : Class.forName("cpw.mods.fml.client.FMLFileResourcePack",true, getClass().getClassLoader());
}
catch (ClassNotFoundException e)
{
return null;
}
}
@Override
public Map<String, String> getSharedModDescriptor()
{
Map<String,String> descriptor = Maps.newHashMap();
descriptor.put("modsystem", "FML");
descriptor.put("id", getModId());
descriptor.put("version",getDisplayVersion());
descriptor.put("name", getName());
descriptor.put("url", modMetadata.url);
descriptor.put("authors", modMetadata.getAuthorList());
descriptor.put("description", modMetadata.description);
return descriptor;
}
}
|
package de.mrapp.android.adapter.expandablelist;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Set;
import de.mrapp.android.adapter.ExpandableListAdapter;
import de.mrapp.android.adapter.MultipleChoiceListAdapter;
import de.mrapp.android.adapter.datastructure.UnmodifiableList;
import de.mrapp.android.adapter.datastructure.group.Group;
import de.mrapp.android.adapter.datastructure.group.GroupIterator;
import de.mrapp.android.adapter.datastructure.group.GroupListIterator;
import de.mrapp.android.adapter.datastructure.group.UnmodifiableGroupList;
import de.mrapp.android.adapter.decorator.AbstractExpandableListDecorator;
import de.mrapp.android.adapter.list.selectable.MultipleChoiceListAdapterImplementation;
import de.mrapp.android.adapter.logging.LogLevel;
import de.mrapp.android.adapter.logging.Logger;
import de.mrapp.android.adapter.util.AdapterViewUtil;
import static de.mrapp.android.util.Condition.ensureNotNull;
/**
* An abstract base class for all adapters, whose underlying data is managed as a list of arbitrary
* group and child items. Such an adapter's purpose is to provide the underlying data for
* visualization using a {@link ExpandableListView} widget.
*
* @param <GroupType>
* The type of the underlying data of the adapter's group items
* @param <ChildType>
* The type of the underlying data of the adapter's child items
* @param <DecoratorType>
* The type of the decorator, which allows to customize the appearance of the views, which
* are used to visualize the group and child items of the adapter
* @author Michael Rapp
* @since 0.1.0
*/
public abstract class AbstractExpandableListAdapter<GroupType, ChildType, DecoratorType extends AbstractExpandableListDecorator<GroupType, ChildType>>
extends BaseExpandableListAdapter implements ExpandableListAdapter<GroupType, ChildType> {
/**
* The constant serial version UID.
*/
private static final long serialVersionUID = 1L;
/**
* The key, which is used to store the state of the view, the adapter has been attached to,
* within a bundle.
*/
@VisibleForTesting
protected static final String ADAPTER_VIEW_STATE_BUNDLE_KEY =
AbstractExpandableListAdapter.class.getSimpleName() + "::AdapterViewState";
/**
* The key, which is used to store the adapter, which manages the adapter's group items, within
* a bundle.
*/
@VisibleForTesting
protected static final String GROUP_ADAPTER_BUNDLE_KEY =
AbstractExpandableListAdapter.class.getSimpleName() + "::GroupAdapterState";
/**
* The key, which is used to store the adapters, which manage the adapter's child items, within
* a bundle.
*/
@VisibleForTesting
protected static final String CHILD_ADAPTER_BUNDLE_KEY =
AbstractExpandableListAdapter.class.getSimpleName() + "::ChildAdapterState_%d";
/**
* The key, which is used to store, whether duplicate child items should be allowed, or not,
* within a bundle.
*/
@VisibleForTesting
protected static final String ALLOW_DUPLICATE_CHILDREN_BUNDLE_KEY =
AbstractExpandableListAdapter.class.getSimpleName() + "::AllowDuplicateChildren";
/**
* The key, which is used to store, whether a group's expansion should be triggered, when it is
* clicked by the user, or not, within a bundle.
*/
@VisibleForTesting
protected static final String TRIGGER_GROUP_EXPANSION_ON_CLICK_BUNDLE_KEY =
AbstractExpandableListAdapter.class.getSimpleName() + "::TriggerGroupExpansionOnClick";
/**
* The key, which is used to store the log level, which is used for logging, within a bundle.
*/
@VisibleForTesting
protected static final String LOG_LEVEL_BUNDLE_KEY =
AbstractExpandableListAdapter.class.getSimpleName() + "::LogLevel";
/**
* The context, the adapter belongs to.
*/
private final transient Context context;
/**
* The decorator, which allows to customize the appearance of the views, which are used to
* visualize the group and child items of the adapter.
*/
private final transient DecoratorType decorator;
/**
* The logger, which is used for logging.
*/
private final transient Logger logger;
/**
* A set, which contains the listeners, which should be notified, when an item of the adapter
* has been clicked by the user.
*/
private transient Set<ExpandableListAdapterItemClickListener<GroupType, ChildType>>
itemClickListeners;
/**
* A set, which contains the listeners, which should be notified, when an item of the adapter
* has been long-clicked by the user.
*/
private transient Set<ExpandableListAdapterItemLongClickListener<GroupType, ChildType>>
itemLongClickListeners;
/**
* A set, which contains the listeners, which should be notified, when the adapter's underlying
* data has been modified.
*/
private transient Set<ExpandableListAdapterListener<GroupType, ChildType>> adapterListeners;
/**
* A set, which contains the listeners, which should be notified, when a group item has been
* expanded or collapsed.
*/
private transient Set<ExpansionListener<GroupType, ChildType>> expansionListeners;
/**
* The view, the adapter is currently attached to.
*/
private transient ExpandableListView adapterView;
/**
* True, if duplicate children, regardless from the group they belong to, are allowed, false
* otherwise.
*/
private boolean allowDuplicateChildren;
/**
* True, if the a group's expansion should be triggered, when it is clicked by the user, false
* otherwise.
*/
private boolean triggerGroupExpansionOnClick;
/**
* True, if the method <code>notifyDataSetChanged():void</code> is automatically called when the
* adapter's underlying data has been changed, false otherwise.
*/
private boolean notifyOnChange;
/**
* An adapter, which manages the adapter's group items.
*/
private MultipleChoiceListAdapter<Group<GroupType, ChildType>> groupAdapter;
/**
* True, if the adapter view has been marked to be tainted, false otherwise. If the adapter is
* marked as tainted, it will be synchronized with the adapter's underlying data.
*/
private boolean adapterViewTainted;
/**
* Notifies all listeners, which have been registered to be notified, when an item of the
* adapter has been clicked by the user, about a group, which has been clicked.
*
* @param group
* The group, which has been clicked by the user, as an instance of the generic type
* GroupType. The item may not be null
* @param index
* The index of the group, which has been clicked by the user, as an {@link Integer}
* value. The index must be between 0 and the value of the method
* <code>getGroupCount():int</code> - 1
*/
private void notifyOnGroupClicked(@NonNull final GroupType group, final int index) {
for (ExpandableListAdapterItemClickListener<GroupType, ChildType> listener : itemClickListeners) {
listener.onGroupClicked(this, group, index);
}
}
/**
* Notifies all listeners, which have been registered to be notified, when an item of the
* adapter has been clicked by the user, about a header, which has been clicked.
*
* @param view
* The header view, which has been clicked by the user, as an instance of the class
* {@link View}. The view may not be null
* @param index
* The index of the header, which has been clicked by the user, as an {@link Integer}
* value
*/
private void notifyOnHeaderClicked(@NonNull final View view, final int index) {
for (ExpandableListAdapterItemClickListener<GroupType, ChildType> listener : itemClickListeners) {
listener.onHeaderClicked(this, view, index);
}
}
/**
* Notifies all listeners, which have been registered to be notified, when an item of the
* adapter has been clicked by the user, about a footer, which has been clicked.
*
* @param view
* The footer view, which has been clicked by the user, as an instance of the class
* {@link View}. The view may not be null
* @param index
* The index of the footer, which has been clicked by the user, as an {@link Integer}
* value
*/
private void notifyOnFooterClicked(@NonNull final View view, final int index) {
for (ExpandableListAdapterItemClickListener<GroupType, ChildType> listener : itemClickListeners) {
listener.onFooterClicked(this, view, index);
}
}
/**
* Notifies all listeners, which have been registered to be notified, when an item of the
* adapter has been clicked by the user, about a child, which has been clicked.
*
* @param child
* The child, which has been clicked by the user, as an instance of the generic type
* ChildType. The item may not be null
* @param childIndex
* The index of the child, which has been clicked by the user, as an {@link Integer}
* value. The index must be between 0 and the value of the method
* <code>getChildCount(groupIndex):int</code> - 1
* @param group
* The group, the child, which has been clicked by the user, belongs to, as an instance
* of the generic type GroupType. The item may not be null
* @param groupIndex
* The index of the group, the child, which has been clicked by the user, belongs to, as
* an {@link Integer} value. The index must be between 0 and the value of the method
* <code>getGroupCount():int</code> - 1
*/
private void notifyOnChildClicked(@NonNull final ChildType child, final int childIndex,
@NonNull final GroupType group, final int groupIndex) {
for (ExpandableListAdapterItemClickListener<GroupType, ChildType> listener : itemClickListeners) {
listener.onChildClicked(this, child, childIndex, group, groupIndex);
}
}
/**
* Notifies all listeners, which have been registered to be notified, when an item of the
* adapter has been long-clicked by the user, about a group, which has been long-clicked.
*
* @param group
* The group, which has been long-clicked by the user, as an instance of the generic
* type GroupType. The item may not be null
* @param index
* The index of the group, which has been long-clicked by the user, as an {@link
* Integer} value. The index must be between 0 and the value of the method
* <code>getGroupCount():int</code> - 1
* @return True, if a listener has consumed the long-click, false otherwise
*/
private boolean notifyOnGroupLongClicked(@NonNull final GroupType group, final int index) {
for (ExpandableListAdapterItemLongClickListener<GroupType, ChildType> listener : itemLongClickListeners) {
if (listener.onGroupLongClicked(this, group, index)) {
return true;
}
}
return false;
}
/**
* Notifies all listeners, which have been registered to be notified, when an item of the
* adapter has been long-clicked by the user, about a header, which has been long-clicked.
*
* @param view
* The header view, which has been long-clicked by the user, as an instance of the class
* {@link View}. The view may not be null
* @param index
* The index of the header, which has been long-clicked by the user, as an {@link
* Integer} value
* @return True, if a listener has consumed the long-click-false otherwise
*/
private boolean notifyOnHeaderLongClicked(@NonNull final View view, final int index) {
for (ExpandableListAdapterItemLongClickListener<GroupType, ChildType> listener : itemLongClickListeners) {
if (listener.onHeaderLongClicked(this, view, index)) {
return true;
}
}
return false;
}
/**
* Notifies all listeners, which have been registered to be notified, when an item of the
* adapter has been long-clicked by the user, about a footer, which has been long-clicked.
*
* @param view
* The footer view, which has been long-clicked by the user, as an instance of the class
* {@link View}. The view may not be null
* @param index
* The index of the footer, which has been long-clicked by the user, as an {@link
* Integer} value
* @return True, if a listener has consumed the long-click-false otherwise
*/
private boolean notifyOnFooterLongClicked(@NonNull final View view, final int index) {
for (ExpandableListAdapterItemLongClickListener<GroupType, ChildType> listener : itemLongClickListeners) {
if (listener.onFooterLongClicked(this, view, index)) {
return true;
}
}
return false;
}
/**
* Notifies all listeners, which have been registered to be notified, when an item of the
* adapter has been long-clicked by the user, about a child, which has been long-clicked.
*
* @param child
* The child, which has been long-clicked by the user, as an instance of the generic
* type ChildType. The item may not be null
* @param childIndex
* The index of the child, which has been long-clicked by the user, as an {@link
* Integer} value. The index must be between 0 and the value of the method
* <code>getChildCount(groupIndex):int</code> - 1
* @param group
* The group, the child, which has been long-clicked by the user, belongs to, as an
* instance of the generic type GroupType. The item may not be null
* @param groupIndex
* The index of the group, the child, which has been long-clicked by the user, belongs
* to, as an {@link Integer} value. The index must be between 0 and the value of the
* method <code>getGroupCount():int</code> - 1
* @return True, if a listener has consumed the long-click, false otherwise
*/
private boolean notifyOnChildLongClicked(@NonNull final ChildType child, final int childIndex,
@NonNull final GroupType group, final int groupIndex) {
for (ExpandableListAdapterItemLongClickListener<GroupType, ChildType> listener : itemLongClickListeners) {
if (listener.onChildLongClicked(this, child, childIndex, group, groupIndex)) {
return true;
}
}
return false;
}
/**
* Notifies all listeners, which have been registered to be notified, when the adapter's
* underlying data has been modified, about a group, which has been added to the adapter.
*
* @param group
* The group, which has been added to the adapter, as an instance of the generic type
* GroupType. The group may not be null
* @param index
* The index of the group, which has been added to the adapter, as an {@link Integer}
* value. The index must be between 0 and the value of the method
* <code>getGroupCount():int</code> - 1
*/
private void notifyOnGroupAdded(@NonNull final GroupType group, final int index) {
for (ExpandableListAdapterListener<GroupType, ChildType> listener : adapterListeners) {
listener.onGroupAdded(this, group, index);
}
}
/**
* Notifies all listeners, which have been register to be notified, when the adapter's
* underlying data has been modified, about a group, which has been removed from the adapter.
*
* @param group
* The group, which has been removed from the adapter, as an instance of the generic
* type GroupType. The group may not be null
* @param index
* The index of the group, which has been removed from the adapter, as an {@link
* Integer} value. The index must be between 0 and the value of the method
* <code>getGroupCount():int</code> - 1
*/
private void notifyOnGroupRemoved(@NonNull final GroupType group, final int index) {
for (ExpandableListAdapterListener<GroupType, ChildType> listener : adapterListeners) {
listener.onGroupRemoved(this, group, index);
}
}
/**
* Notifies all listeners, which have been registered to be notified, when the adapter's
* underlying data has been modified, about a child, which has been added to the adapter.
*
* @param child
* The child, which has been added to the adapter, as an instance of the generic type
* ChildType. The child may not be null
* @param childIndex
* The index of the child, which has been added to the adapter, as an {@link Integer}
* value. The index must be between 0 and the value of the method
* <code>getChildCount(groupIndex):int</code> - 1
* @param group
* The group, the child, which has been added to the adapter, belongs to, as an instance
* of the generic type GroupType. The group may not be null
* @param groupIndex
* The index of the group, the child, which has been added to the adapter, belongs to,
* as an {@link Integer} value. The index must be between 0 and the value of the method
* <code>getGroupCount():int</code> - 1
*/
private void notifyOnChildAdded(@NonNull final ChildType child, final int childIndex,
@NonNull final GroupType group, final int groupIndex) {
for (ExpandableListAdapterListener<GroupType, ChildType> listener : adapterListeners) {
listener.onChildAdded(this, child, childIndex, group, groupIndex);
}
}
/**
* Notifies all listeners, which have been registered to be notified, when the adapter's
* underlying data has been modified, about a child, which has been removed from the adapter.
*
* @param child
* The child, which has been removed from the adapter, as an instance of the generic
* type ChildType. The child may not be null
* @param childIndex
* The index of the child, which has been removed from the adapter, as an {@link
* Integer} value. The index must be between 0 and the value of the method
* <code>getChildCount(groupIndex):int</code> - 1
* @param group
* The group, the child, which has been removed from the adapter, belongs to, as an
* instance of the generic type GroupType. The group may not be null
* @param groupIndex
* The index of the group, the child, which has been removed from the adapter, belongs
* to, as an {@link Integer} value. The index must be between 0 and the value of the
* method <code>getGroupCount():int</code> - 1
*/
private void notifyOnChildRemoved(@NonNull final ChildType child, final int childIndex,
@NonNull final GroupType group, final int groupIndex) {
for (ExpandableListAdapterListener<GroupType, ChildType> listener : adapterListeners) {
listener.onChildRemoved(this, child, childIndex, group, groupIndex);
}
}
/**
* Creates and returns an adapter, which may be used to manage the adapter's child items.
*
* @return The adapter, which has been created, as an instance of the type {@link
* MultipleChoiceListAdapter}. The adapter may not be null
*/
@CallSuper
private MultipleChoiceListAdapter<ChildType> createChildAdapter() {
MultipleChoiceListAdapter<ChildType> childAdapter =
new MultipleChoiceListAdapterImplementation<>(context,
new NullObjectDecorator<ChildType>());
childAdapter.setLogLevel(LogLevel.OFF);
return childAdapter;
}
/**
* Creates and returns a listener, which allows to trigger the expansion state of a group, when
* it is clicked by the user.
*
* @return The listener, which has been created, as an instance of the type {@link
* ExpandableListAdapterItemClickListener}
*/
private ExpandableListAdapterItemClickListener<GroupType, ChildType> createGroupClickListener() {
return new ExpandableListAdapterItemClickListener<GroupType, ChildType>() {
@Override
public void onGroupClicked(
@NonNull final ExpandableListAdapter<GroupType, ChildType> adapter,
@NonNull final GroupType group, final int index) {
if (isGroupExpansionTriggeredOnClick()) {
triggerGroupExpansion(index);
getLogger().logVerbose(getClass(), "Triggering group expansion on click...");
}
}
@Override
public void onChildClicked(
@NonNull final ExpandableListAdapter<GroupType, ChildType> adapter,
@NonNull final ChildType child, final int childIndex,
@NonNull final GroupType group, final int groupIndex) {
}
@Override
public void onHeaderClicked(
@NonNull final ExpandableListAdapter<GroupType, ChildType> adapter,
@NonNull final View view, final int index) {
}
@Override
public void onFooterClicked(
@NonNull final ExpandableListAdapter<GroupType, ChildType> adapter,
@NonNull final View view, final int index) {
}
};
}
/**
* Creates and returns an {@link ExpandableListView.OnGroupClickListener}, which is invoked,
* when a group item of the adapter has been clicked.
*
* @return The listener, which has been created, as an instance of the type {@link
* ExpandableListView.OnGroupClickListener}
*/
private ExpandableListView.OnGroupClickListener createAdapterViewOnGroupClickListener() {
return new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(final ExpandableListView parent, final View v,
final int groupPosition, final long id) {
notifyOnGroupClicked(getGroup(groupPosition), groupPosition);
return true;
}
};
}
/**
* Creates and returns an {@link ExpandableListView.OnChildClickListener}, which is invoked,
* when a child item of the adapter has been clicked.
*
* @return The listener, which has been created, as an instance of the type {@link
* ExpandableListView.OnChildClickListener}
*/
private ExpandableListView.OnChildClickListener createAdapterViewOnChildClickListener() {
return new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
notifyOnChildClicked(getChild(groupPosition, childPosition), childPosition,
getGroup(groupPosition), groupPosition);
return true;
}
};
}
/**
* Creates and returns an {@link AdapterView.OnItemClickListener}, which is invoked, when an
* item of the adapter has been clicked.
*
* @return The listener, which has been created, as an instance of the type {@link
* AdapterView.OnItemClickListener}
*/
private AdapterView.OnItemClickListener createAdapterViewOnItemClickListener() {
return new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(final AdapterView<?> parent, final View view,
final int position, final long id) {
int itemType = ExpandableListView.getPackedPositionType(id);
if (itemType == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
int groupIndex = ExpandableListView.getPackedPositionGroup(id);
if (groupIndex == Integer.MAX_VALUE) {
if (position < getAdapterView().getHeaderViewsCount()) {
notifyOnHeaderClicked(view, position);
} else {
int totalCount = getAdapterView().getCount();
int headerCount = getAdapterView().getHeaderViewsCount();
int footerCount = getAdapterView().getFooterViewsCount();
int itemCount = totalCount - headerCount - footerCount;
notifyOnFooterClicked(view, position - headerCount - itemCount);
}
}
}
}
};
}
/**
* Creates and returns an {@link AdapterView.OnItemLongClickListener}, which is invoked, when an
* item of the adapter has been long-clicked.
*
* @return The listener, which has been created, as an instance of the type {@link
* AdapterView.OnItemLongClickListener}
*/
private AdapterView.OnItemLongClickListener createAdapterViewOnItemLongClickListener() {
return new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(final AdapterView<?> parent, final View view,
final int position, final long id) {
int itemType = ExpandableListView.getPackedPositionType(id);
if (itemType == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
int groupIndex = ExpandableListView.getPackedPositionGroup(id);
if (groupIndex == Integer.MAX_VALUE) {
if (position < getAdapterView().getHeaderViewsCount()) {
return notifyOnHeaderLongClicked(view, position);
} else {
int totalCount = getAdapterView().getCount();
int headerCount = getAdapterView().getHeaderViewsCount();
int footerCount = getAdapterView().getFooterViewsCount();
int itemCount = totalCount - headerCount - footerCount;
return notifyOnFooterLongClicked(view,
position - headerCount - itemCount);
}
} else {
int childIndex = ExpandableListView.getPackedPositionChild(id);
return notifyOnChildLongClicked(getChild(groupIndex, childIndex),
childIndex, getGroup(groupIndex), groupIndex);
}
} else if (itemType == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
int groupIndex = ExpandableListView.getPackedPositionGroup(id);
return notifyOnGroupLongClicked(getGroup(groupIndex), groupIndex);
}
return false;
}
};
}
/**
* Returns, the context, the adapter belongs to.
*
* @return The context, the adapter belongs to, as an instance of the class {@link Context}. The
* context may not be null
*/
protected final Context getContext() {
return context;
}
/**
* Returns the decorator, which allows to customize the appearance of the views, which are used
* to visualize the group and child items of the adapter.
*
* @return The decorator, which allows to customize the appearance of the views, which are used
* to visualize the group and child items of the adapter, as an instance of the generic type
* DecoratorType. The decorator may not be null
*/
protected final DecoratorType getDecorator() {
return decorator;
}
/**
* Returns the logger, which is used for logging.
*
* @return The logger, which is used for logging, as an instance of the class {@link Logger}.
* The logger may not be null
*/
protected final Logger getLogger() {
return logger;
}
/**
* Returns the adapter, which manages the adapter's group items.
*
* @return The adapter, which manages the adapter's group items, as an instance of the type
* {@link MultipleChoiceListAdapter}. The adapter may not be null
*/
protected final MultipleChoiceListAdapter<Group<GroupType, ChildType>> getGroupAdapter() {
return groupAdapter;
}
/**
* Creates and returns a deep copy of the adapter, which manages the adapter's group items.
*
* @return A deep copy of the adapter, which manages the adapter's group items, as an instance
* of the type {@link MultipleChoiceListAdapter}. The adapter may not be null
* @throws CloneNotSupportedException
* The exception, which is thrown, if cloning is not supported by the adapter's
* underlying data
*/
protected final MultipleChoiceListAdapter<Group<GroupType, ChildType>> cloneGroupAdapter()
throws CloneNotSupportedException {
return groupAdapter.clone();
}
/**
* Returns a set, which contains the listeners, which should be notified, when an item of the
* adapter has been clicked by the user.
*
* @return A set, which contains the listeners, which should be notified, when an item of the
* adapter has been clicked by the user, as an instance of the type {@link Set} or an empty set,
* if no listeners should be notified
*/
protected final Set<ExpandableListAdapterItemClickListener<GroupType, ChildType>> getItemClickListeners() {
return itemClickListeners;
}
/**
* Returns a set, which contains the listeners, which should be notified, when an item of the
* adapter has been long-clicked by the user.
*
* @return A set, which contains the listeners, which should be notified, when an item of the
* adapter has been long-clicked by the user, as an instance of the type {@link Set} or an empty
* set, if no listeners should be notified
*/
protected final Set<ExpandableListAdapterItemLongClickListener<GroupType, ChildType>> getItemLongClickListeners() {
return itemLongClickListeners;
}
/**
* Returns a set, which contains the listeners, which should be notified, when the adapter's
* underlying data has been modified.
*
* @return A set, which contains the listeners, which should be notified, when the adapter's
* underlying data has been modified, as an instance of the type {@link Set} or an empty set, if
* no listeners should be notified
*/
protected final Set<ExpandableListAdapterListener<GroupType, ChildType>> getAdapterListeners() {
return adapterListeners;
}
/**
* Returns a set, which contains the listeners, which should be notified, when a group item has
* been expanded or collapsed.
*
* @return A set, which contains the listeners which should be notified, when a group item has
* been expanded or collapsed, as an instance of the type {@link Set} or an empty set, if no
* listeners should be notified
*/
protected final Set<ExpansionListener<GroupType, ChildType>> getExpansionListeners() {
return expansionListeners;
}
/**
* Returns the view, the adapter is currently attached to.
*
* @return The view, the adapter is currently attached to, as an instance of the class {@link
* ExpandableListView}, or null, if the adapter is currently not attached to a view
*/
protected final ExpandableListView getAdapterView() {
return adapterView;
}
/**
* Notifies, that the adapter's underlying data has been changed, if automatically notifying
* such events is currently enabled.
*/
protected final void notifyOnDataSetChanged() {
if (isNotifiedOnChange()) {
notifyDataSetChanged();
}
}
/**
* Returns the index of a specific group item or throws a {@link NoSuchElementException} if the
* adapter does not contain the group item.
*
* @param group
* The group item, whose index should be returned, as an instance of the generic type
* GroupType. The group item may not be null
* @return The index of the the given group item, as an {@link Integer} value
*/
protected final int indexOfGroupOrThrowException(@NonNull final GroupType group) {
int groupIndex = indexOfGroup(group);
if (groupIndex != -1) {
return groupIndex;
} else {
throw new NoSuchElementException("Adapter does not contain group \"" + group + "\"");
}
}
/**
* Returns the index of a specific child item within the group, which belongs to a specific
* index, or throws a {@link NoSuchElementException} if the group does not contain the child
* item.
*
* @param groupIndex
* The index of the group, the child item, whose index should be returned, belongs to,
* as an {@link Integer} value. The value must be between 0 and the value of the method
* <code>getGroupCount():int</code> - 1, otherwise an {@link IndexOutOfBoundsException}
* will be thrown
* @param child
* The child item, whose index should be returned, as an instance of the generic type
* ChildType. The child item may not be null
* @return The index of the given child item, as an {@link Integer} value
*/
protected final int indexOfChildOrThrowException(final int groupIndex,
@NonNull final ChildType child) {
int childIndex = indexOfChild(groupIndex, child);
if (childIndex != -1) {
return childIndex;
} else {
throw new NoSuchElementException(
"Group \"" + getGroup(groupIndex) + "\" at index " + groupIndex +
" does not contain child \"" + child + "\"");
}
}
/**
* Creates and returns a group. This method may be overridden by subclasses in order to modify
* the group.
*
* @param groupIndex
* The index of the group, which should be created, as an {@link Integer} value
* @param group
* The data of the group, which should be created, as an instance of the generic type
* GroupType. The data may not be null
* @return The group, which has been created, as an instance of the class {@link Group}. The
* group may not be null
*/
@CallSuper
protected Group<GroupType, ChildType> createGroup(final int groupIndex,
@NonNull final GroupType group) {
return new Group<>(group, createChildAdapter());
}
/**
* Synchronizes the adapter view, the adapter is currently attached to, with the adapter's
* underlying data, e.g. by collapsing or expanding its groups depending on their current
* expansion states.
*/
protected final void syncAdapterView() {
if (getAdapterView() != null) {
for (int i = 0; i < getGroupCount(); i++) {
if (isGroupExpanded(i)) {
getAdapterView().expandGroup(i);
} else {
getAdapterView().collapseGroup(i);
}
}
}
}
/**
* This method is invoked when the state of the adapter is about to be stored within a bundle.
*
* @param outState
* The bundle, which is used to store the state of the adapter within a bundle, as an
* instance of the class {@link Bundle}. The bundle may not be null
*/
protected abstract void onSaveInstanceState(@NonNull final Bundle outState);
/**
* This method is invoked when the state of the adapter, which has previously been stored within
* a bundle, is about to be restored.
*
* @param savedState
* The bundle, which has been previously used to store the state of the adapter, as an
* instance of the class {@link Bundle}. The bundle may not be null
*/
protected abstract void onRestoreInstanceState(@NonNull final Bundle savedState);
/**
* This method is invoked to apply the decorator, which allows to customize the view, which is
* used to visualize a specific group item.
*
* @param context
* The context, the adapter belongs to, as an instance of the class {@link Context}. The
* context may not be null
* @param view
* The view, which is used to visualize the group item, as an instance of the class
* {@link View}. The view may not be null
* @param index
* The index of the group item, which should be visualized, as an {@link Integer} value
*/
protected abstract void applyDecoratorOnGroup(@NonNull final Context context,
@NonNull final View view, final int index);
/**
* This method is invoked to apply the decorator, which allows to customize the view, which is
* used to visualize a specific child item.
*
* @param context
* The context, the adapter belongs to, as an instance of the class {@link Context}. The
* context may not be null
* @param view
* The view, which is used to visualize the child item, as an instance of the class
* {@link View}. The view may not be null
* @param groupIndex
* The index of the group, the child item, which should be visualized, belongs to, as an
* {@link Integer} value
* @param childIndex
* The index of the child item, which should be visualized, as an {@link Integer} value
*/
protected abstract void applyDecoratorOnChild(@NonNull final Context context,
@NonNull final View view, final int groupIndex,
final int childIndex);
/**
* Creates a new adapter, whose underlying data is managed as a list of arbitrary group and
* child items.
*
* @param context
* The context, the adapter belongs to, as an instance of the class {@link Context}. The
* context may not be null
* @param decorator
* The decorator, which should be used to customize the appearance of the views, which
* are used to visualize the group and child items of the adapter, as an instance of the
* generic type DecoratorType. The decorator may not be null
* @param logLevel
* The log level, which should be used for logging, as a value of the enum {@link
* LogLevel}. The log level may not be null
* @param groupAdapter
* The adapter, which should manage the adapter's group items, as an instance of the
* type {@link MultipleChoiceListAdapter}. The adapter may not be null
* @param allowDuplicateChildren
* True, if duplicate child items, regardless from the group they belong to, should be
* allowed, false otherwise
* @param notifyOnChange
* True, if the method <code>notifyDataSetChanged():void</code> should be automatically
* called when the adapter's underlying data has been changed, false otherwise
* @param triggerGroupExpansionOnClick
* True, if a group's expansion should be triggered, when it is clicked by the user,
* false otherwise
* @param itemClickListeners
* A set, which contains the listeners, which should be notified, when an item of the
* adapter has been clicked by the user, as an instance of the type {@link Set}, or an
* empty set, if no listeners should be notified
* @param itemLongClickListeners
* A set, which contains the listeners, which should be notified, when an item of the
* adapter has been long-clicked by the user, as an instance of the type {@link Set}, or
* an empty set, if no listeners should be notified
* @param adapterListeners
* A set, which contains the listeners, which should be notified, when the adapter's
* underlying data has been modified, as an instance of the type {@link Set}, or an
* empty set, if no listeners should be notified
* @param expansionListeners
* A set, which contains the listeners, which should be notified, when a group item has
* been expanded or collapsed, as an instance of the type {@link Set}, or an empty set,
* if no listeners should be notified
*/
protected AbstractExpandableListAdapter(@NonNull final Context context,
@NonNull final DecoratorType decorator,
@NonNull final LogLevel logLevel,
@NonNull final MultipleChoiceListAdapter<Group<GroupType, ChildType>> groupAdapter,
final boolean allowDuplicateChildren,
final boolean notifyOnChange,
final boolean triggerGroupExpansionOnClick,
@NonNull final Set<ExpandableListAdapterItemClickListener<GroupType, ChildType>> itemClickListeners,
@NonNull final Set<ExpandableListAdapterItemLongClickListener<GroupType, ChildType>> itemLongClickListeners,
@NonNull final Set<ExpandableListAdapterListener<GroupType, ChildType>> adapterListeners,
@NonNull final Set<ExpansionListener<GroupType, ChildType>> expansionListeners) {
ensureNotNull(context, "The context may not be null");
ensureNotNull(decorator, "The decorator may not be null");
ensureNotNull(itemClickListeners, "The item click listeners may not be null");
ensureNotNull(itemLongClickListeners, "The item long click listeners may not be null");
ensureNotNull(adapterListeners, "The adapter listeners may not be null");
ensureNotNull(expansionListeners, "The expansion listeners may not be null");
this.context = context;
this.decorator = decorator;
this.logger = new Logger(logLevel);
this.groupAdapter = groupAdapter;
this.groupAdapter.setLogLevel(LogLevel.OFF);
this.groupAdapter.notifyOnChange(false);
this.allowDuplicateChildren = allowDuplicateChildren;
this.notifyOnChange = notifyOnChange;
this.triggerGroupExpansionOnClick = triggerGroupExpansionOnClick;
this.itemClickListeners = itemClickListeners;
this.itemLongClickListeners = itemLongClickListeners;
this.adapterListeners = adapterListeners;
this.expansionListeners = expansionListeners;
addItemClickListener(createGroupClickListener());
}
@Override
public final LogLevel getLogLevel() {
return getLogger().getLogLevel();
}
@Override
public final void setLogLevel(@NonNull final LogLevel logLevel) {
getLogger().setLogLevel(logLevel);
}
@Override
public final Bundle getParameters() {
return groupAdapter.getParameters();
}
@Override
public final void setParameters(@Nullable final Bundle parameters) {
groupAdapter.setParameters(parameters);
String message = "Set parameters to \"" + parameters + "\"";
getLogger().logDebug(getClass(), message);
}
@Override
public final void addAdapterListener(
@NonNull final ExpandableListAdapterListener<GroupType, ChildType> listener) {
ensureNotNull(listener, "The listener may not be null");
adapterListeners.add(listener);
String message = "Added adapter listener \"" + listener + "\"";
getLogger().logDebug(getClass(), message);
}
@Override
public final void removeAdapterListener(
@NonNull final ExpandableListAdapterListener<GroupType, ChildType> listener) {
ensureNotNull(listener, "The listener may not be null");
adapterListeners.remove(listener);
String message = "Removed adapter listener \"" + listener + "\"";
getLogger().logDebug(getClass(), message);
}
@Override
public final void addExpansionListener(
@NonNull final ExpansionListener<GroupType, ChildType> listener) {
ensureNotNull(listener, "The listener may not be null");
expansionListeners.add(listener);
String message = "Added expansion listener \"" + listener + "\"";
getLogger().logDebug(getClass(), message);
}
@Override
public final void removeExpansionListener(
@NonNull final ExpansionListener<GroupType, ChildType> listener) {
ensureNotNull(listener, "The listener may not be null");
expansionListeners.remove(listener);
String message = "Removed expansion listener \"" + listener + "\"";
getLogger().logDebug(getClass(), message);
}
@Override
public final void addItemClickListener(
@NonNull final ExpandableListAdapterItemClickListener<GroupType, ChildType> listener) {
ensureNotNull(listener, "The listener may not be null");
itemClickListeners.add(listener);
}
@Override
public final void removeItemClickListener(
@NonNull final ExpandableListAdapterItemClickListener<GroupType, ChildType> listener) {
ensureNotNull(listener, "The listener may not be null");
itemClickListeners.remove(listener);
}
@Override
public final void addItemLongClickListener(
@NonNull final ExpandableListAdapterItemLongClickListener<GroupType, ChildType> listener) {
ensureNotNull(listener, "The listener may not be null");
itemLongClickListeners.add(listener);
}
@Override
public final void removeItemLongClickListener(
@NonNull final ExpandableListAdapterItemLongClickListener<GroupType, ChildType> listener) {
ensureNotNull(listener, "The listener may not be null");
itemLongClickListeners.remove(listener);
}
@Override
public final boolean areDuplicateGroupsAllowed() {
return groupAdapter.areDuplicatesAllowed();
}
@Override
public final void allowDuplicateGroups(final boolean allowDuplicateGroups) {
groupAdapter.allowDuplicates(allowDuplicateGroups);
String message =
"Duplicate groups are now " + (allowDuplicateGroups ? "allowed" : "disallowed");
getLogger().logDebug(getClass(), message);
}
@Override
public final boolean isNotifiedOnChange() {
return notifyOnChange;
}
@Override
public final void notifyOnChange(final boolean notifyOnChange) {
this.notifyOnChange = notifyOnChange;
String message = "Changes of the adapter's underlying data are now " +
(notifyOnChange ? "" : "not ") + "automatically notified";
getLogger().logDebug(getClass(), message);
}
@Override
public final int addGroup(@NonNull final GroupType group) {
int index = getGroupCount();
boolean added = addGroup(index, group);
return added ? index : -1;
}
@Override
public final boolean addGroup(final int index, @NonNull final GroupType group) {
boolean added = groupAdapter.addItem(index, createGroup(index, group));
if (added) {
notifyOnGroupAdded(group, index);
notifyOnDataSetChanged();
String message = "Group \"" + group + "\" added at index " + index;
getLogger().logInfo(getClass(), message);
return true;
} else {
String message = "Group \"" + group + "\" at index " + index +
" not added, because adapter already contains group";
getLogger().logDebug(getClass(), message);
return false;
}
}
@Override
public final boolean addAllGroups(@NonNull final Collection<? extends GroupType> groups) {
return addAllGroups(getGroupCount(), groups);
}
@Override
public final boolean addAllGroups(final int index,
@NonNull final Collection<? extends GroupType> groups) {
ensureNotNull(groups, "The collection may not be null");
boolean result = true;
int currentIndex = index;
for (GroupType group : groups) {
boolean added = addGroup(currentIndex, group);
result &= added;
if (added) {
currentIndex++;
}
}
return result;
}
@SafeVarargs
@Override
public final boolean addAllGroups(@NonNull final GroupType... groups) {
return addAllGroups(getGroupCount(), groups);
}
@SafeVarargs
@Override
public final boolean addAllGroups(final int index, @NonNull final GroupType... groups) {
ensureNotNull(groups, "The array may not be null");
return addAllGroups(index, Arrays.asList(groups));
}
@Override
public final GroupType replaceGroup(final int index, @NonNull final GroupType group) {
ensureNotNull(group, "The group may not be null");
GroupType replacedGroup =
groupAdapter.replaceItem(index, new Group<>(group, createChildAdapter())).getData();
notifyOnGroupRemoved(replacedGroup, index);
notifyOnGroupAdded(group, index);
notifyOnDataSetChanged();
String message =
"Replaced group \"" + replacedGroup + "\" at index " + index + " with item \"" +
group + "\"";
getLogger().logInfo(getClass(), message);
return replacedGroup;
}
@Override
public final GroupType removeGroup(final int index) {
GroupType removedGroup = groupAdapter.removeItem(index).getData();
notifyOnGroupRemoved(removedGroup, index);
notifyOnDataSetChanged();
String message = "Removed group \"" + removedGroup + "\" from index " + index;
getLogger().logInfo(getClass(), message);
return removedGroup;
}
@Override
public final boolean removeGroup(@NonNull final GroupType group) {
int index = indexOfGroup(group);
if (index != -1) {
groupAdapter.removeItem(index);
notifyOnGroupRemoved(group, index);
notifyOnDataSetChanged();
String message = "Removed group \"" + group + "\" from index " + index;
getLogger().logInfo(getClass(), message);
return true;
}
String message =
"Group \"" + group + "\" not removed, because adapter does not contain group";
getLogger().logDebug(getClass(), message);
return false;
}
@Override
public final boolean removeAllGroups(@NonNull final Collection<? extends GroupType> groups) {
ensureNotNull(groups, "The collection may not be null");
int numberOfRemovedGroups = 0;
for (int i = getGroupCount() - 1; i >= 0; i
if (groups.contains(getGroup(i))) {
removeGroup(i);
numberOfRemovedGroups++;
}
}
return numberOfRemovedGroups == groups.size();
}
@SafeVarargs
@Override
public final boolean removeAllGroups(@NonNull final GroupType... groups) {
return removeAllGroups(Arrays.asList(groups));
}
@Override
public final void retainAllGroups(@NonNull final Collection<? extends GroupType> groups) {
ensureNotNull(groups, "The collection may not be null");
for (int i = getGroupCount() - 1; i >= 0; i
if (!groups.contains(getGroup(i))) {
removeGroup(i);
}
}
}
@SafeVarargs
@Override
public final void retainAllGroups(@NonNull final GroupType... groups) {
ensureNotNull(groups, "The array may not be null");
retainAllGroups(Arrays.asList(groups));
}
@Override
public final void clearGroups() {
for (int i = getGroupCount() - 1; i >= 0; i
removeGroup(i);
}
}
@Override
public final Iterator<GroupType> groupIterator() {
return new GroupIterator<>(groupAdapter.iterator());
}
@Override
public final ListIterator<GroupType> groupListIterator() {
return new GroupListIterator<>(groupAdapter.listIterator(), context);
}
@Override
public final ListIterator<GroupType> groupListIterator(final int index) {
return new GroupListIterator<>(groupAdapter.listIterator(index), context);
}
@Override
public final List<GroupType> subListGroups(final int start, final int end) {
return new UnmodifiableGroupList<>(getGroupAdapter().subList(start, end));
}
@Override
public final Object[] groupsToArray() {
return getAllGroups().toArray();
}
@Override
public final <T> T[] groupsToArray(@NonNull final T[] array) {
return getAllGroups().toArray(array);
}
@Override
public final int indexOfGroup(@NonNull final GroupType group) {
ensureNotNull(group, "The group may not be null");
for (int i = 0; i < getGroupCount(); i++) {
if (getGroup(i) == group) {
return i;
}
}
return -1;
}
@Override
public final boolean containsGroup(@NonNull final GroupType group) {
return indexOfGroup(group) != -1;
}
@Override
public final boolean containsAllGroups(@NonNull final Collection<? extends GroupType> groups) {
ensureNotNull(groups, "The collection may not be null");
boolean result = true;
for (GroupType group : groups) {
result &= containsGroup(group);
}
return result;
}
@SafeVarargs
@Override
public final boolean containsAllGroups(@NonNull final GroupType... groups) {
return containsAllGroups(Arrays.asList(groups));
}
@Override
public final GroupType getGroup(final int groupIndex) {
return groupAdapter.getItem(groupIndex).getData();
}
@Override
public final List<GroupType> getAllGroups() {
return new UnmodifiableGroupList<>(groupAdapter.getAllItems());
}
@Override
public final boolean isGroupEmpty(final int groupIndex) {
return groupAdapter.getItem(groupIndex).getChildAdapter().isEmpty();
}
@Override
public final boolean isGroupEmpty(@NonNull final GroupType group) {
return isGroupEmpty(indexOfGroupOrThrowException(group));
}
@Override
public final boolean areDuplicateChildrenAllowed() {
return allowDuplicateChildren;
}
@Override
public final void allowDuplicateChildren(final boolean allowDuplicateChildren) {
this.allowDuplicateChildren = true;
Iterator<Group<GroupType, ChildType>> iterator = groupAdapter.iterator();
while (iterator.hasNext()) {
Group<GroupType, ChildType> group = iterator.next();
group.getChildAdapter().allowDuplicates(allowDuplicateChildren);
}
String message =
"Duplicate children are now " + (allowDuplicateChildren ? "allowed" : "disallowed");
getLogger().logDebug(getClass(), message);
}
@Override
public final boolean areDuplicateChildrenAllowed(final int groupIndex) {
return groupAdapter.getItem(groupIndex).getChildAdapter().areDuplicatesAllowed();
}
@Override
public final void allowDuplicateChildren(final int groupIndex,
final boolean allowDuplicateChildren) {
Group<GroupType, ChildType> group = groupAdapter.getItem(groupIndex);
group.getChildAdapter().allowDuplicates(allowDuplicateChildren);
String message = "Duplicate children are now " +
(allowDuplicateChildren ? "allowed" : "disallowed") + " for group \"" +
group.getData() + "\" at index " + groupIndex;
getLogger().logDebug(getClass(), message);
}
@Override
public final boolean areDuplicateChildrenAllowed(@NonNull final GroupType group) {
return areDuplicateChildrenAllowed(indexOfGroupOrThrowException(group));
}
@Override
public final void allowDuplicateChildren(@NonNull final GroupType group,
final boolean allowDuplicateChildren) {
allowDuplicateChildren(indexOfGroupOrThrowException(group), allowDuplicateChildren);
}
@Override
public final int addChild(final int groupIndex, @NonNull final ChildType child) {
int index = getChildCount(groupIndex);
boolean added = addChild(groupIndex, getChildCount(groupIndex), child);
return added ? index : -1;
}
@Override
public final int addChild(@NonNull final GroupType group, @NonNull final ChildType child) {
int groupIndex = indexOfGroupOrThrowException(group);
int childIndex = getChildCount(groupIndex);
boolean added = addChild(groupIndex, childIndex, child);
return added ? childIndex : -1;
}
@Override
public final boolean addChild(final int groupIndex, final int index,
@NonNull final ChildType child) {
Group<GroupType, ChildType> group = groupAdapter.getItem(groupIndex);
if (areDuplicateChildrenAllowed() || !containsChild(child)) {
boolean added = group.getChildAdapter().addItem(index, child);
if (added) {
notifyOnChildAdded(child, index, group.getData(), groupIndex);
notifyOnDataSetChanged();
String message =
"Child \"" + child + "\" added at index " + index + " to group \"" +
group.getData() + "\" at index " + groupIndex;
getLogger().logInfo(getClass(), message);
return true;
} else {
String message =
"Child \"" + child + "\" at index " + index + " not added to group \"" +
group.getData() + "\" at index " + groupIndex +
", because group already contains child";
getLogger().logDebug(getClass(), message);
return false;
}
} else {
String message =
"Child \"" + child + "\" at index " + index + " not added to group \"" +
group.getData() + "\" at index " + groupIndex +
", because adapter already contains child";
getLogger().logDebug(getClass(), message);
return false;
}
}
@Override
public final boolean addChild(@NonNull final GroupType group, final int index,
@NonNull final ChildType child) {
return addChild(indexOfGroupOrThrowException(group), index, child);
}
@Override
public final boolean addAllChildren(final int groupIndex,
@NonNull final Collection<? extends ChildType> children) {
return addAllChildren(groupIndex, getChildCount(groupIndex), children);
}
@Override
public final boolean addAllChildren(@NonNull final GroupType group,
@NonNull final Collection<? extends ChildType> children) {
return addAllChildren(indexOfGroupOrThrowException(group), children);
}
@Override
public final boolean addAllChildren(final int groupIndex, final int index,
@NonNull final Collection<? extends ChildType> children) {
ensureNotNull(children, "The collection may not be null");
boolean result = true;
int currentIndex = index;
for (ChildType child : children) {
boolean added = addChild(groupIndex, currentIndex, child);
result &= added;
if (added) {
currentIndex++;
}
}
return result;
}
@Override
public final boolean addAllChildren(@NonNull final GroupType group, final int childIndex,
@NonNull final Collection<? extends ChildType> children) {
return addAllChildren(indexOfGroupOrThrowException(group), childIndex, children);
}
@SafeVarargs
@Override
public final boolean addAllChildren(final int groupIndex,
@NonNull final ChildType... children) {
ensureNotNull(children, "The array may not be null");
return addAllChildren(groupIndex, Arrays.asList(children));
}
@SafeVarargs
@Override
public final boolean addAllChildren(@NonNull final GroupType group,
@NonNull final ChildType... children) {
ensureNotNull(children, "The array may not be null");
return addAllChildren(group, Arrays.asList(children));
}
@SafeVarargs
@Override
public final boolean addAllChildren(final int groupIndex, final int index,
@NonNull final ChildType... children) {
ensureNotNull(children, "The array may not be null");
return addAllChildren(groupIndex, index, Arrays.asList(children));
}
@SafeVarargs
@Override
public final boolean addAllChildren(@NonNull final GroupType group, final int index,
@NonNull final ChildType... children) {
ensureNotNull(children, "The array may not be null");
return addAllChildren(group, index, Arrays.asList(children));
}
@Override
public final ChildType replaceChild(final int groupIndex, final int index,
@NonNull final ChildType child) {
ensureNotNull(child, "The child may not be null");
Group<GroupType, ChildType> group = groupAdapter.getItem(groupIndex);
ChildType replacedChild = group.getChildAdapter().replaceItem(index, child);
notifyOnChildRemoved(replacedChild, index, group.getData(), groupIndex);
notifyOnChildAdded(replacedChild, index, group.getData(), groupIndex);
notifyOnDataSetChanged();
String message =
"Replaced child \"" + replacedChild + "\" at index " + index + " of group \"" +
group.getData() + "\" at index " + groupIndex + " with child \"" + child +
"\"";
getLogger().logInfo(getClass(), message);
return replacedChild;
}
@Override
public final ChildType replaceChild(@NonNull final GroupType group, final int index,
@NonNull final ChildType child) {
return replaceChild(indexOfGroupOrThrowException(group), index, child);
}
@Override
public final ChildType removeChild(final int groupIndex, final int index) {
return removeChild(false, groupIndex, index);
}
@Override
public final ChildType removeChild(final boolean removeEmptyGroup, final int groupIndex,
final int index) {
Group<GroupType, ChildType> group = groupAdapter.getItem(groupIndex);
ChildType removedChild = group.getChildAdapter().removeItem(index);
notifyOnChildRemoved(removedChild, index, group.getData(), groupIndex);
String message =
"Removed child \"" + removedChild + "\" from index " + index + " of group \"" +
group.getData() + "\" at index " + groupIndex;
getLogger().logInfo(getClass(), message);
if (removeEmptyGroup && group.getChildAdapter().isEmpty()) {
removeGroup(groupIndex);
}
notifyOnDataSetChanged();
return removedChild;
}
@Override
public final ChildType removeChild(@NonNull final GroupType group, final int index) {
return removeChild(false, group, index);
}
@Override
public final ChildType removeChild(final boolean removeEmptyGroup,
@NonNull final GroupType group, final int index) {
return removeChild(removeEmptyGroup, indexOfGroupOrThrowException(group), index);
}
@Override
public final boolean removeChild(final int groupIndex, @NonNull final ChildType child) {
return removeChild(false, groupIndex, child);
}
@Override
public final boolean removeChild(final boolean removeEmptyGroup, final int groupIndex,
@NonNull final ChildType child) {
ensureNotNull(child, "The child may not be null");
Group<GroupType, ChildType> group = groupAdapter.getItem(groupIndex);
int index = group.getChildAdapter().indexOf(child);
if (index != -1) {
removeChild(removeEmptyGroup, groupIndex, index);
}
return false;
}
@Override
public final boolean removeChild(@NonNull final GroupType group,
@NonNull final ChildType child) {
return removeChild(false, group, child);
}
@Override
public final boolean removeChild(final boolean removeEmptyGroup, @NonNull final GroupType group,
@NonNull final ChildType child) {
return removeChild(removeEmptyGroup, indexOfGroupOrThrowException(group), child);
}
@Override
public final boolean removeAllChildren(
@NonNull final Collection<? extends ChildType> children) {
return removeAllChildren(false, children);
}
@Override
public final boolean removeAllChildren(final boolean removeEmptyGroups,
@NonNull final Collection<? extends ChildType> children) {
boolean result = true;
for (int i = groupAdapter.getCount() - 1; i >= 0; i
result &= removeAllChildren(removeEmptyGroups, i, children);
}
return result;
}
@Override
public final boolean removeAllChildren(final int groupIndex,
@NonNull final Collection<? extends ChildType> children) {
return removeAllChildren(false, groupIndex, children);
}
@Override
public final boolean removeAllChildren(final boolean removeEmptyGroup, final int groupIndex,
@NonNull final Collection<? extends ChildType> children) {
ensureNotNull(children, "The collection may not be null");
boolean result = true;
Group<GroupType, ChildType> group = groupAdapter.getItem(groupIndex);
for (int i = group.getChildAdapter().getCount() - 1; i >= 0; i
result &= removeChild(removeEmptyGroup, groupIndex, i) != null;
}
return result;
}
@Override
public final boolean removeAllChildren(@NonNull final GroupType group,
@NonNull final Collection<? extends ChildType> children) {
return removeAllChildren(false, group, children);
}
@Override
public final boolean removeAllChildren(final boolean removeEmptyGroup,
@NonNull final GroupType group,
@NonNull final Collection<? extends ChildType> children) {
return removeAllChildren(removeEmptyGroup, indexOfGroupOrThrowException(group), children);
}
@SafeVarargs
@Override
public final boolean removeAllChildren(@NonNull final ChildType... children) {
return removeAllChildren(false, children);
}
@SafeVarargs
@Override
public final boolean removeAllChildren(final boolean removeEmptyGroups,
@NonNull final ChildType... children) {
ensureNotNull(children, "The array may not be null");
return removeAllChildren(removeEmptyGroups, Arrays.asList(children));
}
@SafeVarargs
@Override
public final boolean removeAllChildren(final int groupIndex,
@NonNull final ChildType... children) {
return removeAllChildren(false, groupIndex, children);
}
@SafeVarargs
@Override
public final boolean removeAllChildren(final boolean removeEmptyGroup, final int groupIndex,
@NonNull final ChildType... children) {
ensureNotNull(children, "The array may not be null");
return removeAllChildren(removeEmptyGroup, groupIndex, Arrays.asList(children));
}
@SafeVarargs
@Override
public final boolean removeAllChildren(@NonNull final GroupType group,
@NonNull final ChildType... children) {
return removeAllChildren(false, group, children);
}
@SafeVarargs
@Override
public final boolean removeAllChildren(final boolean removeEmptyGroup,
@NonNull final GroupType group,
@NonNull final ChildType... children) {
ensureNotNull(children, "The array may not be null");
return removeAllChildren(removeEmptyGroup, group, Arrays.asList(children));
}
@Override
public final void retainAllChildren(@NonNull final Collection<? extends ChildType> children) {
retainAllChildren(false, children);
}
@Override
public final void retainAllChildren(final boolean removeEmptyGroups,
@NonNull final Collection<? extends ChildType> children) {
for (int i = groupAdapter.getCount() - 1; i >= 0; i
retainAllChildren(removeEmptyGroups, i, children);
}
}
@Override
public final void retainAllChildren(final int groupIndex,
@NonNull final Collection<? extends ChildType> children) {
retainAllChildren(false, groupIndex, children);
}
@Override
public final void retainAllChildren(final boolean removeEmptyGroup, final int groupIndex,
@NonNull final Collection<? extends ChildType> children) {
ensureNotNull(children, "The collection may not be null");
Group<GroupType, ChildType> group = groupAdapter.getItem(groupIndex);
for (int i = group.getChildAdapter().getCount() - 1; i >= 0; i
if (!children.contains(group.getChildAdapter().getItem(i))) {
removeChild(removeEmptyGroup, groupIndex, i);
}
}
}
@Override
public final void retainAllChildren(@NonNull final GroupType group,
@NonNull final Collection<? extends ChildType> children) {
retainAllChildren(false, group, children);
}
@Override
public final void retainAllChildren(final boolean removeEmptyGroup,
@NonNull final GroupType group,
@NonNull final Collection<? extends ChildType> children) {
retainAllChildren(removeEmptyGroup, indexOfGroupOrThrowException(group), children);
}
@SafeVarargs
@Override
public final void retainAllChildren(@NonNull final ChildType... children) {
retainAllChildren(false, children);
}
@SafeVarargs
@Override
public final void retainAllChildren(final boolean removeEmptyGroups,
@NonNull final ChildType... children) {
ensureNotNull(children, "The array may not be null");
retainAllChildren(removeEmptyGroups, Arrays.asList(children));
}
@SafeVarargs
@Override
public final void retainAllChildren(final int groupIndex,
@NonNull final ChildType... children) {
retainAllChildren(false, groupIndex, children);
}
@SafeVarargs
@Override
public final void retainAllChildren(final boolean removeEmptyGroup, final int groupIndex,
@NonNull final ChildType... children) {
ensureNotNull(children, "The array may not be null");
retainAllChildren(removeEmptyGroup, groupIndex, Arrays.asList(children));
}
@SafeVarargs
@Override
public final void retainAllChildren(@NonNull final GroupType group,
@NonNull final ChildType... children) {
retainAllChildren(false, group, children);
}
@SafeVarargs
@Override
public final void retainAllChildren(final boolean removeEmptyGroup,
@NonNull final GroupType group,
@NonNull final ChildType... children) {
ensureNotNull(children, "The array may not be null");
retainAllChildren(removeEmptyGroup, group, Arrays.asList(children));
}
@Override
public final void clearChildren() {
clearChildren(false);
}
@Override
public final void clearChildren(final boolean removeEmptyGroups) {
for (int i = groupAdapter.getCount() - 1; i >= 0; i
clearChildren(removeEmptyGroups, i);
}
}
@Override
public final void clearChildren(final int groupIndex) {
clearChildren(false);
}
@Override
public final void clearChildren(final boolean removeEmptyGroup, final int groupIndex) {
Group<GroupType, ChildType> group = groupAdapter.getItem(groupIndex);
for (int i = group.getChildAdapter().getCount() - 1; i >= 0; i
removeChild(removeEmptyGroup, groupIndex, i);
}
}
@Override
public final void clearChildren(@NonNull final GroupType group) {
clearChildren(false, group);
}
@Override
public final void clearChildren(final boolean removeEmptyGroup,
@NonNull final GroupType group) {
clearChildren(removeEmptyGroup, indexOfGroupOrThrowException(group));
}
@Override
public final Iterator<ChildType> childIterator() {
return getAllChildren().iterator();
}
@Override
public final Iterator<ChildType> childIterator(final int groupIndex) {
return groupAdapter.getItem(groupIndex).getChildAdapter().iterator();
}
@Override
public final Iterator<ChildType> childIterator(@NonNull final GroupType group) {
return childIterator(indexOfGroupOrThrowException(group));
}
@Override
public final ListIterator<ChildType> childListIterator(final int groupIndex) {
return groupAdapter.getItem(groupIndex).getChildAdapter().listIterator();
}
@Override
public final ListIterator<ChildType> childListIterator(@NonNull final GroupType group) {
return childListIterator(indexOfGroupOrThrowException(group));
}
@Override
public final ListIterator<ChildType> childListIterator(final int groupIndex,
final int childIndex) {
return groupAdapter.getItem(groupIndex).getChildAdapter().listIterator(childIndex);
}
@Override
public final ListIterator<ChildType> childListIterator(@NonNull final GroupType group,
final int childIndex) {
return childListIterator(indexOfGroupOrThrowException(group), childIndex);
}
@Override
public final List<ChildType> subListChildren(final int groupIndex, final int start,
final int end) {
return groupAdapter.getItem(groupIndex).getChildAdapter().subList(start, end);
}
@Override
public final List<ChildType> subListChildren(@NonNull final GroupType group, final int start,
final int end) {
return subListChildren(indexOfGroupOrThrowException(group), start, end);
}
@Override
public final Object[] childrenToArray() {
return getAllChildren().toArray();
}
@Override
public final Object[] childrenToArray(final int groupIndex) {
return groupAdapter.getItem(groupIndex).getChildAdapter().toArray();
}
@Override
public final Object[] childrenToArray(@NonNull final GroupType group) {
return childrenToArray(indexOfGroupOrThrowException(group));
}
@Override
public final <T> T[] childrenToArray(@NonNull final T[] array) {
return getAllChildren().toArray(array);
}
@Override
public final <T> T[] childrenToArray(final int groupIndex, @NonNull final T[] array) {
return groupAdapter.getItem(groupIndex).getChildAdapter().toArray(array);
}
@Override
public final <T> T[] childrenToArray(@NonNull final GroupType group, @NonNull final T[] array) {
return childrenToArray(indexOfGroupOrThrowException(group), array);
}
@Override
public final int indexOfChild(@NonNull final ChildType child) {
ensureNotNull(child, "The child may not be null");
for (int i = 0; i < groupAdapter.getCount(); i++) {
if (groupAdapter.getItem(i).getChildAdapter().containsItem(child)) {
return i;
}
}
return -1;
}
@Override
public final int indexOfChild(final int groupIndex, @NonNull final ChildType child) {
ensureNotNull(child, "The child may not be null");
return groupAdapter.getItem(groupIndex).getChildAdapter().indexOf(child);
}
@Override
public final int indexOfChild(@NonNull final GroupType group, @NonNull final ChildType child) {
return indexOfChild(indexOfGroupOrThrowException(group), child);
}
@Override
public final int lastIndexOfChild(@NonNull final ChildType child) {
ensureNotNull(child, "The child may not be null");
for (int i = groupAdapter.getCount() - 1; i >= 0; i
if (groupAdapter.getItem(i).getChildAdapter().containsItem(child)) {
return i;
}
}
return -1;
}
@Override
public final int lastIndexOfChild(final int groupIndex, @NonNull final ChildType child) {
ensureNotNull(child, "The child may not be null");
return groupAdapter.getItem(groupIndex).getChildAdapter().lastIndexOf(child);
}
@Override
public final int lastIndexOfChild(@NonNull final GroupType group,
@NonNull final ChildType child) {
return lastIndexOfChild(indexOfGroupOrThrowException(group), child);
}
@Override
public final boolean containsChild(@NonNull final ChildType child) {
ensureNotNull(child, "The child may not be null");
for (Group<GroupType, ChildType> group : groupAdapter.getAllItems()) {
if (group.getChildAdapter().containsItem(child)) {
return true;
}
}
return false;
}
@Override
public final boolean containsChild(final int groupIndex, @NonNull final ChildType child) {
ensureNotNull(child, "The child may not be null");
return groupAdapter.getItem(groupIndex).getChildAdapter().containsItem(child);
}
@Override
public final boolean containsChild(@NonNull final GroupType group,
@NonNull final ChildType child) {
return containsChild(indexOfGroupOrThrowException(group), child);
}
@Override
public final boolean containsAllChildren(
@NonNull final Collection<? extends ChildType> children) {
return getAllChildren().containsAll(children);
}
@Override
public final boolean containsAllChildren(final int groupIndex,
@NonNull final Collection<? extends ChildType> children) {
ensureNotNull(children, "The collection may not be null");
return groupAdapter.getItem(groupIndex).getChildAdapter().containsAllItems(children);
}
@Override
public final boolean containsAllChildren(@NonNull final GroupType group,
@NonNull final Collection<? extends ChildType> children) {
return containsAllChildren(indexOfGroupOrThrowException(group), children);
}
@SafeVarargs
@Override
public final boolean containsAllChildren(@NonNull final ChildType... children) {
ensureNotNull(children, "The array may not be null");
return containsAllChildren(Arrays.asList(children));
}
@Override
public final int getChildCount() {
return getAllChildren().size();
}
@Override
public final int getChildCount(final int groupIndex) {
return groupAdapter.getItem(groupIndex).getChildAdapter().getCount();
}
@Override
public final int getChildCount(@NonNull final GroupType group) {
return getChildCount(indexOfGroupOrThrowException(group));
}
@Override
public final ChildType getChild(@NonNull final GroupType group, final int childIndex) {
return getChild(indexOfGroupOrThrowException(group), childIndex);
}
@Override
public final ChildType getChild(final int groupIndex, final int childIndex) {
return groupAdapter.getItem(groupIndex).getChildAdapter().getItem(childIndex);
}
@Override
public final List<ChildType> getAllChildren() {
List<ChildType> result = new ArrayList<>();
for (Group<GroupType, ChildType> group : groupAdapter.getAllItems()) {
result.addAll(group.getChildAdapter().getAllItems());
}
return new UnmodifiableList<>(result);
}
@Override
public final List<ChildType> getAllChildren(final int groupIndex) {
return groupAdapter.getItem(groupIndex).getChildAdapter().getAllItems();
}
@Override
public final List<ChildType> getAllChildren(@NonNull final GroupType group) {
return getAllChildren(indexOfGroupOrThrowException(group));
}
@SafeVarargs
@Override
public final boolean containsAllChildren(final int groupIndex,
@NonNull final ChildType... children) {
ensureNotNull(children, "The children may not be null");
return groupAdapter.getItem(groupIndex).getChildAdapter().containsAllItems(children);
}
@SafeVarargs
@Override
public final boolean containsAllChildren(@NonNull final GroupType group,
@NonNull final ChildType... children) {
return containsAllChildren(indexOfGroupOrThrowException(group), children);
}
@Override
public final boolean isGroupExpanded(final int index) {
return getGroupAdapter().getItem(index).isExpanded();
}
@Override
public final boolean isGroupExpanded(@NonNull final GroupType group) {
return isGroupExpanded(indexOfGroup(group));
}
@Override
public final GroupType getFirstExpandedGroup() {
int index = getFirstExpandedGroupIndex();
if (index != -1) {
return getGroup(index);
}
return null;
}
@Override
public final int getFirstExpandedGroupIndex() {
for (int i = 0; i < getGroupCount(); i++) {
if (isGroupExpanded(i)) {
return i;
}
}
return -1;
}
@Override
public final GroupType getLastExpandedGroup() {
int index = getLastExpandedGroupIndex();
if (index != -1) {
return getGroup(index);
}
return null;
}
@Override
public final int getLastExpandedGroupIndex() {
for (int i = getGroupCount() - 1; i >= 0; i
if (isGroupExpanded(i)) {
return i;
}
}
return -1;
}
@Override
public final GroupType getFirstCollapsedGroup() {
int index = getFirstCollapsedGroupIndex();
if (index != -1) {
return getGroup(index);
}
return null;
}
@Override
public final int getFirstCollapsedGroupIndex() {
for (int i = 0; i < getGroupCount(); i++) {
if (!isGroupExpanded(i)) {
return i;
}
}
return -1;
}
@Override
public final GroupType getLastCollapsedGroup() {
int index = getLastCollapsedGroupIndex();
if (index != -1) {
return getGroup(index);
}
return null;
}
@Override
public final int getLastCollapsedGroupIndex() {
for (int i = getGroupCount() - 1; i >= 0; i
if (!isGroupExpanded(i)) {
return i;
}
}
return -1;
}
@Override
public final List<GroupType> getExpandedGroups() {
List<GroupType> expandedGroups = new ArrayList<>();
for (int i = 0; i < getGroupCount(); i++) {
if (isGroupExpanded(i)) {
expandedGroups.add(getGroup(i));
}
}
return new UnmodifiableList<>(expandedGroups);
}
@Override
public final List<Integer> getExpandedGroupIndices() {
List<Integer> expandedGroupIndices = new ArrayList<>();
for (int i = 0; i < getGroupCount(); i++) {
if (isGroupExpanded(i)) {
expandedGroupIndices.add(i);
}
}
return new UnmodifiableList<>(expandedGroupIndices);
}
@Override
public final List<GroupType> getCollapsedGroups() {
List<GroupType> collapsedGroups = new ArrayList<>();
for (int i = 0; i < getGroupCount(); i++) {
if (!isGroupExpanded(i)) {
collapsedGroups.add(getGroup(i));
}
}
return new UnmodifiableList<>(collapsedGroups);
}
@Override
public final List<Integer> getCollapsedGroupIndices() {
List<Integer> collapsedGroupIndices = new ArrayList<>();
for (int i = 0; i < getGroupCount(); i++) {
if (isGroupExpanded(i)) {
collapsedGroupIndices.add(i);
}
}
return new UnmodifiableList<>(collapsedGroupIndices);
}
@Override
public final int getExpandedGroupCount() {
return getExpandedGroups().size();
}
@Override
public final void setGroupExpanded(@NonNull final GroupType group, final boolean expanded) {
setGroupExpanded(indexOfGroupOrThrowException(group), expanded);
}
@Override
public final void setGroupExpanded(final int index, final boolean expanded) {
getGroupAdapter().getItem(index).setExpanded(expanded);
if (getAdapterView() != null) {
if (isNotifiedOnChange()) {
if (expanded) {
getAdapterView().expandGroup(index);
} else {
getAdapterView().collapseGroup(index);
}
} else {
adapterViewTainted = true;
}
}
}
@Override
public final boolean triggerGroupExpansion(@NonNull final GroupType group) {
return triggerGroupExpansion(indexOfGroupOrThrowException(group));
}
@Override
public final boolean triggerGroupExpansion(final int index) {
if (isGroupExpanded(index)) {
setGroupExpanded(index, false);
return false;
} else {
setGroupExpanded(index, true);
return true;
}
}
@Override
public final void setAllGroupsExpanded(final boolean expanded) {
for (int i = 0; i < getGroupCount(); i++) {
setGroupExpanded(i, expanded);
}
}
@Override
public final void triggerAllGroupExpansions() {
for (int i = 0; i < getGroupCount(); i++) {
triggerGroupExpansion(i);
}
}
@Override
public final boolean isGroupExpansionTriggeredOnClick() {
return triggerGroupExpansionOnClick;
}
@Override
public final void triggerGroupExpansionOnClick(final boolean triggerGroupExpansionOnClick) {
this.triggerGroupExpansionOnClick = triggerGroupExpansionOnClick;
String message = "Groups are now " + (triggerGroupExpansionOnClick ? "" : "not ") +
"expanded on click";
getLogger().logDebug(getClass(), message);
}
@Override
public final void attach(@NonNull final ExpandableListView adapterView) {
ensureNotNull(adapterView, "The adapter view may not be null");
detach();
this.adapterView = adapterView;
this.adapterView.setAdapter(this);
this.adapterView.setOnGroupClickListener(createAdapterViewOnGroupClickListener());
this.adapterView.setOnChildClickListener(createAdapterViewOnChildClickListener());
this.adapterView.setOnItemClickListener(createAdapterViewOnItemClickListener());
this.adapterView.setOnItemLongClickListener(createAdapterViewOnItemLongClickListener());
syncAdapterView();
String message = "Attached adapter to view \"" + adapterView + "\"";
getLogger().logDebug(getClass(), message);
}
@Override
public final void detach() {
if (adapterView != null) {
if (adapterView.getAdapter() == this) {
adapterView.setAdapter((android.widget.ExpandableListAdapter) null);
String message = "Detached adapter from view \"" + adapterView + "\"";
getLogger().logDebug(getClass(), message);
} else {
String message = "Adapter has not been detached, because the " +
"adapter of the corresponding view has been changed " + "in the meantime";
getLogger().logVerbose(getClass(), message);
}
adapterView = null;
} else {
String message = "Adapter has not been detached, because it has not " +
"been attached to a view yet";
getLogger().logVerbose(getClass(), message);
}
}
@Override
public final void notifyDataSetChanged() {
super.notifyDataSetChanged();
if (adapterViewTainted) {
syncAdapterView();
}
adapterViewTainted = false;
}
@Override
public final long getChildId(final int groupIndex, final int childIndex) {
return childIndex;
}
@Override
public final int getChildrenCount(final int groupIndex) {
return groupAdapter.getItem(groupIndex).getChildAdapter().getCount();
}
@Override
public final int getGroupCount() {
return groupAdapter.getCount();
}
@Override
public final long getGroupId(final int groupIndex) {
return groupIndex;
}
@Override
public final boolean hasStableIds() {
return true;
}
@Override
public final View getGroupView(final int groupIndex, final boolean isExpanded,
@Nullable final View convertView,
@Nullable final ViewGroup parent) {
if (adapterView == null) {
throw new IllegalStateException(
"Adapter must be attached to an ExpandableListView using its attach-method");
}
View view = convertView;
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
view = getDecorator().inflateGroupView(inflater, parent, getGroup(groupIndex));
String message = "Inflated view to visualize the group at index " + groupIndex;
getLogger().logVerbose(getClass(), message);
}
applyDecoratorOnGroup(getContext(), view, groupIndex);
return view;
}
@Override
public final View getChildView(final int groupIndex, final int childIndex,
final boolean isLastChild, @Nullable final View convertView,
@Nullable final ViewGroup parent) {
if (adapterView == null) {
throw new IllegalStateException(
"Adapter must be attached to an ExpandableListView using its attach-method");
}
View view = convertView;
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
view = getDecorator()
.inflateChildView(inflater, parent, getChild(groupIndex, childIndex));
String message = "Inflated view to visualize the child at index " + childIndex +
" of the group at index " + groupIndex;
getLogger().logVerbose(getClass(), message);
}
applyDecoratorOnChild(getContext(), view, groupIndex, childIndex);
return view;
}
@Override
public final void onSaveInstanceState(@NonNull final Bundle outState,
@NonNull final String key) {
Bundle savedState = new Bundle();
groupAdapter.onSaveInstanceState(savedState, GROUP_ADAPTER_BUNDLE_KEY);
if (savedState.containsKey(GROUP_ADAPTER_BUNDLE_KEY)) {
for (int i = 0; i < groupAdapter.getCount(); i++) {
MultipleChoiceListAdapter<ChildType> childAdapter =
groupAdapter.getItem(i).getChildAdapter();
if (childAdapter != null) {
String childAdapterKey = String.format(CHILD_ADAPTER_BUNDLE_KEY, i);
childAdapter.onSaveInstanceState(savedState, childAdapterKey);
}
}
}
if (adapterView != null) {
AdapterViewUtil
.onSaveInstanceState(adapterView, savedState, ADAPTER_VIEW_STATE_BUNDLE_KEY);
} else {
String message = "The state of the adapter view can not be stored, because the " +
"adapter has not been attached to a view";
getLogger().logWarn(getClass(), message);
}
savedState.putBoolean(ALLOW_DUPLICATE_CHILDREN_BUNDLE_KEY, areDuplicateChildrenAllowed());
savedState.putBoolean(TRIGGER_GROUP_EXPANSION_ON_CLICK_BUNDLE_KEY,
isGroupExpansionTriggeredOnClick());
savedState.putInt(LOG_LEVEL_BUNDLE_KEY, getLogLevel().getRank());
outState.putBundle(key, savedState);
getLogger().logDebug(getClass(), "Saved instance state");
}
@Override
public final void onRestoreInstanceState(@NonNull final Bundle savedInstanceState,
@NonNull final String key) {
Bundle savedState = savedInstanceState.getBundle(key);
if (savedState != null) {
if (savedState.containsKey(GROUP_ADAPTER_BUNDLE_KEY)) {
groupAdapter.onRestoreInstanceState(savedState, GROUP_ADAPTER_BUNDLE_KEY);
for (int i = 0; i < groupAdapter.getCount(); i++) {
String childAdapterKey = String.format(CHILD_ADAPTER_BUNDLE_KEY, i);
if (savedState.containsKey(childAdapterKey)) {
MultipleChoiceListAdapter<ChildType> childAdapter = createChildAdapter();
childAdapter.onRestoreInstanceState(savedState, childAdapterKey);
Group<GroupType, ChildType> group = groupAdapter.getItem(i);
if (group != null) {
group.setChildAdapter(childAdapter);
}
}
}
}
if (savedState.containsKey(ADAPTER_VIEW_STATE_BUNDLE_KEY) && adapterView != null) {
AdapterViewUtil.onRestoreInstanceState(adapterView, savedState,
ADAPTER_VIEW_STATE_BUNDLE_KEY);
}
allowDuplicateChildren(savedState.getBoolean(ALLOW_DUPLICATE_CHILDREN_BUNDLE_KEY));
triggerGroupExpansionOnClick(
savedState.getBoolean(TRIGGER_GROUP_EXPANSION_ON_CLICK_BUNDLE_KEY));
setLogLevel(LogLevel.fromRank(savedState.getInt(LOG_LEVEL_BUNDLE_KEY)));
notifyDataSetChanged();
getLogger().logDebug(getClass(), "Restored instance state");
} else {
getLogger().logWarn(getClass(),
"Saved instance state does not contain bundle with key \"" + key + "\"");
}
}
@CallSuper
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (allowDuplicateChildren ? 1231 : 1237);
result = prime * result + (triggerGroupExpansionOnClick ? 1231 : 1237);
result = prime * result + groupAdapter.hashCode();
result = prime * result + getLogLevel().getRank();
return result;
}
@CallSuper
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractExpandableListAdapter<?, ?, ?> other = (AbstractExpandableListAdapter<?, ?, ?>) obj;
if (allowDuplicateChildren != other.allowDuplicateChildren)
return false;
if (triggerGroupExpansionOnClick != other.triggerGroupExpansionOnClick)
return false;
if (!groupAdapter.equals(other.groupAdapter))
return false;
if (!getLogLevel().equals(other.getLogLevel()))
return false;
return true;
}
@Override
public abstract AbstractExpandableListAdapter<GroupType, ChildType, DecoratorType> clone()
throws CloneNotSupportedException;
}
|
package be.ibridge.kettle.job.entry.shell;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.commons.vfs.FileObject;
import org.eclipse.swt.widgets.Shell;
import org.w3c.dom.Node;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Result;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleXMLException;
import be.ibridge.kettle.core.logging.Log4jFileAppender;
import be.ibridge.kettle.core.util.EnvUtil;
import be.ibridge.kettle.core.util.StreamLogger;
import be.ibridge.kettle.core.util.StringUtil;
import be.ibridge.kettle.core.vfs.KettleVFS;
import be.ibridge.kettle.job.Job;
import be.ibridge.kettle.job.JobMeta;
import be.ibridge.kettle.job.entry.JobEntryBase;
import be.ibridge.kettle.job.entry.JobEntryDialogInterface;
import be.ibridge.kettle.job.entry.JobEntryInterface;
import be.ibridge.kettle.repository.Repository;
/**
* Shell type of Job Entry. You can define shell scripts to be executed in a Job.
*
* @author Matt
* @since 01-10-2003, rewritten on 18-06-2004
*
*/
public class JobEntryShell extends JobEntryBase implements Cloneable, JobEntryInterface
{
private String filename;
public String arguments[];
public boolean argFromPrevious;
public boolean setLogfile;
public String logfile, logext;
public boolean addDate, addTime;
public int loglevel;
public boolean execPerRow;
public JobEntryShell(String name)
{
super(name, "");
setType(JobEntryInterface.TYPE_JOBENTRY_SHELL);
}
public JobEntryShell()
{
this("");
clear();
}
public JobEntryShell(JobEntryBase jeb)
{
super(jeb);
setType(JobEntryInterface.TYPE_JOBENTRY_SHELL);
}
public Object clone()
{
JobEntryShell je = (JobEntryShell) super.clone();
return je;
}
public String getXML()
{
StringBuffer retval = new StringBuffer(300);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("filename", filename));
retval.append(" ").append(XMLHandler.addTagValue("arg_from_previous", argFromPrevious));
retval.append(" ").append(XMLHandler.addTagValue("exec_per_row", execPerRow));
retval.append(" ").append(XMLHandler.addTagValue("set_logfile", setLogfile));
retval.append(" ").append(XMLHandler.addTagValue("logfile", logfile));
retval.append(" ").append(XMLHandler.addTagValue("logext", logext));
retval.append(" ").append(XMLHandler.addTagValue("add_date", addDate));
retval.append(" ").append(XMLHandler.addTagValue("add_time", addTime));
retval.append(" ").append(XMLHandler.addTagValue("loglevel", LogWriter.getLogLevelDesc(loglevel)));
if (arguments!=null)
for (int i=0;i<arguments.length;i++)
{
retval.append(" ").append(XMLHandler.addTagValue("argument"+i, arguments[i]));
}
return retval.toString();
}
public void loadXML(Node entrynode, ArrayList databases, Repository rep) throws KettleXMLException
{
try
{
super.loadXML(entrynode, databases);
setFileName( XMLHandler.getTagValue(entrynode, "filename") );
argFromPrevious = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "arg_from_previous") );
execPerRow = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "exec_per_row") );
setLogfile = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "set_logfile") );
addDate = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "add_date") );
addTime = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "add_time") );
logfile = XMLHandler.getTagValue(entrynode, "logfile");
logext = XMLHandler.getTagValue(entrynode, "logext");
loglevel = LogWriter.getLogLevel( XMLHandler.getTagValue(entrynode, "loglevel"));
// How many arguments?
int argnr = 0;
while ( XMLHandler.getTagValue(entrynode, "argument"+argnr)!=null) argnr++;
arguments = new String[argnr];
// Read them all...
for (int a=0;a<argnr;a++) arguments[a]=XMLHandler.getTagValue(entrynode, "argument"+a);
}
catch(KettleException e)
{
throw new KettleXMLException("Unable to load job entry of type 'shell' from XML node", e);
}
}
// Load the jobentry from repository
public void loadRep(Repository rep, long id_jobentry, ArrayList databases)
throws KettleException
{
try
{
super.loadRep(rep, id_jobentry, databases);
setFileName( rep.getJobEntryAttributeString(id_jobentry, "file_name") );
argFromPrevious = rep.getJobEntryAttributeBoolean(id_jobentry, "arg_from_previous");
execPerRow = rep.getJobEntryAttributeBoolean(id_jobentry, "exec_per_row");
setLogfile = rep.getJobEntryAttributeBoolean(id_jobentry, "set_logfile");
addDate = rep.getJobEntryAttributeBoolean(id_jobentry, "add_date");
addTime = rep.getJobEntryAttributeBoolean(id_jobentry, "add_time");
logfile = rep.getJobEntryAttributeString(id_jobentry, "logfile");
logext = rep.getJobEntryAttributeString(id_jobentry, "logext");
loglevel = LogWriter.getLogLevel( rep.getJobEntryAttributeString(id_jobentry, "loglevel") );
// How many arguments?
int argnr = rep.countNrJobEntryAttributes(id_jobentry, "argument");
arguments = new String[argnr];
// Read them all...
for (int a=0;a<argnr;a++)
{
arguments[a]= rep.getJobEntryAttributeString(id_jobentry, a, "argument");
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to load job entry of type 'shell' from the repository with id_jobentry="+id_jobentry, dbe);
}
}
// Save the attributes of this job entry
public void saveRep(Repository rep, long id_job)
throws KettleException
{
try
{
super.saveRep(rep, id_job);
rep.saveJobEntryAttribute(id_job, getID(), "file_name", filename);
rep.saveJobEntryAttribute(id_job, getID(), "arg_from_previous", argFromPrevious);
rep.saveJobEntryAttribute(id_job, getID(), "exec_per_row", execPerRow);
rep.saveJobEntryAttribute(id_job, getID(), "set_logfile", setLogfile);
rep.saveJobEntryAttribute(id_job, getID(), "add_date", addDate);
rep.saveJobEntryAttribute(id_job, getID(), "add_time", addTime);
rep.saveJobEntryAttribute(id_job, getID(), "logfile", logfile);
rep.saveJobEntryAttribute(id_job, getID(), "logext", logext);
rep.saveJobEntryAttribute(id_job, getID(), "loglevel", LogWriter.getLogLevelDesc(loglevel));
// save the arguments...
if (arguments!=null)
{
for (int i=0;i<arguments.length;i++)
{
rep.saveJobEntryAttribute(id_job, getID(), i, "argument", arguments[i]);
}
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to save job entry of type 'shell' to the repository", dbe);
}
}
public void clear()
{
super.clear();
filename=null;
arguments=null;
argFromPrevious=false;
addDate=false;
addTime=false;
logfile=null;
logext=null;
setLogfile=false;
execPerRow=false;
}
public void setFileName(String n)
{
filename=n;
}
/**
* @deprecated use getFilename() instead
* @return the filename
*/
public String getFileName()
{
return filename;
}
public String getFilename()
{
return filename;
}
public String getRealFilename()
{
return StringUtil.environmentSubstitute(getFilename());
}
public String getLogFilename()
{
String retval="";
if (setLogfile)
{
retval+=logfile;
Calendar cal = Calendar.getInstance();
if (addDate)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
retval+="_"+sdf.format(cal.getTime());
}
if (addTime)
{
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
retval+="_"+sdf.format(cal.getTime());
}
if (logext!=null && logext.length()>0)
{
retval+="."+logext;
}
}
return retval;
}
public Result execute(Result result, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
Log4jFileAppender appender = null;
int backupLogLevel = log.getLogLevel();
if (setLogfile)
{
try
{
appender = LogWriter.createFileAppender(StringUtil.environmentSubstitute(getLogFilename()), true);
}
catch(KettleException e)
{
log.logError(toString(), "Unable to open file appender for file ["+getLogFilename()+"] : "+e.toString());
log.logError(toString(), Const.getStackTracker(e));
result.setNrErrors(1);
result.setResult(false);
return result;
}
log.addAppender(appender);
log.setLogLevel(loglevel);
}
result.setEntryNr( nr );
int iteration = 0;
String args[] = arguments;
Row resultRow = null;
boolean first = true;
List rows = result.getRows();
log.logDetailed(toString(), "Found "+(rows!=null?rows.size():0)+" previous result rows");
while( ( first && !execPerRow ) || ( execPerRow && rows!=null && iteration<rows.size() && result.getNrErrors()==0 ) )
{
first=false;
if (rows!=null && execPerRow)
{
resultRow = (Row) rows.get(iteration);
}
else
{
resultRow = null;
}
List cmdRows = null;
if (execPerRow) // Execute for each input row
{
if (argFromPrevious) // Copy the input row to the (command line) arguments
{
if (resultRow!=null)
{
args = new String[resultRow.size()];
for (int i=0;i<resultRow.size();i++)
{
args[i] = resultRow.getValue(i).getString();
}
}
}
else
{
// Just pass a single row
ArrayList newList = new ArrayList();
newList.add(resultRow);
cmdRows = newList;
}
}
else
{
if (argFromPrevious)
{
// Only put the first Row on the arguments
args = null;
if (resultRow!=null)
{
args = new String[resultRow.size()];
for (int i=0;i<resultRow.size();i++)
{
args[i] = resultRow.getValue(i).getString();
}
}
}
else
{
// Keep it as it was...
cmdRows = rows;
}
}
executeShell(result, cmdRows, args);
iteration++;
}
if (setLogfile)
{
if (appender!=null)
{
log.removeAppender(appender);
appender.close();
}
log.setLogLevel(backupLogLevel);
}
return result;
}
private void executeShell(Result result, List cmdRows, String[] args)
{
LogWriter log = LogWriter.getInstance();
try
{
// What's the exact command?
String cmd[] = null;
String base[] = null;
log.logBasic(toString(), "Running on platform : "+Const.getOS());
FileObject fileObject = null;
String realFilename = StringUtil.environmentSubstitute(getFilename());
fileObject = KettleVFS.getFileObject(realFilename);
if( Const.getOS().equals( "Windows 95" ) )
{
base = new String[] { "command.com", "/C" };
}
else
if( Const.getOS().startsWith( "Windows" ) )
{
base = new String[] { "cmd.exe", "/C" };
}
else
{
base = new String[] { KettleVFS.getFilename(fileObject) };
}
// Construct the arguments...
if (argFromPrevious && cmdRows!=null)
{
ArrayList cmds = new ArrayList();
// Add the base command...
for (int i=0;i<base.length;i++) cmds.add(base[i]);
if( Const.getOS().equals( "Windows 95" ) ||
Const.getOS().startsWith( "Windows" ) )
{
// for windows all arguments including the command itself need to be
// included in 1 argument to cmd/command.
StringBuffer cmdline = new StringBuffer(300);
cmdline.append('"');
cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\""));
// Add the arguments from previous results...
for (int i=0;i<cmdRows.size();i++) // Normally just one row, but once in a while to remain compatible we have multiple.
{
Row r = (Row)cmdRows.get(i);
for (int j=0;j<r.size();j++)
{
cmdline.append(' ');
cmdline.append(r.getValue(j).getString());
}
}
cmdline.append('"');
cmds.add(cmdline.toString());
}
else
{
// Add the arguments from previous results...
for (int i=0;i<cmdRows.size();i++) // Normally just one row, but once in a while to remain compatible we have multiple.
{
Row r = (Row)cmdRows.get(i);
for (int j=0;j<r.size();j++)
{
cmds.add(r.getValue(j).getString());
}
}
}
cmd = (String[]) cmds.toArray(new String[cmds.size()]);
}
else
if (args!=null)
{
ArrayList cmds = new ArrayList();
// Add the base command...
for (int i=0;i<base.length;i++) cmds.add(base[i]);
if( Const.getOS().equals( "Windows 95" ) ||
Const.getOS().startsWith( "Windows" ) )
{
// for windows all arguments including the command itself need to be
// included in 1 argument to cmd/command.
StringBuffer cmdline = new StringBuffer(300);
cmdline.append('"');
cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\""));
for (int i=0;i<args.length;i++)
{
cmdline.append(' ');
cmdline.append(args[i]);
}
cmdline.append('"');
cmds.add(cmdline.toString());
}
else
{
for (int i=0;i<args.length;i++)
{
cmds.add(args[i]);
}
}
cmd = (String[]) cmds.toArray(new String[cmds.size()]);
}
if (log.isBasic())
{
StringBuffer command = new StringBuffer();
for (int i=0;i<cmd.length;i++)
{
if (i>0) command.append(' ');
command.append(cmd[i]);
}
log.logBasic(toString(), "Executing command : "+command.toString());
}
// Launch the script!
log.logDetailed(toString(), "Passing "+(cmd.length-1)+" arguments to command : ["+cmd[0]+"]");
// Build the environment variable list...
Runtime runtime = java.lang.Runtime.getRuntime();
Process proc = runtime.exec(cmd,
EnvUtil.getEnvironmentVariablesForRuntimeExec());
// any error message?
StreamLogger errorLogger = new
StreamLogger(proc.getErrorStream(), toString()+" (stderr)");
// any output?
StreamLogger outputLogger = new
StreamLogger(proc.getInputStream(), toString()+" (stdout)");
// kick them off
new Thread(errorLogger).start();
new Thread(outputLogger).start();
proc.waitFor();
log.logDetailed(toString(), "command ["+cmd[0]+"] has finished");
// What's the exit status?
result.setExitStatus( proc.exitValue() );
if (result.getExitStatus()!=0)
{
log.logDetailed(toString(), "Exit status of shell ["+StringUtil.environmentSubstitute(getFileName())+"] was "+result.getExitStatus());
result.setNrErrors(1);
}
}
catch(IOException ioe)
{
log.logError(toString(), "Error running shell ["+StringUtil.environmentSubstitute(getFileName())+"] : "+ioe.toString());
result.setNrErrors(1);
}
catch(InterruptedException ie)
{
log.logError(toString(), "Shell ["+StringUtil.environmentSubstitute(getFileName())+"] was interupted : "+ie.toString());
result.setNrErrors(1);
}
catch(Exception e)
{
log.logError(toString(), "Unexpected error running shell ["+StringUtil.environmentSubstitute(getFileName())+"] : "+e.toString());
result.setNrErrors(1);
}
if (result.getNrErrors() > 0)
{
result.setResult( false );
}
else
{
result.setResult( true );
}
}
private String optionallyQuoteField(String field, String quote)
{
if (Const.isEmpty(field) || Const.isEmpty(quote)) return null;
// If the field already contains quotes, we don't touch it anymore, just return the same string...
// also return it if no spaces are found
if (field.indexOf(quote)>=0 || field.indexOf(' ')<0 )
{
return field;
}
else
{
return quote + field + quote;
}
}
public boolean evaluates()
{
return true;
}
public boolean isUnconditional()
{
return true;
}
public JobEntryDialogInterface getDialog(Shell shell,JobEntryInterface jei,JobMeta jobMeta,String jobName,Repository rep) {
return new JobEntryShellDialog(shell,this);
}
}
|
package cat.mobilejazz.utilities.format;
import java.util.Iterator;
public class StringFormatter {
private static final String INDENT_LITERAL_32 = " ";
public static StringBuilder appendWS(StringBuilder b, int num) {
return b.append(INDENT_LITERAL_32, 0, num);
}
public static <V> CharSequence printIterable(StringBuilder output, Iterable<V> iterable,
CharSequence delimiter, ObjectPrinter<V> printer) {
Iterator<V> i = iterable.iterator();
if (i.hasNext()) {
output.append(printer.toString(i.next()));
}
while (i.hasNext()) {
output.append(delimiter);
output.append(printer.toString(i.next()));
}
return output;
}
@SuppressWarnings("unchecked")
public static <V> CharSequence printIterable(StringBuilder output, Iterable<V> iterable,
CharSequence delimiter) {
return printIterable(output, iterable, delimiter,
(ObjectPrinter<V>) DefaultObjectPrinter.getInstance());
}
public static <V> CharSequence printIterable(StringBuilder output, Iterable<V> iterable) {
return printIterable(output, iterable, ", ");
}
public static <V> CharSequence printIterable(StringBuilder output, CharSequence delimiter,
ObjectPrinter<V> printer, V... array) {
if (array.length > 0) {
output.append(printer.toString(array[0]));
}
for (int i = 1; i < array.length; i++) {
output.append(delimiter);
output.append(printer.toString(array[i]));
}
return output;
}
@SuppressWarnings("unchecked")
public static <V> CharSequence printIterable(StringBuilder output, CharSequence delimiter,
V... array) {
return printIterable(output, delimiter,
(ObjectPrinter<V>) DefaultObjectPrinter.getInstance(), array);
}
public static <V> CharSequence printIterable(StringBuilder output, V... array) {
return printIterable(output, ", ", array);
}
public static <V> CharSequence printIterable(Iterable<V> iterable,
CharSequence delimiter, ObjectPrinter<V> printer) {
return printIterable(new StringBuilder(), iterable, delimiter, printer);
}
public static <V> CharSequence printIterable(Iterable<V> iterable,
CharSequence delimiter) {
return printIterable(new StringBuilder(), iterable, delimiter);
}
public static <V> CharSequence printIterable(Iterable<V> iterable) {
return printIterable(new StringBuilder(), iterable);
}
public static <V> CharSequence printIterable(CharSequence delimiter,
ObjectPrinter<V> printer, V... array) {
return printIterable(new StringBuilder(), delimiter, printer, array);
}
public static <V> CharSequence printIterable(CharSequence delimiter,
V... array) {
return printIterable(new StringBuilder(), delimiter, array);
}
public static <V> CharSequence printIterable(V... array) {
return printIterable(new StringBuilder(), array);
}
}
|
package org.jboss.wsf.stack.cxf.client.configuration;
import java.net.URL;
import java.util.Map;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.jboss.wsf.stack.cxf.client.util.SpringUtils;
/**
* JBossWS version of @see{org.apache.cxf.BusFactory}. This detects if Spring is available or not when the default
* createBus() method is invoked; if Spring libraries are available in the classpath, an instance of
* @see{org.jboss.wsf.stack.cxf.client.configuration.JBossWSSpringBusFactory} is internally used for
* creating the bus. On the contrary, an instance of @see{org.jboss.wsf.stack.cxf.client.configuration.JBossWSNonSpringBusFactory}
* is internally used when Spring is not available in the classpath.
* Users willing to create a bus factory given a parent @see{org.springframework.context.ApplicationContext} should
* directly create an instance of @see{org.jboss.wsf.stack.cxf.client.configuration.JBossWSSpringBusFactory}.
*
* @author alessio.soldano@jboss.com
* @since 16-Jun-2010
*
*/
public class JBossWSBusFactory extends BusFactory
{
private JBossWSSpringBusFactory springBusFactory;
private JBossWSNonSpringBusFactory nonSpringBusFactory;
@Override
public Bus createBus()
{
if (isSpringAvailable())
{
return getSpringBusFactory().createBus();
}
else
{
return getNonSpringBusFactory().createBus();
}
}
private boolean isSpringAvailable() {
// Spring is available iff:
// 1) TCCL has Spring classes
// 2) the SpringBusFactory has already been loaded or the defining classloader can load that
return (SpringUtils.isSpringAvailable() && (springBusFactory != null || SpringUtils.isSpringAvailable(this.getClass().getClassLoader())));
}
/** JBossWSSpringBusFactory methods **/
public Bus createBus(String cfgFile)
{
return getSpringBusFactory().createBus(cfgFile, true);
}
public Bus createBus(String cfgFiles[])
{
return getSpringBusFactory().createBus(cfgFiles, true);
}
public Bus createBus(String cfgFile, boolean includeDefaults)
{
return getSpringBusFactory().createBus(cfgFile, includeDefaults);
}
public Bus createBus(String cfgFiles[], boolean includeDefaults)
{
return getSpringBusFactory().createBus(cfgFiles, includeDefaults);
}
public Bus createBus(URL url)
{
return getSpringBusFactory().createBus(url);
}
public Bus createBus(URL[] urls)
{
return getSpringBusFactory().createBus(urls);
}
public Bus createBus(URL url, boolean includeDefaults)
{
return getSpringBusFactory().createBus(url, includeDefaults);
}
public Bus createBus(URL[] urls, boolean includeDefaults)
{
return getSpringBusFactory().createBus(urls, includeDefaults);
}
/** JBossWSNonSpringBusFactory methods **/
@SuppressWarnings("rawtypes")
public Bus createBus(Map<Class, Object> extensions)
{
return getNonSpringBusFactory().createBus(extensions);
}
@SuppressWarnings("rawtypes")
public Bus createBus(Map<Class, Object> extensions, Map<String, Object> properties)
{
return getNonSpringBusFactory().createBus(extensions, properties);
}
public JBossWSSpringBusFactory getSpringBusFactory()
{
if (springBusFactory == null)
{
springBusFactory = new JBossWSSpringBusFactory();
}
return springBusFactory;
}
public JBossWSNonSpringBusFactory getNonSpringBusFactory()
{
if (nonSpringBusFactory == null)
{
nonSpringBusFactory = new JBossWSNonSpringBusFactory();
}
return nonSpringBusFactory;
}
/**
* Gets (and internally sets) the default bus after having set the thread
* context class loader to the provided one (which affects the Bus
* construction if it's not been created yet). The former thread context
* class loader is restored before returning to the caller.
*
* @param contextClassLoader
* @return the default bus
*/
public static Bus getDefaultBus(ClassLoader contextClassLoader)
{
ClassLoader origClassLoader = SecurityActions.getContextClassLoader();
try
{
SecurityActions.setContextClassLoader(contextClassLoader);
return BusFactory.getDefaultBus();
}
finally
{
SecurityActions.setContextClassLoader(origClassLoader);
}
}
}
|
/**
Convert a String containing space-separated feature-name floating-point-value pairs
into a FeatureVector. For example:
<pre>length=12 width=1.75 blue temperature=-17.2</pre>
Features without a corresponding value (ie those not including the character "=",
such as the feature <code>blue</code> here) will be set to 1.0.
<p>If a feature occurs more than once in the input string, the values of each
occurrence will be added.</p>
@author David Mimno and Andrew McCallum
*/
package cc.mallet.pipe;
import java.io.*;
import cc.mallet.types.Alphabet;
import cc.mallet.types.Instance;
import cc.mallet.types.FeatureVector;
public class FeatureValueString2FeatureVector extends Pipe implements Serializable {
public FeatureValueString2FeatureVector (Alphabet dataDict) {
super (dataDict, null);
}
public FeatureValueString2FeatureVector () {
super(new Alphabet(), null);
}
public Instance pipe (Instance carrier) {
String[] fields = carrier.getData().toString().split("\\s+");
int numFields = fields.length;
Object[] featureNames = new Object[numFields];
double[] featureValues = new double[numFields];
for (int i = 0; i < numFields; i++) {
if (fields[i].contains("=")) {
String[] subFields = fields[i].split("=");
featureNames[i] = subFields[0];
featureValues[i] = Double.parseDouble(subFields[1]);
}
else {
featureNames[i] = fields[i];
featureValues[i] = 1.0;
}
}
carrier.setData(new FeatureVector(getDataAlphabet(), featureNames, featureValues));
return carrier;
}
}
|
package com.codenvy.analytics.api;
import com.codenvy.analytics.datamodel.ValueData;
import com.codenvy.analytics.metrics.MetricNotFoundException;
import com.codenvy.analytics.metrics.Parameters;
import com.codenvy.analytics.services.view.CSVFileCleaner;
import com.codenvy.analytics.services.view.SectionData;
import com.codenvy.analytics.services.view.ViewBuilder;
import com.codenvy.analytics.services.view.ViewData;
import com.codenvy.analytics.util.Utils;
import com.codenvy.api.analytics.MetricHandler;
import com.codenvy.api.analytics.shared.dto.MetricValueDTO;
import com.codenvy.dto.server.JsonArrayImpl;
import com.google.inject.Inject;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.security.RolesAllowed;
import javax.inject.Singleton;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author Alexander Reshetnyak
* @author Anatoliy Bazko
*/
@Path("view")
@Singleton
public class View {
private static final Logger LOG = LoggerFactory.getLogger(View.class);
private final ViewBuilder viewBuilder;
private final MetricHandler metricHandler;
private final CSVFileCleaner csvFileCleanerHolder;
@Inject
public View(ViewBuilder viewBuilder,
MetricHandler metricHandler,
CSVFileCleaner csvFileCleanerHolder) {
this.viewBuilder = viewBuilder;
this.metricHandler = metricHandler;
this.csvFileCleanerHolder = csvFileCleanerHolder;
}
@GET
@Path("metric/{name}")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({"user", "system/admin", "system/manager"})
public Response getMetricValue(@PathParam("name") String metricName,
@QueryParam("page") String page,
@QueryParam("per_page") String perPage,
@Context UriInfo uriInfo,
@Context SecurityContext securityContext) {
try {
Map<String, String> context = Utils.extractParams(uriInfo,
page,
perPage,
securityContext);
MetricValueDTO value = metricHandler.getValue(metricName, context, uriInfo);
return Response.status(Response.Status.OK).entity(value).build();
} catch (MetricNotFoundException e) {
LOG.error(e.getMessage(), e);
return Response.status(Response.Status.NOT_FOUND).build();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@GET
@Path("{name}")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({"user", "system/admin", "system/manager"})
public Response getViewDataAsJson(@PathParam("name") String name,
@Context UriInfo uriInfo,
@Context SecurityContext securityContext) {
try {
Map<String, String> params = Utils.extractParams(uriInfo, securityContext);
com.codenvy.analytics.metrics.Context context = com.codenvy.analytics.metrics.Context.valueOf(params);
ViewData result = viewBuilder.getViewData(name, context);
String json = transformToJson(result);
return Response.status(Response.Status.OK).entity(json).build();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@GET
@Path("{name}.csv")
@Produces({"text/csv"})
@RolesAllowed({"user", "system/admin", "system/manager"})
public Response getViewDataAsCsv(@PathParam("name") String name,
@Context UriInfo uriInfo,
@Context SecurityContext securityContext) {
try {
Map<String, String> params = Utils.extractParams(uriInfo, securityContext);
com.codenvy.analytics.metrics.Context context = com.codenvy.analytics.metrics.Context.valueOf(params);
if (context.exists(Parameters.TIME_UNIT)) {
context = com.codenvy.analytics.Utils.initRowsCountForCSVReport(context);
}
ViewData result = viewBuilder.getViewData(name, context);
final File csvFile = csvFileCleanerHolder.createNewReportFile();
try (FileOutputStream csvOutputStream = new FileOutputStream(csvFile)) {
transformToCsv(result, csvOutputStream);
}
return Response.status(Response.Status.OK).entity(getStreamingOutput(csvFile)).build();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
private StreamingOutput getStreamingOutput(final File csvFile) {
return new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException, WebApplicationException {
try (FileInputStream csvInputStream = new FileInputStream(csvFile)) {
IOUtils.copy(csvInputStream, os);
} finally {
csvFile.delete();
}
}
};
}
/**
* Transforms view data into table in json format.
*
* @return the resulted format will be:
* [
* [
* ["section0-row0-column0", "section0-row0-column1", ...]
* ["section0-row1-column0", "section0-row1-column1", ...]
* ...
* ],
* [
* ["section1-row0-column0", "section0-row0-column1", ...]
* ["section1-row1-column0", "section0-row1-column1", ...]
* ...
* ],
* ...
* ]
*/
protected String transformToJson(ViewData data) {
List<LinkedHashSet<Object>> result = new ArrayList<>(data.size());
for (Entry<String, SectionData> sectionEntry : data.entrySet()) {
LinkedHashSet<Object> newSectionData = new LinkedHashSet<>(sectionEntry.getValue().size());
for (int i = 0; i < sectionEntry.getValue().size(); i++) {
List<ValueData> rowData = sectionEntry.getValue().get(i);
List<String> newRowData = new ArrayList<>(rowData.size());
for (int j = 0; j < rowData.size(); j++) {
newRowData.add(rowData.get(j).getAsString());
}
newSectionData.add(newRowData);
}
result.add(newSectionData);
}
return new JsonArrayImpl<>(result).toJson();
}
/**
* Transforms view data into table in csv format.
*
* @return the resulted format will be:
* section0-row0-column0, section0-row0-column1, ...
* section0-row1-column0, section0-row1-column1, ...
* ...
* section1-row0-column0, section0-row0-column1, ...
* section1-row1-column0, section0-row1-column1, ...
* ...
*/
protected void transformToCsv(ViewData data, OutputStream os) throws IOException {
for (Entry<String, SectionData> sectionEntry : data.entrySet()) {
for (int i = 0; i < sectionEntry.getValue().size(); i++) {
List<ValueData> rowData = sectionEntry.getValue().get(i);
os.write((getCsvRow(rowData) + "\n").getBytes("UTF-8"));
}
}
}
public String getCsvRow(List<ValueData> data) {
StringBuilder builder = new StringBuilder();
for (ValueData valueData : data) {
if (builder.length() != 0) {
builder.append(',');
}
builder.append('\"');
builder.append(valueData.getAsString().replace("\"", "\"\""));
builder.append('\"');
}
return builder.toString();
}
}
|
package com.reactnativenavigation.views;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import com.reactnativenavigation.R;
import com.reactnativenavigation.params.LightBoxParams;
import com.reactnativenavigation.utils.ViewUtils;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
public class LightBox extends Dialog implements DialogInterface.OnDismissListener {
private Runnable onDismissListener;
private ContentView content;
private RelativeLayout lightBox;
private boolean cancelable;
public LightBox(AppCompatActivity activity, Runnable onDismissListener, LightBoxParams params) {
super(activity, R.style.LightBox);
this.onDismissListener = onDismissListener;
this.cancelable = !params.overrideBackPress;
setOnDismissListener(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
createContent(activity, params);
setCancelable(cancelable);
getWindow().setWindowAnimations(android.R.style.Animation);
getWindow().setSoftInputMode(params.adjustSoftInput);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
}
private void createContent(final Context context, final LightBoxParams params) {
lightBox = new RelativeLayout(context);
lightBox.setAlpha(0);
lightBox.setBackgroundColor(params.backgroundColor.getColor());
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
content = new ContentView(context, params.screenId, params.navigationParams);
lp.addRule(RelativeLayout.CENTER_IN_PARENT, content.getId());
content.setAlpha(0);
lightBox.addView(content, lp);
if (params.tapBackgroundToDismiss) {
lightBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hide();
}
});
}
content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Note that this may be called multiple times as the lightbox views get built. We want to hold off
// doing anything here until the lightbox screen and its measurements are available.
final View lightboxScreen = content.getChildAt(0);
if (lightboxScreen != null) {
final int screenHeight = lightboxScreen.getHeight();
final int screenWidth = lightboxScreen.getWidth();
if (screenHeight > 0 && screenWidth > 0) {
content.getViewTreeObserver().removeOnGlobalLayoutListener(this);
content.getLayoutParams().height = screenHeight;
content.getLayoutParams().width = screenWidth;
content.setBackgroundColor(Color.TRANSPARENT);
ViewUtils.runOnPreDraw(content, new Runnable() {
@Override
public void run() {
animateShow();
}
});
}
}
}
});
setContentView(lightBox, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
@Override
public void show() {
super.show();
}
@Override
public void hide() {
animateHide();
}
@Override
public void onBackPressed() {
if (cancelable) {
hide();
}
}
@Override
public void onDismiss(DialogInterface dialogInterface) {
onDismissListener.run();
}
public void destroy() {
if (content != null) {
content.unmountReactView();
lightBox.removeAllViews();
content = null;
}
dismiss();
}
private void animateShow() {
ObjectAnimator yTranslation = ObjectAnimator.ofFloat(content, View.TRANSLATION_Y, 80, 0).setDuration(400);
yTranslation.setInterpolator(new FastOutSlowInInterpolator());
yTranslation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
content.setAlpha(1);
}
});
ObjectAnimator lightBoxAlpha = ObjectAnimator.ofFloat(lightBox, View.ALPHA, 0, 1).setDuration(70);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(lightBoxAlpha, yTranslation);
animatorSet.start();
}
private void animateHide() {
ObjectAnimator alpha = ObjectAnimator.ofFloat(content, View.ALPHA, 0);
ObjectAnimator yTranslation = ObjectAnimator.ofFloat(content, View.TRANSLATION_Y, 60);
AnimatorSet contentAnimators = new AnimatorSet();
contentAnimators.playTogether(alpha, yTranslation);
contentAnimators.setDuration(150);
ObjectAnimator lightBoxAlpha = ObjectAnimator.ofFloat(lightBox, View.ALPHA, 0).setDuration(100);
AnimatorSet allAnimators = new AnimatorSet();
allAnimators.playSequentially(contentAnimators, lightBoxAlpha);
allAnimators.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
destroy();
}
});
allAnimators.start();
}
}
|
package nl.fhict.happynews.api.controller;
import com.sun.org.apache.regexp.internal.RE;
import nl.fhict.happynews.api.hibernate.PostRepository;
import nl.fhict.happynews.shared.Post;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@RestController
public class PostController {
/**Automagically creates a repository**/
@Autowired
private PostRepository postRepository;
/**
* Handles a GET request by returning all posts.
* @param ordered Whether the list should be ordered by latest or not.
* @return The Posts in JSON.
*/
@RequestMapping(value = "/post", method = RequestMethod.GET, produces = "application/json")
public Collection<Post> getAllPost(@RequestParam(required = false, defaultValue = "true", value="ordered") boolean ordered) {
if(ordered){
return this.postRepository.findAllByOrderByPublishedAtDesc();
}else{
return this.postRepository.findAll();
}
}
/**
* Handles a GET request by returning posts in a paginated format.
* @param pageable the page and page size
* @return A Page with Post information
*/
@RequestMapping(value = "/page", method = RequestMethod.GET, produces = "application/json")
public Page<Post> getAllByPage(Pageable pageable){
return this.postRepository.findAll(pageable);
}
/**
* Handles a GET request by returning a Post by it's UUID.
* @param uuid The UUID.
* @return The Post in JSON.
*/
@RequestMapping(value = "/post/uuid/{uuid}", method = RequestMethod.GET, produces = "application/json")
public Post getPostByUuid(@PathVariable("uuid") String uuid) {
return this.postRepository.findByUuid(uuid);
}
/**
* Handles a GET request by returning a collection of Post after a certain date.
* @param date The date after which posts should be retrieved.
* @param ordered Whether the list should be ordered by latest or not.
* @return The Posts in JSON.
*/
@RequestMapping(value = "/post/afterdate/{date}", method = RequestMethod.GET, produces = "application/json")
public Collection<Post> getPostAfterDate(@PathVariable("date") String date, @RequestParam(required = false, defaultValue = "true", value="ordered") boolean ordered) {
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d hh:mm:ss z yyyy");
Date properdate = null;
try {
properdate = sdf.parse(date);
} catch (ParseException e) {
Logger logger = LoggerFactory.getLogger(PostRepository.class);
logger.error("Date cannot be parsed.", e);
}
if(ordered){
return this.postRepository.findByPublishedAtAfterOrderByPublishedAtDesc(properdate);
}else{
return this.postRepository.findByPublishedAtAfter(properdate);
}
}
}
|
package gscrot.processor.watermark;
import gscrot.processor.watermark.WatermarkPlugin.Mode;
import gscrot.processor.watermark.WatermarkPlugin.Position;
import iconlib.IconUtils;
import java.awt.Graphics2D;
import com.redpois0n.gscrot.GraphicsImageProcessor;
public class WatermarkProcessor extends GraphicsImageProcessor {
public WatermarkProcessor() {
super("Watermark", IconUtils.getIcon("watermark", WatermarkProcessor.class));
}
@Override
public void process(Graphics2D g, int width, int height) {
if (WatermarkPlugin.mode == Mode.TEXT) {
g.setFont(WatermarkPlugin.font);
g.setColor(WatermarkPlugin.foreground);
String s = WatermarkPlugin.string;
if (WatermarkPlugin.position == Position.TOPLEFT) {
g.drawString(s, 10, 10);
} else if (WatermarkPlugin.position == Position.TOPRIGHT) {
g.drawString(s, width - g.getFontMetrics().stringWidth(s) - 10, 10);
} else if (WatermarkPlugin.position == Position.BOTTOMLEFT) {
g.drawString(s, 10, height - g.getFontMetrics().getHeight() - 10);
} else if (WatermarkPlugin.position == Position.BOTTOMRIGHT) {
g.drawString(s, width - g.getFontMetrics().stringWidth(s) - 10, height - g.getFontMetrics().getHeight() - 10);
}
} else if (WatermarkPlugin.mode == Mode.IMAGE) {
}
}
}
|
package info.northcarolinawaterfalls.app;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import info.northcarolinawaterfalls.app.ExpansionDownloaderDialogFragment.ExpansionDownloadDialogListener;
public class MainActivity extends SherlockFragmentActivity implements
ExpansionDownloadDialogListener, OnCancelListener {
private static final String TAG = "MainActivity";
public static final String PREFS_NAME = "AppSettingsPreferences";
private static final String USER_PREF_PAUSE_DOWNLOAD = "UserPrefPauseDownload";
private static final String USER_PREF_SKIP_PLAY_SERVICES = "UserPrefSkipPlayServices";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume(){
super.onResume();
if(googlePlayServicesAvailable()){
// Determine if the expansion files have been downloaded
// Do this in the else of the above check because it's irrelevant if
// Play Services aren't available.
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean userPrefPauseDownload = settings.getBoolean(USER_PREF_PAUSE_DOWNLOAD, false);
if(!ExpansionDownloaderService.expansionFilesDownloaded(this)){
// Warn user about offline maps.
if(!userPrefPauseDownload){
DialogFragment expansionDownloaderDialogFragment = new ExpansionDownloaderDialogFragment();
expansionDownloaderDialogFragment.show(getSupportFragmentManager(), "expansionDownloaderDialogFragment");
} else {
// TODO: We should probably not show this repeatedly.
Toast.makeText(
getApplicationContext(),
"Offline maps not available. Open App Info to download.",
Toast.LENGTH_LONG
).show();
}
}
} else {
// Disable Search by Location button
Button searchLocationButton = (Button) findViewById(R.id.main_btn_search_location);
if(searchLocationButton != null){
searchLocationButton.setClickable(false);
searchLocationButton.setEnabled(false);
}
}
}
/* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
// Define a DialogFragment that displays the error dialog generated in showErrorDialog
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
/*
* Handle results returned to the FragmentActivity by Google Play services
* error checking/correcting routine.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
Log.d(TAG, "Inside onActivityResult.");
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
/*
* If the result code is Activity.RESULT_OK, we should
* have Play Services available.
*/
switch (resultCode) {
case Activity.RESULT_OK :
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(USER_PREF_SKIP_PLAY_SERVICES, false);
editor.commit();
break;
}
}
}
// GooglePlayServices errorDialog onCancel interface
@Override
public void onCancel(DialogInterface dialog) {
// User chose not to install Play Services. This means no map tabs.
// Save preference.
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(USER_PREF_SKIP_PLAY_SERVICES, true);
editor.commit();
}
private boolean googlePlayServicesAvailable() {
// Check that Google Play services is available
// Unfortunately, this has the side effect of creating an
// error dialog, so it's not just a simple check.
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d(TAG, "Google Play services is available.");
editor.putBoolean(USER_PREF_SKIP_PLAY_SERVICES, false);
editor.commit();
return true;
} else if(!settings.getBoolean(USER_PREF_SKIP_PLAY_SERVICES, false)) {
// Google Play services was not available for some reason
// Disable map fragments until this is resolved.
Log.d(TAG, "Google Play services is NOT available.");
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
resultCode, this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
editor.putBoolean(USER_PREF_SKIP_PLAY_SERVICES, true);
editor.commit();
if (errorDialog != null) {
// Play Services can sometimes provide a dialog with options
// for the user to correct the issue.
// Create a new DialogFragment for the error dialog.
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(getSupportFragmentManager(), "Maps");
// If I'm reading the docs correctly, then if the user opts to install
// Play Services, startActivityForResult will be called when done, and
// return through this activity's onActivityResult.
}
return false;
}
return false;
}
/*
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
*/
public void searchAll(View view){
// Create new intent
Intent intent = new Intent(this, ResultsActivity.class);
// Pack it with message containing blank search term (for "show all")
intent.putExtra(SearchActivity.EXTRA_ONLY_SHARED, false);
intent.putExtra(SearchActivity.EXTRA_SEARCH_MODE, SearchActivity.SEARCH_MODE_WATERFALL);
intent.putExtra(SearchActivity.EXTRA_SEARCH_TERM, "");
// Start the Results activity
startActivity(intent);
}
public void searchByName(View view){
Intent intent = new Intent(this, SearchActivity.class);
intent.putExtra(SearchActivity.EXTRA_SEARCH_MODE, SearchActivity.SEARCH_MODE_WATERFALL);
startActivity(intent);
}
public void searchByHike(View view){
Intent intent = new Intent(this, SearchActivity.class);
intent.putExtra(SearchActivity.EXTRA_SEARCH_MODE, SearchActivity.SEARCH_MODE_HIKE);
startActivity(intent);
}
public void searchByLocation(View view){
Intent intent = new Intent(this, SearchActivity.class);
intent.putExtra(SearchActivity.EXTRA_SEARCH_MODE, SearchActivity.SEARCH_MODE_LOCATION);
startActivity(intent);
}
public void searchByShared(View view){
Intent intent = new Intent(this, ResultsActivity.class);
// Pack intent with message containing blank search term (for "show all")
// and shared = true
intent.putExtra(SearchActivity.EXTRA_ONLY_SHARED, true);
intent.putExtra(SearchActivity.EXTRA_SEARCH_MODE, SearchActivity.SEARCH_MODE_WATERFALL);
intent.putExtra(SearchActivity.EXTRA_SEARCH_TERM, "");
startActivity(intent);
}
public void appInfo(View view){
Intent intent = new Intent(this, AppInfoActivity.class);
startActivity(intent);
}
private void startAppInfoActivity(){
Intent intent = new Intent(this, AppInfoActivity.class);
startActivity(intent);
}
// ExpansionDownloadDialogListener interface methods
public void onExpansionDownloaderDialogPositiveClick(DialogFragment dialog){
Log.d(TAG, "Download affirmative.");
startAppInfoActivity();
}
public void onExpansionDownloaderDialogNegativeClick(DialogFragment dialog){
Toast.makeText(getApplicationContext(), "Skipped downloading offline maps.", Toast.LENGTH_LONG).show();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(USER_PREF_PAUSE_DOWNLOAD, true);
editor.commit();
}
// PlayServicesCheckDialogListener interface methods
public void onPlayServicesDialogPositiveClick(DialogFragment dialog){
Log.d(TAG, "Play Services Check affirmative.");
startAppInfoActivity();
}
public void onPlayServicesDialogNegativeClick(DialogFragment dialog){
// OK. Fine.
}
}
|
package com.androsz.electricsleepbeta.widget;
import java.io.IOException;
import java.io.StreamCorruptedException;
import java.util.List;
import org.achartengine.GraphicalView;
import org.achartengine.chart.AbstractChart;
import org.achartengine.chart.TimeChart;
import org.achartengine.model.PointD;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.util.AttributeSet;
import android.util.Log;
import com.androsz.electricsleepbeta.R;
import com.androsz.electricsleepbeta.app.SettingsActivity;
import com.androsz.electricsleepbeta.db.SleepSession;
import com.androsz.electricsleepbeta.util.MathUtils;
public class SleepChart extends GraphicalView {
private static final String TAG = SleepChart.class.getSimpleName();
Context mContext;
public int rating;
public TimeChart mChart;
public XYMultipleSeriesDataset mDataset;
public XYMultipleSeriesRenderer mRenderer;
private static final double INVALID_CALIBRATION = -1;
int mBackgroundColor;
int mTextColor;
int mCalibrationBorderColor;
int mCalibrationColor;
int mGridColor;
int mMovementBorderColor;
int mMovementColor;
boolean mSetBackgroundColor;
boolean mSetGridColor;
boolean mSetInScroll;
boolean mSetTextColor;
boolean mShowGrid;
boolean mShowLabels;
boolean mShowLegend;
boolean mShowTitle = true;
private double mCalibrationLevel = INVALID_CALIBRATION;
private String mAxisFormat;
public SleepChartData mData;
int mDefStyle;
AttributeSet mAttrs;
public SleepChart(final Context context) {
this(context, null);
}
public SleepChart(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public SleepChart(final Context context, final AttributeSet attrs, int defStyle) {
super(context, attrs);
mContext = context;
mAttrs = attrs;
mDefStyle = defStyle;
// Now begin processing attributes
final Resources resources = mContext.getResources();
final TypedArray array =
mContext.obtainStyledAttributes(mAttrs, R.styleable.SleepChart, mDefStyle, 0);
if (array.hasValue(R.styleable.SleepChart_android_background)) {
mSetBackgroundColor = true;
mBackgroundColor = array.getColor(R.styleable.SleepChart_android_background,
R.color.background_dark);
}
if (array.hasValue(R.styleable.SleepChart_android_textColor)) {
mSetTextColor = true;
mTextColor = array.getColor(R.styleable.SleepChart_android_textColor,
R.color.text_dark);
}
if (array.getBoolean(R.styleable.SleepChart_setScroll, false)) {
mSetInScroll = true;
}
if (array.hasValue(R.styleable.SleepChart_gridAxisColor)) {
mSetGridColor = true;
mGridColor = array.getColor(R.styleable.SleepChart_gridAxisColor,
R.color.sleepchart_axis);
}
mMovementColor = array.getColor(R.styleable.SleepChart_movementColor,
R.color.sleepchart_movement_light);
mMovementBorderColor = array.getColor(R.styleable.SleepChart_movementBorderColor,
R.color.sleepchart_movement_border_light);
mCalibrationColor = array.getColor(R.styleable.SleepChart_calibrationColor,
R.color.sleepchart_calibration_light);
mCalibrationBorderColor = array.getColor(R.styleable.SleepChart_calibrationBorderColor,
R.color.sleepchart_calibration_border_light);
mShowGrid = array.getBoolean(R.styleable.SleepChart_showGrid, true);
mShowLabels = array.getBoolean(R.styleable.SleepChart_showLabels, true);
mShowLegend = array.getBoolean(R.styleable.SleepChart_showLegend, true);
mShowTitle = array.getBoolean(R.styleable.SleepChart_showTitle, true);
}
@Override
protected AbstractChart buildChart() {
Log.d(TAG, "Attempting to build chart.");
if (mChart != null) {
Log.d(TAG, "Attempt to build chart when chart already exists.");
return null;
}
mDataset = new XYMultipleSeriesDataset();
mRenderer = new XYMultipleSeriesRenderer();
// Set initial framing for renderer.
mRenderer.setYAxisMin(0);
mRenderer.setYAxisMax(SettingsActivity.MAX_ALARM_SENSITIVITY);
mRenderer.setXAxisMin(System.currentTimeMillis());
mRenderer.setXAxisMax(System.currentTimeMillis());
mRenderer.setPanEnabled(false, false);
mRenderer.setZoomEnabled(false, false);
mChart = new TimeChart(mDataset, mRenderer);
mChart.setDateFormat("h:mm:ss");
return mChart;
}
public void addPoint(double x, double y) {
mData.add(x, y);
}
public double getCalibrationLevel() {
if (mData != null) {
return mData.calibrationLevel;
} else if (mCalibrationLevel != INVALID_CALIBRATION) {
return mCalibrationLevel;
}
return INVALID_CALIBRATION;
}
public boolean makesSenseToDisplay() {
if (mData == null) {
return false;
}
Log.d(TAG, "Make sense to display is: " + (mData.xySeriesMovement.getItemCount() > 1));
return mData.xySeriesMovement.getItemCount() > 1;
}
public void reconfigure() {
if (makesSenseToDisplay()) {
Log.d(TAG, "Executing reconfigure after it made sense to display.");
final double firstX = mData.xySeriesMovement.getX(0);
final double lastX =
mData.xySeriesMovement.getX(mData.xySeriesMovement.getItemCount() - 1);
// if (makesSenseToDisplay()) {
// reconfigure the calibration line..
mData.xySeriesCalibration.clear();
mData.xySeriesCalibration.add(firstX, mData.calibrationLevel);
mData.xySeriesCalibration.add(lastX, mData.calibrationLevel);
/*
* if (lastX - firstX > HOUR_IN_MS*2) { ((TimeChart)
* mChart).setDateFormat("h");
* xyMultipleSeriesRenderer.setXLabels(8); }else if (lastX - firstX
* > MINUTE_IN_MS*3) { ((TimeChart) mChart).setDateFormat("h:mm");
* xyMultipleSeriesRenderer.setXLabels(5); }
*/
mRenderer.setXAxisMin(firstX);
mRenderer.setXAxisMax(lastX);
mRenderer.setYAxisMin(0);
mRenderer.setYAxisMax(SettingsActivity.MAX_ALARM_SENSITIVITY);
setupChartAxisFormat();
} else {
Log.w(TAG, "Asked to reconfigure but it did not make sense to display.");
}
}
/**
* Set this sleep chart to the given data.
*/
public void setData(SleepChartData data) {
synchronized (this) {
mData = data;
setupData();
}
}
public void setCalibrationLevel(final double calibrationLevel) {
if (mData == null) {
mCalibrationLevel = calibrationLevel;
} else {
mData.calibrationLevel = calibrationLevel;
}
}
public void setScroll(boolean scroll) {
mSetInScroll = scroll;
}
public void sync(final Cursor cursor)
throws StreamCorruptedException, IllegalArgumentException,
IOException, ClassNotFoundException {
Log.d(TAG, "Attempting to sync with cursor: " + cursor);
this.sync(new SleepSession(cursor));
}
public void sync(final Double x, final Double y, final double calibrationLevel) {
Log.d(TAG, "Attempting to sync with values: " +
" x=" + x +
" y=" + y +
" calibrationLevel=" + calibrationLevel);
synchronized (this) {
initCheckData();
mData.add(x, y, calibrationLevel);
}
reconfigure();
repaint();
}
public void sync(List<PointD> points)
{
synchronized (this) {
initCheckData();
clear();
for (PointD point : points) {
addPoint(point.x, point.y);
}
}
reconfigure();
repaint();
}
public void sync(final SleepSession sleepRecord) {
Log.d(TAG, "Attempting to sync with sleep record: " + sleepRecord);
synchronized (this) {
initCheckData();
mData.set(com.androsz.electricsleepbeta.util.PointD.convertToNew(sleepRecord.getData()),
sleepRecord.getCalibrationLevel());
}
// TODO this need to take into account timezone information.
if (mShowTitle) {
mRenderer.setChartTitle(sleepRecord.getTitle(mContext));
}
reconfigure();
repaint();
}
public void clear() {
synchronized (this) {
if (mData != null) {
mData.clear();
}
}
}
/**
* Perform a check to see if data is initialized and if not then initialize it.
*/
private void initCheckData() {
if (mData == null) {
mData = new SleepChartData(mContext);
mData.calibrationLevel = mCalibrationLevel;
setupData();
}
}
/**
* Set the chart's axis format based upon current duration of the data.
*/
private void setupChartAxisFormat() {
if (mData == null) {
return;
}
final double duration = mData.getDuration();
String axisFormat;
final int MSEC_PER_MINUTE = 1000 * 60;
final int MSEC_PER_HOUR = MSEC_PER_MINUTE * 60;
if (duration > (15 * MSEC_PER_MINUTE)) {
axisFormat = "h:mm";
} else {
axisFormat = "h:mm:ss";
}
if (!axisFormat.equals(mAxisFormat)) {
mAxisFormat = axisFormat;
mChart.setDateFormat(mAxisFormat);
}
}
/**
* Helper method that initializes charting after insertion of data.
*/
private void setupData() {
if (mData == null) {
Log.w(TAG, "Asked to setup data when it was not instantiated.");
return;
}
// remove all existing series
for (int i = 0; i < mDataset.getSeriesCount(); i++) {
mDataset.removeSeries(i);
}
for (int i = 0; i < mRenderer.getSeriesRendererCount(); i++) {
mRenderer.removeSeriesRenderer(mRenderer.getSeriesRendererAt(i));
}
// add series to the dataset
mDataset.addSeries(mData.xySeriesMovement);
mDataset.addSeries(mData.xySeriesCalibration);
// set up the dataset renderer
mRenderer.addSeriesRenderer(mData.xySeriesMovementRenderer);
mRenderer.addSeriesRenderer(mData.xySeriesCalibrationRenderer);
final float textSize = MathUtils.calculatePxFromSp(mContext, 14);
mRenderer.setChartTitleTextSize(textSize);
mRenderer.setAxisTitleTextSize(textSize);
mRenderer.setLabelsTextSize(textSize);
// xyMultipleSeriesRenderer.setLegendHeight((int) (MathUtils
// .calculatePxFromDp(context, 30) + textSize*3));
mRenderer.setAntialiasing(true);
mRenderer.setFitLegend(true);
mRenderer.setLegendTextSize(textSize);
mRenderer.setXLabels(5);
mRenderer.setYLabels(8);
mRenderer.setYLabelsAlign(Align.RIGHT);
setupStyle();
setupChartAxisFormat();
}
/**
* Iterate over the known attributes for this view setting our chart to the desired settings.
*/
private void setupStyle() {
// TODO remove comment
// After this point buildChart() should have been invoked and the
// various renders and series
// should have been populated.
if (mAttrs == null) {
Log.d(TAG, "No attributes nothing to process.");
return;
}
Log.d(TAG, "Processing attributes.");
// background color processing
if (mSetBackgroundColor) {
mRenderer.setBackgroundColor(mBackgroundColor);
mRenderer.setMarginsColor(mBackgroundColor);
mRenderer.setApplyBackgroundColor(true);
} else {
mRenderer.setBackgroundColor(Color.TRANSPARENT);
mRenderer.setMarginsColor(Color.TRANSPARENT);
mRenderer.setApplyBackgroundColor(true);
}
if (mSetTextColor) {
mRenderer.setLabelsColor(mTextColor);
mRenderer.setAxesColor(mTextColor);
}
// SleepChart_setScroll
mRenderer.setInScroll(mSetInScroll);
// SleepChart_gridAxisColor
if (mSetGridColor) {
mRenderer.setGridColor(mGridColor);
} else {
mRenderer.setGridColor(R.color.sleepchart_axis);
}
// SleepChart_movementColor
mData.xySeriesMovementRenderer.setFillBelowLineColor(mMovementColor);
// SleepChart_movementBorderColor
mData.xySeriesMovementRenderer.setColor(mMovementBorderColor);
// SleepChart_calibrationColor
mData.xySeriesCalibrationRenderer.setFillBelowLineColor(mCalibrationColor);
// SleepChart_calibrationBorderColor
mData.xySeriesCalibrationRenderer.setColor(mCalibrationBorderColor);
// SleepChart_showGrid
mRenderer.setShowGrid(mShowGrid);
int[] margins = mRenderer.getMargins();
mRenderer.setShowLabels(mShowLabels);
if (mShowLabels) {
margins[1] += 25; // increase left margin
}
mRenderer.setShowLegend(mShowLegend);
if (mShowLegend) {
margins[2] += 20; // increase bottom margin
}
if (mShowTitle) {
margins[0] += 20; // increase top margin
}
mRenderer.setMargins(margins);
setupChartAxisFormat();
}
}
|
package com.education.flashmath.network;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import android.content.Context;
import android.provider.Settings.Secure;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class FlashMathClient {
private static FlashMathClient flashMathClient;
private RequestParams auth;
private AsyncHttpClient client;
private FlashMathClient(Context context) { // Private constructor
auth = new RequestParams();
// TODO Replace this "global" with the device token
String android_id = Secure.getString(context.getContentResolver(),
Secure.ANDROID_ID);
auth.put("token", encryptPassword(android_id));
client = new AsyncHttpClient();
}
public static FlashMathClient getClient(Context context) {
if (flashMathClient == null) {
flashMathClient = new FlashMathClient(context);
}
return flashMathClient;
}
public void getQuestions(String subject, AsyncHttpResponseHandler handler) {
String url = "http://flashmathapi.herokuapp.com/quizzes/" + subject + "/";
client.get(url, auth, handler);
}
public void getScores(String subject, AsyncHttpResponseHandler handler) {
String url = "http://flashmathapi.herokuapp.com/scores/" + subject + "/";
client.get(url, auth, handler);
}
public void clearScores(String subject, AsyncHttpResponseHandler handler) {
String url = "http://flashmathapi.herokuapp.com/scores/" + subject + "/clear";
client.get(url, auth, handler);
}
public void putScore(String subject, String score, AsyncHttpResponseHandler handler) {
String url = "http://flashmathapi.herokuapp.com/scores/" + subject + "/" + score + "/";
client.get(url, auth, handler);
}
private static String encryptPassword(String password)
{
String sha1 = "";
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(password.getBytes("UTF-8"));
sha1 = byteToHex(crypt.digest());
}
catch(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
return sha1;
}
private static String byteToHex(final byte[] hash)
{
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
}
|
package org.navalplanner.web.planner.chart;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.commons.lang.Validate;
import org.joda.time.LocalDate;
import org.navalplanner.web.I18nHelper;
import org.zkforge.timeplot.Plotinfo;
import org.zkforge.timeplot.Timeplot;
import org.zkforge.timeplot.geometry.TimeGeometry;
import org.zkforge.timeplot.geometry.ValueGeometry;
import org.zkoss.ganttz.util.Interval;
/**
* Abstract class with the common functionality for the earned value chart.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public abstract class EarnedValueChartFiller extends ChartFiller {
public static <K, V> void forValuesAtSameKey(Map<K, V> a, Map<K, V> b,
IOperation<K, V> onSameKey) {
for (Entry<K, V> each : a.entrySet()) {
V aValue = each.getValue();
V bValue = b.get(each.getKey());
onSameKey.operate(each.getKey(), aValue, bValue);
}
}
public interface IOperation<K, V> {
public void operate(K key, V a, V b);
public void undefinedFor(K key);
}
protected static abstract class PreconditionChecker<K, V> implements
IOperation<K, V> {
private final IOperation<K, V> decorated;
protected PreconditionChecker(IOperation<K, V> decorated) {
this.decorated = decorated;
}
@Override
public void operate(K key, V a, V b) {
if (isOperationDefinedFor(key, a, b)) {
decorated.operate(key, a, b);
} else {
decorated.undefinedFor(key);
}
}
protected abstract boolean isOperationDefinedFor(K key, V a, V b);
@Override
public void undefinedFor(K key) {
decorated.undefinedFor(key);
}
}
public static <K, V> IOperation<K, V> notNullOperands(
final IOperation<K, V> operation) {
return new PreconditionChecker<K, V>(operation) {
@Override
protected boolean isOperationDefinedFor(K key, V a, V b) {
return a != null && b != null;
}
};
}
public static <K> IOperation<K, BigDecimal> secondOperandNotZero(
final IOperation<K, BigDecimal> operation) {
return new PreconditionChecker<K, BigDecimal>(operation) {
@Override
protected boolean isOperationDefinedFor(K key, BigDecimal a, BigDecimal b) {
return b.signum() != 0;
}
};
}
public static boolean includes(Interval interval, LocalDate date) {
LocalDate start = LocalDate.fromDateFields(interval.getStart());
LocalDate end = LocalDate.fromDateFields(interval.getFinish());
return start.compareTo(date) <= 0 && date.compareTo(end) < 0;
}
public enum EarnedValueType {
BCWS(_("BCWS"), _("Budgeted Cost Work Scheduled"), "#0000FF"), ACWP(
_("ACWP"), _("Actual Cost Work Performed"), "#FF0000"), BCWP(
_("BCWP"), _("Budgeted Cost Work Performed"), "#00FF00"), CV(
_("CV"), _("Cost Variance"), "#FF8800"), SV(_("SV"),
_("Schedule Variance"), "#00FFFF"), BAC(_("BAC"),
_("Budget At Completion"), "#FF00FF"), EAC(_("EAC"),
_("Estimate At Completion"), "#880000"), VAC(_("VAC"),
_("Variance At Completion"), "#000088"), ETC(_("ETC"),
_("Estimate To Complete"), "#008800"), CPI(_("CPI"),
_("Cost Performance Index"), "#888800"), SPI(_("SPI"),
_("Schedule Performance Index"), "#008888")
;
/**
* Forces to mark the string as needing translation
*/
private static String _(String string) {
return string;
}
private String acronym;
private String name;
private String color;
private EarnedValueType(String acronym, String name, String color) {
this.acronym = acronym;
this.name = name;
this.color = color;
}
public String getAcronym() {
return I18nHelper._(acronym);
}
public String getName() {
return I18nHelper._(name);
}
public String getColor() {
return color;
}
}
protected Map<EarnedValueType, SortedMap<LocalDate, BigDecimal>> indicators = new HashMap<EarnedValueType, SortedMap<LocalDate, BigDecimal>>();
private Interval indicatorsInterval;
protected abstract void calculateBudgetedCostWorkScheduled(Interval interval);
protected abstract void calculateActualCostWorkPerformed(Interval interval);
protected abstract void calculateBudgetedCostWorkPerformed(Interval interval);
protected Plotinfo createPlotInfo(SortedMap<LocalDate, BigDecimal> map,
Interval interval, String lineColor) {
Plotinfo plotInfo = createPlotinfo(map, interval, true);
plotInfo.setLineColor(lineColor);
return plotInfo;
}
public void calculateValues(Interval interval) {
this.indicatorsInterval = interval;
// BCWS
calculateBudgetedCostWorkScheduled(interval);
// ACWP
calculateActualCostWorkPerformed(interval);
// BCWP
calculateBudgetedCostWorkPerformed(interval);
calculateCostVariance();
calculateScheduleVariance();
// BAC
calculateBudgetAtCompletion();
// EAC
calculateEstimateAtCompletion();
// VAC
calculateVarianceAtCompletion();
// ETC
calculateEstimatedToComplete();
// CPI
calculateCostPerformanceIndex();
// SPI
calculateSchedulePerformanceIndex();
}
public BigDecimal getIndicator(EarnedValueType indicator, LocalDate date) {
return indicators.get(indicator).get(date);
}
private void calculateCostVariance() {
// CV = BCWP - ACWP
indicators.put(EarnedValueType.CV,
substract(EarnedValueType.BCWP, EarnedValueType.ACWP));
}
private void calculateScheduleVariance() {
// SV = BCWP - BCWS
indicators.put(EarnedValueType.SV,
substract(EarnedValueType.BCWP, EarnedValueType.BCWS));
}
private void calculateBudgetAtCompletion() {
// BAC = max (BCWS)
SortedMap<LocalDate, BigDecimal> bac = new TreeMap<LocalDate, BigDecimal>();
SortedMap<LocalDate, BigDecimal> bcws = indicators
.get(EarnedValueType.BCWS);
BigDecimal value = Collections.max(bcws.values());
for (LocalDate day : bcws.keySet()) {
bac.put(day, value);
}
indicators.put(EarnedValueType.BAC, bac);
}
private void calculateEstimateAtCompletion() {
// EAC = (ACWP/BCWP) * BAC
SortedMap<LocalDate, BigDecimal> dividend = divide(
EarnedValueType.ACWP, EarnedValueType.BCWP,
BigDecimal.ZERO);
SortedMap<LocalDate, BigDecimal> bac = indicators
.get(EarnedValueType.BAC);
indicators.put(EarnedValueType.EAC, multiply(dividend, bac));
}
private static SortedMap<LocalDate, BigDecimal> multiply(
Map<LocalDate, BigDecimal> firstFactor,
Map<LocalDate, BigDecimal> secondFactor) {
final SortedMap<LocalDate, BigDecimal> result = new TreeMap<LocalDate, BigDecimal>();
forValuesAtSameKey(firstFactor, secondFactor,
multiplicationOperation(result));
return result;
}
private static IOperation<LocalDate, BigDecimal> multiplicationOperation(
final SortedMap<LocalDate, BigDecimal> result) {
return notNullOperands(new IOperation<LocalDate, BigDecimal>() {
@Override
public void operate(LocalDate key, BigDecimal a,
BigDecimal b) {
result.put(key, a.multiply(b));
}
@Override
public void undefinedFor(LocalDate key) {
result.put(key, BigDecimal.ZERO);
}
});
}
private void calculateVarianceAtCompletion() {
indicators.put(EarnedValueType.VAC,
substract(EarnedValueType.BAC, EarnedValueType.EAC));
}
private void calculateEstimatedToComplete() {
// ETC = EAC - ACWP
indicators.put(EarnedValueType.ETC,
substract(EarnedValueType.EAC, EarnedValueType.ACWP));
}
private SortedMap<LocalDate, BigDecimal> substract(EarnedValueType minuend,
EarnedValueType subtrahend) {
return substract(indicators.get(minuend), indicators.get(subtrahend));
}
private static SortedMap<LocalDate, BigDecimal> substract(
Map<LocalDate, BigDecimal> minuend,
Map<LocalDate, BigDecimal> subtrahend) {
final SortedMap<LocalDate, BigDecimal> result = new TreeMap<LocalDate, BigDecimal>();
forValuesAtSameKey(minuend, subtrahend, substractionOperation(result));
return result;
}
private static IOperation<LocalDate, BigDecimal> substractionOperation(
final SortedMap<LocalDate, BigDecimal> result) {
return notNullOperands(new IOperation<LocalDate, BigDecimal>() {
@Override
public void operate(LocalDate key, BigDecimal minuedValue,
BigDecimal subtrahendValue) {
result.put(key,
minuedValue.subtract(subtrahendValue));
}
@Override
public void undefinedFor(LocalDate key) {
}
});
}
private void calculateCostPerformanceIndex() {
// CPI = BCWP / ACWP
indicators.put(EarnedValueType.CPI,
divide(EarnedValueType.BCWP, EarnedValueType.ACWP,
BigDecimal.ZERO));
}
private void calculateSchedulePerformanceIndex() {
// SPI = BCWP / BCWS
indicators.put(EarnedValueType.SPI,
divide(EarnedValueType.BCWP, EarnedValueType.BCWS,
BigDecimal.ZERO));
}
private SortedMap<LocalDate, BigDecimal> divide(EarnedValueType dividend,
EarnedValueType divisor, BigDecimal defaultIfNotComputable) {
Validate.notNull(indicators.get(dividend));
Validate.notNull(indicators.get(divisor));
return divide(indicators.get(dividend), indicators.get(divisor),
defaultIfNotComputable);
}
private static SortedMap<LocalDate, BigDecimal> divide(
Map<LocalDate, BigDecimal> dividend,
Map<LocalDate, BigDecimal> divisor,
final BigDecimal defaultIfNotComputable) {
final TreeMap<LocalDate, BigDecimal> result = new TreeMap<LocalDate, BigDecimal>();
forValuesAtSameKey(dividend, divisor,
divisionOperation(result, defaultIfNotComputable));
return result;
}
private static IOperation<LocalDate, BigDecimal> divisionOperation(
final TreeMap<LocalDate, BigDecimal> result,
final BigDecimal defaultIfNotComputable) {
return notNullOperands(secondOperandNotZero(new IOperation<LocalDate, BigDecimal>() {
@Override
public void operate(LocalDate key, BigDecimal dividendValue,
BigDecimal divisorValue) {
result.put(key, dividendValue.divide(divisorValue,
RoundingMode.DOWN));
}
@Override
public void undefinedFor(LocalDate key) {
result.put(key, defaultIfNotComputable);
}
}));
}
protected abstract Set<EarnedValueType> getSelectedIndicators();
@Override
public void fillChart(Timeplot chart, Interval interval, Integer size) {
chart.getChildren().clear();
chart.invalidate();
resetMinimumAndMaximumValueForChart();
calculateValues(interval);
List<Plotinfo> plotinfos = new ArrayList<Plotinfo>();
for (EarnedValueType indicator : getSelectedIndicators()) {
Plotinfo plotinfo = createPlotInfo(indicators.get(indicator),
interval, indicator.getColor());
plotinfos.add(plotinfo);
}
if (plotinfos.isEmpty()) {
// If user doesn't select any indicator, it is needed to create
// a default Plotinfo in order to avoid errors on Timemplot
plotinfos.add(new Plotinfo());
}
ValueGeometry valueGeometry = getValueGeometry();
TimeGeometry timeGeometry = getTimeGeometry(interval);
for (Plotinfo plotinfo : plotinfos) {
appendPlotinfo(chart, plotinfo, valueGeometry, timeGeometry);
}
chart.setWidth(size + "px");
chart.setHeight("150px");
}
public Interval getIndicatorsDefinitionInterval() {
return indicatorsInterval;
}
/**
* Will try to use today if possible
* @return Today if there are values defined for that date. The last day in
* the interval otherwise
*/
public LocalDate initialDateForIndicatorValues() {
Interval chartInterval = getIndicatorsDefinitionInterval();
LocalDate today = new LocalDate();
return includes(chartInterval, today) ? today
: LocalDate.fromDateFields(chartInterval.getFinish());
}
protected void addZeroBeforeTheFirstValue(
SortedMap<LocalDate, BigDecimal> map) {
if (!map.isEmpty()) {
map.put(map.firstKey().minusDays(1), BigDecimal.ZERO);
}
}
}
|
package com.fsck.k9.mail.transport;
import com.fsck.k9.mail.store.TrustManagerFactory;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.LayeredSocketFactory;
import org.apache.http.params.HttpParams;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;
public class TrustedSocketFactory implements LayeredSocketFactory {
private SSLSocketFactory mSocketFactory;
private org.apache.http.conn.ssl.SSLSocketFactory mSchemeSocketFactory;
protected static final String ENABLED_CIPHERS[];
protected static final String ENABLED_PROTOCOLS[];
static {
String preferredCiphers[] = {
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
"TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
"TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
"TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
"TLS_ECDHE_RSA_WITH_RC4_128_SHA",
"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
"TLS_RSA_WITH_AES_128_CBC_SHA",
"TLS_RSA_WITH_AES_256_CBC_SHA",
"SSL_RSA_WITH_3DES_EDE_CBC_SHA",
"SSL_RSA_WITH_RC4_128_SHA",
"SSL_RSA_WITH_RC4_128_MD5",
};
String preferredProtocols[] = {
"TLSv1.2", "TLSv1.1", "TLSv1"
};
String[] supportedCiphers = null;
String[] supportedProtocols = null;
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, null, new SecureRandom());
SSLSocketFactory sf = sslContext.getSocketFactory();
supportedCiphers = sf.getSupportedCipherSuites();
SSLSocket sock = (SSLSocket)sf.createSocket();
supportedProtocols = sock.getSupportedProtocols();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (KeyManagementException kme) {
kme.printStackTrace();
} catch (NoSuchAlgorithmException nsae) {
nsae.printStackTrace();
}
ENABLED_CIPHERS = supportedCiphers == null ? null :
filterBySupport(preferredCiphers, supportedCiphers);
ENABLED_PROTOCOLS = supportedProtocols == null ? null :
filterBySupport(preferredProtocols, supportedProtocols);
}
protected static String[] filterBySupport(String[] preferred, String[] supported) {
List<String> enabled = new ArrayList<String>();
Set<String> available = new HashSet<String>();
Collections.addAll(available, supported);
for (String item : preferred) {
if (available.contains(item)) enabled.add(item);
}
return enabled.toArray(new String[enabled.size()]);
}
public TrustedSocketFactory(String host, boolean secure) throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] {
TrustManagerFactory.get(host, secure)
}, new SecureRandom());
mSocketFactory = sslContext.getSocketFactory();
mSchemeSocketFactory = org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
mSchemeSocketFactory.setHostnameVerifier(
org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}
public Socket connectSocket(Socket sock, String host, int port,
InetAddress localAddress, int localPort, HttpParams params)
throws IOException, UnknownHostException, ConnectTimeoutException {
return mSchemeSocketFactory.connectSocket(sock, host, port, localAddress, localPort, params);
}
public Socket createSocket() throws IOException {
return mSocketFactory.createSocket();
}
public boolean isSecure(Socket sock) throws IllegalArgumentException {
return mSchemeSocketFactory.isSecure(sock);
}
public static void hardenSocket(SSLSocket sock) {
if (ENABLED_CIPHERS != null) {
sock.setEnabledCipherSuites(ENABLED_CIPHERS);
}
if (ENABLED_PROTOCOLS != null) {
sock.setEnabledProtocols(ENABLED_PROTOCOLS);
}
}
public Socket createSocket(
final Socket socket,
final String host,
final int port,
final boolean autoClose
) throws IOException, UnknownHostException {
SSLSocket sslSocket = (SSLSocket) mSocketFactory.createSocket(
socket,
host,
port,
autoClose
);
//hostnameVerifier.verify(host, sslSocket);
// verifyHostName() didn't blowup - good!
hardenSocket(sslSocket);
return sslSocket;
}
}
|
// This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// Modifications:
// 2007 Jan 29: Modify to work with TestCase changes; rename to show that it's an integration test. - dj@opennms.org
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
package org.opennms.netmgt.threshd;
import org.opennms.netmgt.rrd.RrdUtils;
import org.opennms.test.mock.MockLogAppender;
public class LatencyThresholderIntegrationTest extends ThresholderTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
MockLogAppender.setupLogging();
setupDatabase();
createMockRrd();
setupEventManager();
replayMocks();
String dirName = "target/threshd-test/192.168.1.1";
String fileName = "icmp"+RrdUtils.getExtension();
int nodeId = 1;
String ipAddress = "192.168.1.1";
String serviceName = "ICMP";
String groupName = "icmp-latency";
setupThresholdConfig(dirName, fileName, nodeId, ipAddress, serviceName, groupName);
m_thresholder = new LatencyThresholder();
m_thresholder.initialize(m_serviceParameters);
m_thresholder.initialize(m_iface, m_parameters);
verifyMocks();
expectRrdStrategyCalls();
}
@Override
protected void tearDown() throws Exception {
RrdUtils.setStrategy(null);
MockLogAppender.assertNoWarningsOrGreater();
super.tearDown();
}
public void xtestIcmpDouble() throws Exception {
setupFetchSequence(new double[] { 69000.0, 79000.0, 74999.0, 74998.0 });
replayMocks();
ensureExceededAfterFetches("icmp-double", 3);
verifyMocks();
}
public void testNormalValue() throws Exception {
setupFetchSequence(new double[] { 69000.0, 79000.0, 74999.0, 74998.0 });
replayMocks();
ensureNoEventAfterFetches("icmp", 4);
verifyMocks();
}
public void testBigValue() throws Exception {
setupFetchSequence(new double[] { 79000.0, 80000.0, 84999.0, 84998.0, 97000.0 });
replayMocks();
ensureExceededAfterFetches("icmp", 3);
ensureNoEventAfterFetches("icmp", 2);
verifyMocks();
}
public void testRearm() throws Exception {
double values[] = {
79000.0,
80000.0,
84999.0, // expect exceeded
84998.0,
15000.0, // expect rearm
77000.0,
77000.0,
77000.0 // expect exceeded
};
setupFetchSequence(values);
replayMocks();
ensureExceededAfterFetches("icmp", 3);
ensureRearmedAfterFetches("icmp", 2);
ensureExceededAfterFetches("icmp", 3);
verifyMocks();
}
}
|
package com.jcwhatever.pvs.arenas.managers;
import com.jcwhatever.nucleus.events.manager.EventMethod;
import com.jcwhatever.nucleus.events.manager.IEventListener;
import com.jcwhatever.nucleus.storage.IDataNode;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.Rand;
import com.jcwhatever.pvs.api.PVStarAPI;
import com.jcwhatever.pvs.api.arena.ArenaTeam;
import com.jcwhatever.pvs.api.arena.IArena;
import com.jcwhatever.pvs.api.arena.IArenaPlayer;
import com.jcwhatever.pvs.api.arena.managers.ISpawnManager;
import com.jcwhatever.pvs.api.arena.options.ArenaContext;
import com.jcwhatever.pvs.api.arena.options.RemoveFromContextReason;
import com.jcwhatever.pvs.api.events.players.PlayerRemovedFromContextEvent;
import com.jcwhatever.pvs.api.events.spawns.ClearReservedSpawnsEvent;
import com.jcwhatever.pvs.api.events.spawns.ReserveSpawnEvent;
import com.jcwhatever.pvs.api.events.spawns.SpawnAddedEvent;
import com.jcwhatever.pvs.api.events.spawns.SpawnPreAddEvent;
import com.jcwhatever.pvs.api.events.spawns.SpawnPreRemoveEvent;
import com.jcwhatever.pvs.api.events.spawns.SpawnRemovedEvent;
import com.jcwhatever.pvs.api.events.spawns.UnreserveSpawnEvent;
import com.jcwhatever.pvs.api.spawns.SpawnType;
import com.jcwhatever.pvs.api.spawns.Spawnpoint;
import com.jcwhatever.pvs.arenas.AbstractArena;
import com.jcwhatever.pvs.arenas.context.AbstractContextManager;
import com.jcwhatever.pvs.spawns.SpawnpointsCollection;
import org.bukkit.Location;
import org.bukkit.plugin.Plugin;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Spawn manager implementation.
*/
public class SpawnManager extends SpawnpointsCollection implements ISpawnManager, IEventListener {
@Nullable
public static Spawnpoint getRespawnLocation(AbstractContextManager manager, ArenaContext context) {
PreCon.notNull(manager);
PreCon.notNull(context);
AbstractArena arena = manager.getArena();
List<Spawnpoint> spawns = arena.getSpawns().getAll(context);
if (spawns.isEmpty() && context == ArenaContext.LOBBY) {
spawns = arena.getSpawns().getAll(ArenaContext.GAME);
}
if (spawns.isEmpty())
return null;
return Rand.get(spawns);
}
private final Map<UUID, Spawnpoint> _reserved = new HashMap<>(15); // key is player id
private final IArena _arena;
private final IDataNode _dataNode;
/*
* Constructor.
*/
public SpawnManager(IArena arena) {
_arena = arena;
_dataNode = arena.getDataNode("spawns");
loadSettings();
arena.getEventManager().register(this);
}
@Override
public Plugin getPlugin() {
return PVStarAPI.getPlugin();
}
@Override
public IArena getArena() {
return _arena;
}
@Override
public boolean hasLobbySpawns() {
return !getAll(PVStarAPI.getSpawnTypeManager().getLobbySpawnType()).isEmpty();
}
@Override
public boolean hasGameSpawns() {
return !getAll(PVStarAPI.getSpawnTypeManager().getGameSpawnType()).isEmpty();
}
@Override
public boolean hasSpectatorSpawns() {
return !getAll(PVStarAPI.getSpawnTypeManager().getSpectatorSpawnType()).isEmpty();
}
@Override
public List<Spawnpoint> getAll(ArenaContext context) {
PreCon.notNull(context);
switch (context) {
case LOBBY:
return getAll(
PVStarAPI.getSpawnTypeManager().getLobbySpawnType());
case GAME:
return getAll(
PVStarAPI.getSpawnTypeManager().getGameSpawnType());
case SPECTATOR:
return getAll(
PVStarAPI.getSpawnTypeManager().getSpectatorSpawnType());
default:
return new ArrayList<>(0);
}
}
@Override
public List<Spawnpoint> getAll(ArenaTeam team, ArenaContext context) {
PreCon.notNull(team);
PreCon.notNull(context);
SpawnType type;
switch (context) {
case LOBBY:
type = PVStarAPI.getSpawnTypeManager().getLobbySpawnType();
break;
case GAME:
type = PVStarAPI.getSpawnTypeManager().getGameSpawnType();
break;
case SPECTATOR:
type = PVStarAPI.getSpawnTypeManager().getSpectatorSpawnType();
break;
default:
return new ArrayList<>(0);
}
return getAll(type, team);
}
@Override
public boolean add(Spawnpoint spawn) {
PreCon.notNull(spawn);
SpawnPreAddEvent event = new SpawnPreAddEvent(getArena(), spawn);
getArena().getEventManager().call(this, event);
if (event.isCancelled() || !super.add(spawn))
return false;
IDataNode node = _dataNode.getNode(spawn.getName());
node.set("type", spawn.getSpawnType().getName());
node.set("team", spawn.getTeam());
node.set("location", spawn);
node.save();
getArena().getEventManager().call(this, new SpawnAddedEvent(getArena(), spawn));
return true;
}
@Override
public void addAll(final Collection<? extends Spawnpoint> spawns) {
PreCon.notNull(spawns);
for (Spawnpoint spawn : spawns) {
add(spawn);
}
}
@Override
public boolean remove(Spawnpoint spawn) {
PreCon.notNull(spawn);
SpawnPreRemoveEvent preEvent = new SpawnPreRemoveEvent(getArena(), spawn);
getArena().getEventManager().call(this, preEvent);
if (preEvent.isCancelled() || !super.remove(spawn))
return false;
IDataNode node = _dataNode.getNode(spawn.getName());
node.remove();
node.save();
getArena().getEventManager().call(this, new SpawnRemovedEvent(getArena(), spawn));
return true;
}
@Override
public void removeAll(final Collection<? extends Spawnpoint> spawns) {
PreCon.notNull(spawns);
for (Spawnpoint spawn : spawns)
remove(spawn);
}
@Override
public void reserve(IArenaPlayer player, Spawnpoint spawn) {
PreCon.notNull(player);
PreCon.notNull(spawn);
ReserveSpawnEvent event = new ReserveSpawnEvent(getArena(), player, spawn);
getArena().getEventManager().call(this, event);
if (event.isCancelled())
return;
// remove spawn to prevent it's use
super.remove(spawn);
_reserved.put(player.getUniqueId(), spawn);
}
@Override
public void unreserve(IArenaPlayer player) {
PreCon.notNull(player);
Spawnpoint spawn = _reserved.remove(player.getUniqueId());
if (spawn == null)
return;
UnreserveSpawnEvent event = new UnreserveSpawnEvent(getArena(), player, spawn);
getArena().getEventManager().call(this, event);
if (event.isCancelled()) {
_reserved.put(player.getUniqueId(), spawn);
return;
}
super.add(spawn);
}
@Override
public void clearReserved() {
ClearReservedSpawnsEvent event = new ClearReservedSpawnsEvent(getArena());
getArena().getEventManager().call(this, event);
if (event.isCancelled())
return;
for (Spawnpoint spawn : _reserved.values()) {
super.add(spawn);
}
_reserved.clear();
}
@Override
public int totalReserved() {
return _reserved.size();
}
@Override
public int totalReserved(SpawnType spawnType) {
PreCon.notNull(spawnType);
int result = 0;
for (Spawnpoint spawn : _reserved.values()) {
if (spawn.getSpawnType().equals(spawnType))
result++;
}
return result;
}
/*
* Load spawn manager settings.
*/
private void loadSettings() {
for (IDataNode spawnNode : _dataNode) {
String typeName = spawnNode.getString("type");
Location location = spawnNode.getLocation("location");
ArenaTeam team = spawnNode.getEnum("team", ArenaTeam.class);
if (typeName == null || typeName.isEmpty())
continue;
if (location == null)
continue;
if (team == null)
continue;
SpawnType type = PVStarAPI.getSpawnTypeManager().getType(typeName);
if (type == null)
continue;
Spawnpoint spawnpoint = new Spawnpoint(spawnNode.getName(), type, team, location);
super.add(spawnpoint);
}
}
/*
* Un-reserve a spawn when a player leaves.
*/
@EventMethod
private void onPlayerRemoved(PlayerRemovedFromContextEvent event) {
if (event.getReason() == RemoveFromContextReason.CONTEXT_CHANGE)
return;
unreserve(event.getPlayer());
}
}
|
package org.eclipse.mylar.internal.trac.ui.wizard;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.mylar.core.MylarStatusHandler;
import org.eclipse.mylar.internal.trac.core.ITracClient;
import org.eclipse.mylar.internal.trac.core.TracCorePlugin;
import org.eclipse.mylar.internal.trac.core.TracException;
import org.eclipse.mylar.internal.trac.core.TracRepositoryConnector;
import org.eclipse.mylar.internal.trac.core.TracRepositoryQuery;
import org.eclipse.mylar.internal.trac.core.model.TracSearch;
import org.eclipse.mylar.internal.trac.core.model.TracSearchFilter;
import org.eclipse.mylar.internal.trac.core.model.TracSearchFilter.CompareOperator;
import org.eclipse.mylar.internal.trac.ui.TracUiPlugin;
import org.eclipse.mylar.tasks.core.AbstractRepositoryQuery;
import org.eclipse.mylar.tasks.core.TaskRepository;
import org.eclipse.mylar.tasks.core.TaskRepositoryManager;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
import org.eclipse.mylar.tasks.ui.search.AbstractRepositoryQueryPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;
/**
* Trac search page. Provides a form similar to the one the Bugzilla connector
* uses.
*
* @author Steffen Pingel
*/
public class TracCustomQueryPage extends AbstractRepositoryQueryPage {
private static final String TITLE = "Enter query parameters";
private static final String DESCRIPTION = "If attributes are blank or stale press the Update button.";
private static final String TITLE_QUERY_TITLE = "Query Title:";
private static final String[] DEFAULT_STATUS_SELECTION = new String[] { "new", "assigned", "reopened", };
private TracRepositoryQuery query;
private Text titleText;
private static final int PRODUCT_HEIGHT = 60;
private static final int STATUS_HEIGHT = 40;
protected final static String PAGE_NAME = "TracSearchPage"; //$NON-NLS-1$
private static final String SEARCH_URL_ID = PAGE_NAME + ".SEARCHURL";
protected Combo summaryText = null;
protected Combo repositoryCombo = null;
private TextSearchField summaryField;
private TextSearchField descriptionField;
private ListSearchField componentField;
private ListSearchField versionField;
private ListSearchField milestoneField;
private ListSearchField priorityField;
private ListSearchField typeField;
private ListSearchField resolutionField;
private ListSearchField statusField;
private Button updateButton;
private TextSearchField keywordsField;
private Map<String, SearchField> searchFieldByName = new HashMap<String, SearchField>();
private boolean firstTime = true;
// private UserSearchField ownerField;
// private UserSearchField reporterField;
// private UserSearchField ccField;
public TracCustomQueryPage(TaskRepository repository, AbstractRepositoryQuery query) {
super(TITLE);
this.repository = repository;
this.query = (TracRepositoryQuery) query;
setTitle(TITLE);
setDescription(DESCRIPTION);
}
public TracCustomQueryPage(TaskRepository repository) {
this(repository, null);
}
@Override
public void createControl(Composite parent) {
Composite control = new Composite(parent, SWT.NONE);
GridData gd = new GridData(GridData.FILL_BOTH);
control.setLayoutData(gd);
GridLayout layout = new GridLayout(4, false);
if (inSearchContainer()) {
layout.marginWidth = 0;
layout.marginHeight = 0;
}
control.setLayout(layout);
createTitleGroup(control);
summaryField = new TextSearchField("summary");
summaryField.createControls(control, "Summary");
descriptionField = new TextSearchField("description");
descriptionField.createControls(control, "Description");
keywordsField = new TextSearchField("keywords");
keywordsField.createControls(control, "Keywords");
createOptionsGroup(control);
createUserGroup(control);
if (query != null) {
titleText.setText(query.getSummary());
restoreWidgetValues(query.getTracSearch());
}
setControl(control);
}
@Override
public boolean canFlipToNextPage() {
return false;
}
private void restoreWidgetValues(TracSearch search) {
java.util.List<TracSearchFilter> filters = search.getFilters();
for (TracSearchFilter filter : filters) {
SearchField field = searchFieldByName.get(filter.getFieldName());
if (field != null) {
field.setFilter(filter);
} else {
MylarStatusHandler.log("Ignoring invalid search filter: " + filter, this);
}
}
}
private void createTitleGroup(Composite control) {
if (inSearchContainer()) {
return;
}
Label titleLabel = new Label(control, SWT.NONE);
titleLabel.setText(TITLE_QUERY_TITLE);
titleText = new Text(control, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
gd.horizontalSpan = 3;
titleText.setLayoutData(gd);
titleText.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
// ignore
}
public void keyReleased(KeyEvent e) {
getContainer().updateButtons();
}
});
}
protected Control createOptionsGroup(Composite control) {
Group group = new Group(control, SWT.NONE);
// group.setText("Ticket Attributes");
GridLayout layout = new GridLayout();
layout.numColumns = 1;
group.setLayout(layout);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.horizontalSpan = 4;
group.setLayoutData(gd);
createProductAttributes(group);
createTicketAttributes(group);
createUpdateButton(group);
return group;
}
protected void createUserGroup(Composite control) {
UserSearchField userField = new UserSearchField();
userField.createControls(control);
}
/**
* Creates the area for selection on product attributes
* component/version/milestone.
*/
protected Control createProductAttributes(Composite control) {
Composite group = new Composite(control, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 3;
group.setLayout(layout);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.horizontalSpan = 1;
group.setLayoutData(gd);
Label label = new Label(group, SWT.LEFT);
label.setText("Component");
label = new Label(group, SWT.LEFT);
label.setText("Version");
label = new Label(group, SWT.LEFT);
label.setText("Milestone");
componentField = new ListSearchField("component");
componentField.createControls(group, PRODUCT_HEIGHT);
versionField = new ListSearchField("version");
versionField.createControls(group, PRODUCT_HEIGHT);
milestoneField = new ListSearchField("milestone");
milestoneField.createControls(group, PRODUCT_HEIGHT);
return group;
}
/**
* Creates the area for selection of ticket attributes
* status/resolution/priority.
*/
protected Control createTicketAttributes(Composite control) {
Composite group = new Composite(control, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 4;
group.setLayout(layout);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.horizontalSpan = 1;
group.setLayoutData(gd);
Label label = new Label(group, SWT.LEFT);
label.setText("Status");
label = new Label(group, SWT.LEFT);
label.setText("Resolution");
label = new Label(group, SWT.LEFT);
label.setText("Type");
label = new Label(group, SWT.LEFT);
label.setText("Priority");
statusField = new ListSearchField("status");
statusField.createControls(group, STATUS_HEIGHT);
resolutionField = new ListSearchField("resolution");
resolutionField.createControls(group, STATUS_HEIGHT);
typeField = new ListSearchField("type");
typeField.createControls(group, STATUS_HEIGHT);
priorityField = new ListSearchField("priority");
priorityField.createControls(group, STATUS_HEIGHT);
return group;
}
protected Control createUpdateButton(final Composite control) {
Composite group = new Composite(control, SWT.NONE);
GridLayout layout = new GridLayout(2, false);
group.setLayout(layout);
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
updateButton = new Button(group, SWT.PUSH);
updateButton.setText("Update Attributes from Repository");
updateButton.setLayoutData(new GridData());
updateButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (repository != null) {
updateAttributesFromRepository(true);
} else {
MessageDialog.openInformation(Display.getCurrent().getActiveShell(),
TracUiPlugin.TITLE_MESSAGE_DIALOG, TaskRepositoryManager.MESSAGE_NO_REPOSITORY);
}
}
});
return group;
}
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (scontainer != null) {
scontainer.setPerformActionEnabled(true);
}
if (visible && firstTime) {
firstTime = false;
if (!hasAttributes()) {
// delay the execution so the dialog's progress bar is visible
// when the attributes are updated
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (getControl() != null && !getControl().isDisposed()) {
initializePage();
}
}
});
} else {
// no remote connection is needed to get attributes therefore do
// not use delayed execution to avoid flickering
initializePage();
}
}
}
private void initializePage() {
updateAttributesFromRepository(false);
boolean restored = (query != null);
if (inSearchContainer()) {
restored |= restoreWidgetValues();
}
// initialize with default values
if (!restored) {
statusField.selectItems(DEFAULT_STATUS_SELECTION);
}
}
private boolean hasAttributes() {
TracRepositoryConnector connector = (TracRepositoryConnector) TasksUiPlugin.getRepositoryManager()
.getRepositoryConnector(TracCorePlugin.REPOSITORY_KIND);
try {
ITracClient client = connector.getClientManager().getRepository(repository);
return client.hasAttributes();
} catch (MalformedURLException e) {
return false;
}
}
private void updateAttributesFromRepository(final boolean force) {
TracRepositoryConnector connector = (TracRepositoryConnector) TasksUiPlugin.getRepositoryManager()
.getRepositoryConnector(TracCorePlugin.REPOSITORY_KIND);
final ITracClient client;
try {
client = connector.getClientManager().getRepository(repository);
} catch (MalformedURLException e) {
TracUiPlugin.handleTracException(e);
return;
}
if (!client.hasAttributes() || force) {
try {
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
client.updateAttributes(monitor, force);
} catch (TracException e) {
throw new InvocationTargetException(e);
}
}
};
if (getContainer() != null) {
getContainer().run(true, true, runnable);
} else if (scontainer != null) {
scontainer.getRunnableContext().run(true, true, runnable);
} else {
IProgressService service = PlatformUI.getWorkbench().getProgressService();
service.run(true, true, runnable);
}
} catch (InvocationTargetException e) {
TracUiPlugin.handleTracException(e.getCause());
return;
} catch (InterruptedException e) {
return;
}
}
statusField.setValues(client.getTicketStatus());
resolutionField.setValues(client.getTicketResolutions());
typeField.setValues(client.getTicketTypes());
priorityField.setValues(client.getPriorities());
componentField.setValues(client.getComponents());
versionField.setValues(client.getVersions());
milestoneField.setValues(client.getMilestones());
}
public TaskRepository getRepository() {
return repository;
}
public void setRepository(TaskRepository repository) {
this.repository = repository;
}
@Override
public boolean isPageComplete() {
if (titleText != null && titleText.getText().length() > 0) {
return true;
}
return false;
}
public String getQueryUrl(String repsitoryUrl) {
TracSearch search = getTracSearch();
StringBuilder sb = new StringBuilder();
sb.append(repsitoryUrl);
sb.append(ITracClient.QUERY_URL);
sb.append(search.toUrl());
return sb.toString();
}
private TracSearch getTracSearch() {
TracSearch search = new TracSearch();
for (SearchField field : searchFieldByName.values()) {
TracSearchFilter filter = field.getFilter();
if (filter != null) {
search.addFilter(filter);
}
}
return search;
}
@Override
public TracRepositoryQuery getQuery() {
return new TracRepositoryQuery(repository.getUrl(), getQueryUrl(repository.getUrl()), getTitleText(),
TasksUiPlugin.getTaskListManager().getTaskList());
}
private String getTitleText() {
return (titleText != null) ? titleText.getText() : "<search>";
}
// public boolean performAction() {
// Proxy proxySettings = TasksUiPlugin.getDefault().getProxySettings();
// SearchHitCollector collector = new
// SearchHitCollector(TasksUiPlugin.getTaskListManager().getTaskList(),
// repository, getQuery(), proxySettings);
// NewSearchUI.runQueryInBackground(collector);
// return true;
@Override
public boolean performAction() {
if (inSearchContainer()) {
saveWidgetValues();
}
return super.performAction();
}
public IDialogSettings getDialogSettings() {
IDialogSettings settings = TracUiPlugin.getDefault().getDialogSettings();
IDialogSettings dialogSettings = settings.getSection(PAGE_NAME);
if (dialogSettings == null) {
dialogSettings = settings.addNewSection(PAGE_NAME);
}
return dialogSettings;
}
private boolean restoreWidgetValues() {
IDialogSettings settings = getDialogSettings();
String repoId = "." + repository.getUrl();
String searchUrl = settings.get(SEARCH_URL_ID + repoId);
if (searchUrl == null) {
return false;
}
restoreWidgetValues(new TracSearch(searchUrl));
return true;
}
public void saveWidgetValues() {
String repoId = "." + repository.getUrl();
IDialogSettings settings = getDialogSettings();
settings.put(SEARCH_URL_ID + repoId, getTracSearch().toUrl());
}
private abstract class SearchField {
protected String fieldName;
public SearchField(String fieldName) {
this.fieldName = fieldName;
if (fieldName != null) {
assert !searchFieldByName.containsKey(fieldName);
searchFieldByName.put(fieldName, this);
}
}
public String getFieldName() {
return fieldName;
}
public abstract TracSearchFilter getFilter();
public abstract void setFilter(TracSearchFilter filter);
}
private class TextSearchField extends SearchField {
private Combo conditionCombo;
protected Text searchText;
private Label label;
private CompareOperator[] compareOperators = { CompareOperator.CONTAINS, CompareOperator.CONTAINS_NOT,
CompareOperator.BEGINS_WITH, CompareOperator.ENDS_WITH, CompareOperator.IS, CompareOperator.IS_NOT, };
public TextSearchField(String fieldName) {
super(fieldName);
}
public void createControls(Composite parent, String labelText) {
if (labelText != null) {
label = new Label(parent, SWT.LEFT);
label.setText(labelText);
}
conditionCombo = new Combo(parent, SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY);
for (CompareOperator op : compareOperators) {
conditionCombo.add(op.toString());
}
conditionCombo.setText(compareOperators[0].toString());
searchText = new Text(parent, SWT.BORDER);
GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
// the user search field has additional controls and no fieldName
if (fieldName != null) {
gd.horizontalSpan = 2;
}
searchText.setLayoutData(gd);
}
public CompareOperator getCondition() {
return compareOperators[conditionCombo.getSelectionIndex()];
}
public String getSearchText() {
return searchText.getText();
}
public boolean setCondition(CompareOperator operator) {
if (conditionCombo != null) {
int i = conditionCombo.indexOf(operator.toString());
if (i != -1) {
conditionCombo.select(i);
return true;
}
}
return false;
}
public void setSearchText(String text) {
searchText.setText(text);
}
@Override
public TracSearchFilter getFilter() {
String text = getSearchText();
if (text.length() == 0) {
return null;
}
TracSearchFilter newFilter = new TracSearchFilter(getFieldName());
newFilter.setOperator(getCondition());
newFilter.addValue(getSearchText());
return newFilter;
}
@Override
public void setFilter(TracSearchFilter filter) {
setCondition(filter.getOperator());
java.util.List<String> values = filter.getValues();
setSearchText(values.get(0));
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
}
private class ListSearchField extends SearchField {
private List list;
public ListSearchField(String fieldName) {
super(fieldName);
}
public void setValues(Object[] items) {
// preserve selected values
TracSearchFilter filter = getFilter();
list.removeAll();
if (items != null) {
list.setEnabled(true);
for (Object item : items) {
list.add(item.toString());
}
// restore selected values
if (filter != null) {
setFilter(filter);
}
} else {
list.setEnabled(false);
}
}
public void createControls(Composite parent, int height) {
list = new List(parent, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.heightHint = height;
list.setLayoutData(gd);
}
@Override
public TracSearchFilter getFilter() {
int[] indicies = list.getSelectionIndices();
if (indicies.length == 0) {
return null;
}
TracSearchFilter newFilter = new TracSearchFilter(getFieldName());
newFilter.setOperator(CompareOperator.IS);
for (int i : indicies) {
newFilter.addValue(list.getItem(i));
}
return newFilter;
}
@Override
public void setFilter(TracSearchFilter filter) {
list.deselectAll();
java.util.List<String> values = filter.getValues();
for (String item : values) {
int i = list.indexOf(item);
if (i != -1) {
list.select(i);
} else {
list.add(item, 0);
list.select(0);
}
}
}
public void selectItems(String[] items) {
list.deselectAll();
for (String item : items) {
int i = list.indexOf(item);
if (i != -1) {
list.select(i);
}
}
}
}
private class UserSearchField extends SearchField {
private TextSearchField textField;
private Combo userCombo;
public UserSearchField() {
super(null);
textField = new TextSearchField(null);
new UserSelectionSearchField("owner", 0);
new UserSelectionSearchField("reporter", 1);
new UserSelectionSearchField("cc", 2);
}
public void createControls(Composite parent) {
userCombo = new Combo(parent, SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY);
userCombo.add("Owner");
userCombo.add("Reporter");
userCombo.add("CC");
userCombo.select(0);
textField.createControls(parent, null);
}
@Override
public TracSearchFilter getFilter() {
return null;
}
@Override
public void setFilter(TracSearchFilter filter) {
}
private void setSelection(int index) {
userCombo.select(index);
}
private int getSelection() {
return userCombo.getSelectionIndex();
}
class UserSelectionSearchField extends SearchField {
private int index;
public UserSelectionSearchField(String fieldName, int index) {
super(fieldName);
this.index = index;
}
@Override
public TracSearchFilter getFilter() {
if (index == getSelection()) {
textField.setFieldName(fieldName);
return textField.getFilter();
}
return null;
}
@Override
public void setFilter(TracSearchFilter filter) {
textField.setFieldName(fieldName);
textField.setFilter(filter);
setSelection(index);
}
}
}
}
|
package com.jetbrains.ther.parsing;
import com.intellij.lang.PsiBuilder;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.tree.IElementType;
import com.jetbrains.ther.lexer.TheRTokenTypes;
import org.jetbrains.annotations.NotNull;
public class TheRStatementParsing extends Parsing {
private static final Logger LOG = Logger.getInstance(TheRStatementParsing.class.getName());
public TheRStatementParsing(@NotNull final TheRParsingContext context) {
super(context);
}
public void parseStatement() {
IElementType firstToken = myBuilder.getTokenType();
if (firstToken == null) return;
if (firstToken == TheRTokenTypes.STATEMENT_BREAK) {
myBuilder.advanceLexer();
firstToken = myBuilder.getTokenType();
}
if (firstToken == TheRTokenTypes.IF_KEYWORD) {
parseIfStatement();
return;
}
if (firstToken == TheRTokenTypes.WHILE_KEYWORD) {
parseWhileStatement();
return;
}
if (firstToken == TheRTokenTypes.FOR_KEYWORD) {
parseForStatement();
return;
}
if (firstToken == TheRTokenTypes.REPEAT_KEYWORD) {
parseRepeatStatement();
return;
}
if (firstToken == TheRTokenTypes.BREAK_KEYWORD) {
parseBreakStatement();
return;
}
if (firstToken == TheRTokenTypes.NEXT_KEYWORD) {
parseNextStatement();
return;
}
if (firstToken == TheRTokenTypes.LBRACE) {
parseBlock();
return;
}
parseSimpleStatement();
}
private void checkSemicolon() {
if (myBuilder.getTokenType() == TheRTokenTypes.SEMICOLON) {
myBuilder.advanceLexer();
if (myBuilder.getTokenType() == TheRTokenTypes.STATEMENT_BREAK) {
myBuilder.advanceLexer();
}
}
}
protected void parseSimpleStatement() {
final IElementType tokenType = myBuilder.getTokenType();
if (tokenType == null) return;
final PsiBuilder.Marker exprStatement = myBuilder.mark();
final TheRExpressionParsing expressionParser = getExpressionParser();
final boolean successfull = expressionParser.parseExpression();
if (successfull) {
if (TheRTokenTypes.ASSIGNMENTS.contains(myBuilder.getTokenType())) {
myBuilder.advanceLexer();
if (myBuilder.getTokenType() == TheRTokenTypes.FUNCTION_KEYWORD) {
getFunctionParser().parseFunctionDeclaration();
}
else if (!expressionParser.parseExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
}
checkSemicolon();
exprStatement.done(TheRElementTypes.ASSIGNMENT_STATEMENT);
}
else {
checkSemicolon();
exprStatement.done(TheRElementTypes.EXPRESSION_STATEMENT);
}
return;
}
else
exprStatement.drop();
myBuilder.advanceLexer();
myBuilder.error("Statement expected, found " + tokenType.toString());
}
private void parseIfStatement() {
LOG.assertTrue(myBuilder.getTokenType() == TheRTokenTypes.IF_KEYWORD);
final PsiBuilder.Marker ifStatement = myBuilder.mark();
myBuilder.advanceLexer();
checkMatches(TheRTokenTypes.LPAR, "( expected");
getExpressionParser().parseExpression();
checkMatches(TheRTokenTypes.RPAR, ") expected");
parseStatement();
if (myBuilder.getTokenType() == TheRTokenTypes.ELSE_KEYWORD) {
myBuilder.advanceLexer();
parseStatement();
}
checkSemicolon();
ifStatement.done(TheRElementTypes.IF_STATEMENT);
}
private void parseRepeatStatement() {
LOG.assertTrue(myBuilder.getTokenType() == TheRTokenTypes.REPEAT_KEYWORD);
final PsiBuilder.Marker statement = myBuilder.mark();
myBuilder.advanceLexer();
parseStatement();
checkSemicolon();
statement.done(TheRElementTypes.REPEAT_STATEMENT);
}
private void parseBreakStatement() {
LOG.assertTrue(myBuilder.getTokenType() == TheRTokenTypes.BREAK_KEYWORD);
final PsiBuilder.Marker statement = myBuilder.mark();
myBuilder.advanceLexer();
if (myBuilder.getTokenType() == TheRTokenTypes.LPAR) {
myBuilder.advanceLexer();
checkMatches(TheRTokenTypes.RPAR, ") expected");
}
checkSemicolon();
statement.done(TheRElementTypes.BREAK_STATEMENT);
}
private void parseNextStatement() {
LOG.assertTrue(myBuilder.getTokenType() == TheRTokenTypes.BREAK_KEYWORD);
final PsiBuilder.Marker statement = myBuilder.mark();
myBuilder.advanceLexer();
checkMatches(TheRTokenTypes.LPAR, "( expected");
checkMatches(TheRTokenTypes.RPAR, ") expected");
checkSemicolon();
statement.done(TheRElementTypes.NEXT_STATEMENT);
}
private void parseWhileStatement() {
LOG.assertTrue(myBuilder.getTokenType() == TheRTokenTypes.WHILE_KEYWORD);
final PsiBuilder.Marker statement = myBuilder.mark();
myBuilder.advanceLexer();
checkMatches(TheRTokenTypes.LPAR, "( expected");
getExpressionParser().parseExpression();
checkMatches(TheRTokenTypes.RPAR, ") expected");
parseStatement();
checkSemicolon();
statement.done(TheRElementTypes.WHILE_STATEMENT);
}
private void parseForStatement() {
LOG.assertTrue(myBuilder.getTokenType() == TheRTokenTypes.FOR_KEYWORD);
final PsiBuilder.Marker statement = myBuilder.mark();
myBuilder.advanceLexer();
checkMatches(TheRTokenTypes.LPAR, "( expected");
getExpressionParser().parseExpression();
if (myBuilder.getTokenType() == TheRTokenTypes.IN_KEYWORD) {
myBuilder.advanceLexer();
getExpressionParser().parseExpression();
}
else {
myBuilder.error("in expected");
}
checkMatches(TheRTokenTypes.RPAR, ") expected");
parseStatement();
checkSemicolon();
statement.done(TheRElementTypes.FOR_STATEMENT);
}
public void parseBlock() {
if (myBuilder.getTokenType() == TheRTokenTypes.STATEMENT_BREAK) {
myBuilder.advanceLexer();
}
if (myBuilder.getTokenType() != TheRTokenTypes.LBRACE) {
myBuilder.error("statements block expected");
return;
}
final PsiBuilder.Marker block = myBuilder.mark();
myBuilder.advanceLexer();
while (myBuilder.getTokenType() != TheRTokenTypes.RBRACE) {
if (myBuilder.eof()) {
myBuilder.error("missing }");
block.done(TheRElementTypes.BLOCK);
return;
}
parseSourceElement();
}
myBuilder.advanceLexer();
checkSemicolon();
block.done(TheRElementTypes.BLOCK);
}
public void parseSourceElement() {
if (myBuilder.getTokenType() == TheRTokenTypes.FUNCTION_KEYWORD) {
getFunctionParser().parseFunctionDeclaration();
}
else {
getStatementParser().parseStatement();
}
}
}
|
package org.eclipse.titan.designer.wizards.projectFormat;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.eclipse.core.filesystem.URIUtil;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IPathVariableManager;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.titan.common.logging.ErrorReporter;
import org.eclipse.titan.common.path.TITANPathUtilities;
import org.eclipse.titan.common.path.TitanURIUtil;
import org.eclipse.titan.common.utils.IOUtils;
import org.eclipse.titan.designer.Activator;
import org.eclipse.titan.designer.GeneralConstants;
import org.eclipse.titan.designer.consoles.TITANDebugConsole;
import org.eclipse.titan.designer.core.TITANNature;
import org.eclipse.titan.designer.graphics.ImageCache;
import org.eclipse.titan.designer.productUtilities.ProductConstants;
import org.eclipse.titan.designer.properties.data.DOMErrorHandlerImpl;
import org.eclipse.titan.designer.properties.data.ProjectBuildPropertyData;
import org.eclipse.titan.designer.properties.data.ProjectDocumentHandlingUtility;
import org.eclipse.titan.designer.properties.data.ProjectFileHandler;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.progress.IProgressConstants;
import org.osgi.framework.Bundle;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSParser;
import org.xml.sax.SAXException;
/**
* This class should be the importation of modules described in a provided Tpd
* file.
*
* @author Kristof Szabados
* */
public class TpdImporter {
private static final String CREATING_PROJECT = "creating project";
private static final String CREATION_FAILED = "Project creation failed";
private static final String TPD_XSD = "schema/TPD.xsd";
private DOMImplementationLS domImplLS;
private LSParser parser;
private DOMConfiguration config;
private Map<String, String> finalProjectNames = new HashMap<String, String>();
private Map<URI, Document> projectsToImport = new HashMap<URI, Document>();
private List<URI> importChain = new ArrayList<URI>();
private boolean wasAutoBuilding;
private Shell shell;
private final boolean headless;
private List<String> searchPaths;
private Map<String, String> tpdNameAttrMap = new HashMap<String, String>();
private Map<String, String> tpdURIMap = new HashMap<String, String>();
public TpdImporter(final Shell shell, final boolean headless) {
this.shell = shell;
this.headless = headless;
IWorkspaceDescription description = ResourcesPlugin.getWorkspace().getDescription();
wasAutoBuilding = description.isAutoBuilding();
description.setAutoBuilding(false);
try {
ResourcesPlugin.getWorkspace().setDescription(description);
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace("while disabling autobuild on the workspace", e);
}
Activator.getDefault().pauseHandlingResourceChanges();
}
/**
* Internal function used to do the import job. It is needed to extract this
* functionality in order to be able to handle erroneous situations.
*
* @param projectFile
* the file path string of the project descriptor file (tpd)
* @param projectsCreated
* the list of projects created so far. In case of problems we
* will try to delete them.
* @param monitor
* the monitor used to report progress.
*
* @return true if the import was successful, false otherwise.
* */
public boolean internalFinish(final String projectFile, final boolean isSkipExistingProjects,
final boolean isOpenPropertiesForAllImports, final List<IProject> projectsCreated, final IProgressMonitor monitor,
final List<String> searchPaths) {
if (projectFile == null || "".equals(projectFile.trim())) {
return false;
}
if(searchPaths != null) {
this.searchPaths = new ArrayList<String>(searchPaths);
}
System.setProperty(DOMImplementationRegistry.PROPERTY, ProjectFormatConstants.DOM_IMPLEMENTATION_SOURCE);
DOMImplementationRegistry registry = null;
try {
registry = DOMImplementationRegistry.newInstance();
} catch (Exception e) {
ErrorReporter.logExceptionStackTrace("While importing from `" + projectFile + "'", e);
activatePreviousSettings();
return false;
}
// Specifying "LS 3.0" in the features list ensures that the
// DOMImplementation
// object implements the load and save features of the DOM 3.0
// specification.
final DOMImplementation domImpl = registry.getDOMImplementation(ProjectFormatConstants.LOAD_SAVE_VERSION);
domImplLS = (DOMImplementationLS) domImpl;
// If the mode is MODE_SYNCHRONOUS, the parse and parseURI
// methods of the LSParser
// object return the org.w3c.dom.Document object. If the mode is
// MODE_ASYNCHRONOUS, the parse and parseURI methods return null.
parser = domImplLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, ProjectFormatConstants.XML_SCHEMA);
config = parser.getDomConfig();
DOMErrorHandlerImpl errorHandler = new DOMErrorHandlerImpl();
config.setParameter("error-handler", errorHandler);
config.setParameter("validate", Boolean.TRUE);
config.setParameter("schema-type", ProjectFormatConstants.XML_SCHEMA);
config.setParameter("well-formed", Boolean.TRUE);
config.setParameter("validate-if-schema", Boolean.TRUE);
Validator tpdValidator = null;
try {
final Schema tpdXsd = getTPDSchema();
tpdValidator = tpdXsd.newValidator();
} catch (Exception e) {
ErrorReporter.INTERNAL_ERROR(e.getMessage());
// Hint: cp $TTCN3_DIR/etc/xsd/TPD.xsd designer/schema/
}
URI resolvedProjectFileURI = TITANPathUtilities.resolvePath(projectFile, (URI) null);
// Loading all URI Documents (tpds)
// and collect projects to be imported
if (!loadURIDocuments(resolvedProjectFileURI, tpdValidator)) {
return false;
}
final SubMonitor progress = SubMonitor.convert(monitor, 3);
progress.setTaskName("Loading data");
IProgressMonitor projectCreationMonitor = progress.newChild(1);
projectCreationMonitor.beginTask("Creating required projects", projectsToImport.size());
// Create projects and
// store load location
// (where they are loaded from)
Map<URI, IProject> projectMap = new HashMap<URI, IProject>();
for (URI file : projectsToImport.keySet()) {
Document actualDocument = projectsToImport.get(file);
IProject project = createProject(actualDocument.getDocumentElement(), file.equals(resolvedProjectFileURI) || !isSkipExistingProjects);
if (project == null) {
projectCreationMonitor.worked(1);
continue;
}
projectsCreated.add(project);
projectMap.put(file, project);
try {
project.setPersistentProperty(
new QualifiedName(ProjectBuildPropertyData.QUALIFIER, ProjectBuildPropertyData.LOAD_LOCATION), file.getPath()
.toString());
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace("While loading referenced project from `" + file.getPath() + "'", e);
}
projectCreationMonitor.worked(1);
}
projectCreationMonitor.done();
IProgressMonitor normalInformationLoadingMonitor = progress.newChild(1);
normalInformationLoadingMonitor.beginTask("Loading directly stored project information", projectsToImport.size());
//Load Project Data from all projects:
for (URI file : projectsToImport.keySet()) {
if (!projectMap.containsKey(file)) {
normalInformationLoadingMonitor.worked(1);
continue;
}
IProject project = projectMap.get(file);
IPath projectFileFolderPath = new Path(file.getPath()).removeLastSegments(1);
URI projectFileFolderURI = URIUtil.toURI(projectFileFolderPath);
Document actualDocument = projectsToImport.get(file);
if (this.searchPaths != null && !this.searchPaths.isEmpty()) {
String tpdNameAttrVal = tpdNameAttrMap.get(project.getName());
String tpdURIVal = tpdURIMap.get(project.getName());
if (tpdNameAttrVal != null) {
try {
project.setPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, ProjectBuildPropertyData.USE_TPD_NAME),
tpdNameAttrVal);
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace("While setting `useTpdName' for project `" + project.getName() + "'", e);
}
}
if (tpdURIVal != null) {
try {
project.setPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, ProjectBuildPropertyData.ORIG_TPD_URI),
tpdURIVal);
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace("While setting `origTpdURI' for project `" + project.getName() + "'", e);
}
}
}
Element mainElement = actualDocument.getDocumentElement();
if (!loadProjectDataFromNode(mainElement, project, projectFileFolderURI)) {
return false;
}
normalInformationLoadingMonitor.worked(1);
}
normalInformationLoadingMonitor.done();
//Load information from packed projects
IPath mainProjectFileFolderPath = new Path(resolvedProjectFileURI.getPath()).removeLastSegments(1);
URI mainProjectFileFolderURI = URIUtil.toURI(mainProjectFileFolderPath);
List<Node> packedProjects = loadPackedProjects(projectsToImport.get(resolvedProjectFileURI));
IProgressMonitor packedInformationLoadingMonitor = progress.newChild(1);
packedInformationLoadingMonitor.beginTask("Loading packed project information", packedProjects.size());
for (Node node : packedProjects) {
IProject project = createProject(node, false);
if (project == null) {
packedInformationLoadingMonitor.worked(1);
continue;
}
projectsCreated.add(project);
try {
project.setPersistentProperty(
new QualifiedName(ProjectBuildPropertyData.QUALIFIER, ProjectBuildPropertyData.LOAD_LOCATION),
resolvedProjectFileURI.toString());
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace("While loading packed project `" + project.getName() + "'", e);
}
if (!loadProjectDataFromNode(node, project, mainProjectFileFolderURI)) {
return false;
}
packedInformationLoadingMonitor.worked(1);
}
packedInformationLoadingMonitor.done();
IProject mainProject = projectMap.get(resolvedProjectFileURI);
if (mainProject == null) {
progress.done();
return false;
}
try {
mainProject.setPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, ProjectBuildPropertyData.USE_TPD_NAME),
mainProject.getName() + ".tpd");
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace("While setting `useTpdName' for project `" + mainProject.getName() + "'", e);
}
List<WorkspaceJob> jobs = new ArrayList<WorkspaceJob>();
List<IProject> projectsToBeConfigured;
if (isOpenPropertiesForAllImports) {
projectsToBeConfigured = projectsCreated;
} else {
projectsToBeConfigured = new ArrayList<IProject>();
projectsToBeConfigured.add(mainProject);
}
if (!headless) {
for (final IProject project : projectsToBeConfigured) {
WorkspaceJob loadJob = new WorkspaceJob("Property initilizer for " + project.getName()) {
@Override
public IStatus runInWorkspace(final IProgressMonitor monitor) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
PreferenceDialog dialog = PreferencesUtil.createPropertyDialogOn(null, project,
GeneralConstants.PROJECT_PROPERTY_PAGE, null, null);
if (dialog != null) {
dialog.open();
}
}
});
return Status.OK_STATUS;
}
};
loadJob.setUser(false);
loadJob.setSystem(true);
loadJob.setRule(project.getWorkspace().getRuleFactory().refreshRule(project));
loadJob.setProperty(IProgressConstants.ICON_PROPERTY, ImageCache.getImageDescriptor("titan.gif"));
loadJob.schedule();
jobs.add(loadJob);
}
for (WorkspaceJob job : jobs) {
try {
job.join();
} catch (InterruptedException e) {
ErrorReporter.logExceptionStackTrace("Interrupted while performing: " + job.getName(), e);
}
}
}
activatePreviousSettings();
progress.done();
return true;
}
public static void validateTpd(final File tpdFile) throws IOException, SAXException {
final Schema tpdXsd = getTPDSchema();
Validator validator = tpdXsd.newValidator();
validator.validate(new StreamSource(tpdFile));
}
public static Schema getTPDSchema() throws IOException, SAXException {
Bundle bundle = Platform.getBundle(ProductConstants.PRODUCT_ID_DESIGNER);
InputStream xsdInputStream = null;
try {
xsdInputStream = FileLocator.openStream(bundle, new Path(TPD_XSD), false);
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema result = factory.newSchema(new StreamSource(xsdInputStream));
xsdInputStream.close();
return result;
} finally {
IOUtils.closeQuietly(xsdInputStream);
}
}
private void activatePreviousSettings() {
IWorkspaceDescription description = ResourcesPlugin.getWorkspace().getDescription();
if (description.isAutoBuilding() != wasAutoBuilding) {
description.setAutoBuilding(wasAutoBuilding);
try {
ResourcesPlugin.getWorkspace().setDescription(description);
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace("Resetting autobuild settings to" + wasAutoBuilding, e);
}
}
Activator.getDefault().resumeHandlingResourceChanges();
}
/**
* Collects the list of packed projects from the provided document.
*
* @param document
* the document to check.
*
* @return the list of found packed projects, an empty list if none.
* */
private List<Node> loadPackedProjects(final Document document) {
NodeList referencedProjectsList = document.getDocumentElement().getChildNodes();
Node packed = ProjectFileHandler.getNodebyName(referencedProjectsList, ProjectFormatConstants.PACKED_REFERENCED_PROJECTS_NODE);
if (packed == null) {
return new ArrayList<Node>();
}
List<Node> result = new ArrayList<Node>();
NodeList projects = packed.getChildNodes();
for (int i = 0, size = projects.getLength(); i < size; i++) {
Node referencedProjectNode = projects.item(i);
if (ProjectFormatConstants.PACKED_REFERENCED_PROJECT_NODE.equals(referencedProjectNode.getNodeName())) {
result.add(referencedProjectNode);
}
}
return result;
}
/**
* Loads the project data from the provided node onto the provided project.
*
* @param mainElement
* the node to load the data from.
* @param project
* the project to set the loaded data on.
* @param projectFileFolderURI
* the URI of the folder to calculate all paths relative to.
*
* @return true if the import was successful, false otherwise.
* */
private boolean loadProjectDataFromNode(final Node mainElement, final IProject project, final URI projectFileFolderURI) {
NodeList mainNodes = mainElement.getChildNodes();
Node referencedProjectsNode = ProjectFileHandler.getNodebyName(mainNodes, ProjectFormatConstants.REFERENCED_PROJECTS_NODE);
if (referencedProjectsNode != null) {
if (!loadReferencedProjectsData(referencedProjectsNode, project)) {
return false;
}
}
Node pathVariablesNode = ProjectFileHandler.getNodebyName(mainNodes, ProjectFormatConstants.PATH_VARIABLES);
if (pathVariablesNode != null) {
if (!loadPathVariables(pathVariablesNode, project.getName())) {
return false;
}
}
Node foldersNode = ProjectFileHandler.getNodebyName(mainNodes, ProjectFormatConstants.FOLDERS_NODE);
if (foldersNode != null) {
if (!loadFoldersData(foldersNode, project, projectFileFolderURI)) {
return false;
}
}
Node filesNode = ProjectFileHandler.getNodebyName(mainNodes, ProjectFormatConstants.FILES_NODE);
if (filesNode != null) {
if (!loadFilesData(filesNode, project, projectFileFolderURI)) {
return false;
}
}
ProjectDocumentHandlingUtility.createDocument(project);
if (!loadConfigurationData(project, mainNodes)) {
return false;
}
return true;
}
/**
* Load the data related to project references.
*
* @param referencedProjectsNode
* the node containing information on referenced projects.
* @param project
* the project to set the data on.
*
* @return true if the import was successful, false otherwise.
* */
private boolean loadReferencedProjectsData(final Node referencedProjectsNode, final IProject project) {
NodeList referencedProjectsList = referencedProjectsNode.getChildNodes();
List<IProject> referencedProjects = new ArrayList<IProject>();
for (int i = 0, size = referencedProjectsList.getLength(); i < size; i++) {
Node referencedProjectNode = referencedProjectsList.item(i);
if (referencedProjectNode.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
NamedNodeMap attributeMap = referencedProjectNode.getAttributes();
if (attributeMap == null) {
continue;
}
Node nameNode = attributeMap.getNamedItem(ProjectFormatConstants.REFERENCED_PROJECT_NAME_ATTRIBUTE);
if (nameNode == null) {
displayError("Import failed", "Error while importing project " + project.getName() + " the name attribute of the " + i
+ " th referenced project is missing");
return false;
}
String projectName = nameNode.getTextContent();
String realProjectName = finalProjectNames.get(projectName);
if (realProjectName != null && realProjectName.length() > 0) {
IProject tempProject = ResourcesPlugin.getWorkspace().getRoot().getProject(realProjectName);
referencedProjects.add(tempProject);
} else {
//already existing projects:
IProject tempProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
referencedProjects.add(tempProject);
}
}
try {
IProjectDescription description = project.getDescription();
description.setReferencedProjects(referencedProjects.toArray(new IProject[referencedProjects.size()]));
project.setDescription(description, null);
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace("While setting project references for `" + project.getName() + "'", e);
return false;
}
return true;
}
/**
* Load the information describing folders.
*
* @param foldersNode
* the node to load from.
* @param project
* the project to set this information on.
* @param projectFileFolderURI
* the location of the project file's folder.
*
* @return true if the import was successful, false otherwise.
* */
private boolean loadFoldersData(final Node foldersNode, final IProject project, final URI projectFileFolderURI) {
final URI projectLocationURI = project.getLocationURI();
NodeList folderNodeList = foldersNode.getChildNodes();
for (int i = 0, size = folderNodeList.getLength(); i < size; i++) {
Node folderItem = folderNodeList.item(i);
if (folderItem.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
NamedNodeMap attributeMap = folderItem.getAttributes();
if (attributeMap == null) {
continue;
}
Node projectRelativePathNode = attributeMap.getNamedItem(ProjectFormatConstants.FOLDER_ECLIPSE_LOCATION_NODE);
if (projectRelativePathNode == null) {
displayError("Import failed", "Error while importing project " + project.getName()
+ " the project relative path attribute of the " + i + " th folder is missing");
return false;
}
String projectRelativePath = projectRelativePathNode.getTextContent();
Node relativeURINode = attributeMap.getNamedItem(ProjectFormatConstants.FOLDER_RELATIVE_LOCATION);
Node rawURINode = attributeMap.getNamedItem(ProjectFormatConstants.FOLDER_RAW_LOCATION);
IFolder folder = project.getFolder(projectRelativePath);
if (!folder.exists()) {
try {
if (relativeURINode != null) {
String relativeLocation = relativeURINode.getTextContent();
URI locationURI;
try {
locationURI = org.eclipse.core.runtime.URIUtil.fromString(relativeLocation);
} catch(URISyntaxException e) {
continue;
}
URI absoluteURI = org.eclipse.core.runtime.URIUtil.makeAbsolute(locationURI, projectFileFolderURI);
if (TitanURIUtil.isPrefix(projectLocationURI, absoluteURI)) {
folder.create(false, true, null);
} else {
File tmpFolder = new File(absoluteURI);
if (tmpFolder.exists()) {
folder.createLink(absoluteURI, IResource.ALLOW_MISSING_LOCAL, null);
} else {
ErrorReporter.logError("Error while importing folders into project `" + project.getName() + "'. Folder `"
+ absoluteURI + "' does not exist");
continue;
}
}
} else if (rawURINode != null) {
String rawLocation = rawURINode.getTextContent();
folder.createLink(URI.create(rawLocation), IResource.ALLOW_MISSING_LOCAL, null);
} else {
TITANDebugConsole
.getConsole()
.newMessageStream()
.println(
"Cannot create the resource " + folder.getFullPath().toString()
+ " the location information is missing or corrupted");
}
} catch (CoreException e) {
//be silent, it can happen normally
}
} else {
ErrorReporter.logWarning("Folder to be imported `" + folder.getName() + "' already exists in project `" + project.getName()
+ "'");
}
}
return true;
}
/**
* Load the information describing files.
*
* @param filesNode
* the node to load from.
* @param project
* the project to set this information on.
* @param projectFileFolderURI
* the location of the project file's folder.
*
* @return true if the import was successful, false otherwise.
* */
private boolean loadFilesData(final Node filesNode, final IProject project, final URI projectFileFolderURI) {
NodeList fileNodeList = filesNode.getChildNodes();
for (int i = 0, size = fileNodeList.getLength(); i < size; i++) {
Node fileItem = fileNodeList.item(i);
if (fileItem.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
NamedNodeMap attributeMap = fileItem.getAttributes();
if (attributeMap == null) {
// there is no attribute, check next node
continue;
}
Node projectRelativePathNode = attributeMap.getNamedItem(ProjectFormatConstants.FILE_ECLIPSE_LOCATION_NODE);
if (projectRelativePathNode == null) {
displayError("Import failed", "Error while importing project " + project.getName() + " some attributes of the " + i
+ " th file are missing");
continue;
}
String projectRelativePath = projectRelativePathNode.getTextContent();
Node relativeURINode = attributeMap.getNamedItem(ProjectFormatConstants.FILE_RELATIVE_LOCATION);
Node rawURINode = attributeMap.getNamedItem(ProjectFormatConstants.FILE_RAW_LOCATION);
IFile targetFile = project.getFile(projectRelativePath);
if (!targetFile.exists()) {
try {
if (relativeURINode != null) {
String relativeLocation = relativeURINode.getTextContent();
//perhaps the next few lines should be implemented as in the function loadFoldersData()
URI absoluteURI = TITANPathUtilities.resolvePathURI(relativeLocation, URIUtil.toPath(projectFileFolderURI).toOSString());
if (absoluteURI == null) {
continue;
}
File file = new File(absoluteURI);
if (file.exists()) {
targetFile.createLink(absoluteURI, IResource.ALLOW_MISSING_LOCAL, null);
} else {
ErrorReporter.logError("Error while importing files into project `" + project.getName() + "'. File `"
+ absoluteURI + "' does not exist");
continue;
}
} else if (rawURINode != null) {
String rawURI = rawURINode.getTextContent();
targetFile.createLink(URI.create(rawURI), IResource.ALLOW_MISSING_LOCAL, null);
} else {
TITANDebugConsole
.getConsole()
.newMessageStream()
.println(
"Can not create the resource " + targetFile.getFullPath().toString()
+ " the location information is missing or corrupted");
continue;
}
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace("While creating link for `" + targetFile + "'", e);
return false;
}
}
}
return true;
}
/**
* Load the information on path variables.
*
* @param rootNode
* the node to load from.
* @param projectName
* the name of the project to be used on the user interface.
*
* @return true if the import was successful, false otherwise.
* */
private boolean loadPathVariables(final Node rootNode, final String projectName) {
final IPathVariableManager pathVariableManager = ResourcesPlugin.getWorkspace().getPathVariableManager();
NodeList variableNodes = rootNode.getChildNodes();
for (int i = 0, size = variableNodes.getLength(); i < size; i++) {
Node variable = variableNodes.item(i);
if (variable.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
NamedNodeMap attributeMap = variable.getAttributes();
if (attributeMap == null) {
continue;
}
Node nameNode = attributeMap.getNamedItem("name");
Node valueNode = attributeMap.getNamedItem("value");
if (nameNode == null || valueNode == null) {
displayError("Import failed", "Error while importing project " + projectName
+ " some attributes of a path variable are missing");
return false;
}
final String variableName = nameNode.getTextContent();
final String variableValue = valueNode.getTextContent();
if (headless || shell == null) {
try {
pathVariableManager.setURIValue(variableName, URIUtil.toURI(variableValue));
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace("While setting path variable `" + variableName + "' in headless mode", e);
}
} else {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
try {
if (pathVariableManager.isDefined(variableName)) {
URI uri = pathVariableManager.getURIValue(variableName);
if (!variableValue.equals(URIUtil.toPath(uri).toString())) {
EditPathVariableDialog dialog = new EditPathVariableDialog(shell, variableName, uri, URIUtil.toURI(
variableValue));
if (Window.OK == dialog.open()) {
URI actualValue = dialog.getActualValue();
pathVariableManager.setURIValue(variableName, actualValue);
}
}
} else {
NewPathVariableDialog dialog = new NewPathVariableDialog(shell, variableName, URIUtil.toURI(variableValue));
if (Window.OK == dialog.open()) {
URI actualValue = dialog.getActualValue();
pathVariableManager.setURIValue(variableName, actualValue);
}
}
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace("While setting path variable `" + variableName + "' in GUI mode", e);
}
}
});
}
}
return true;
}
/**
* Loads the configuration related options onto the project from the
* document being loaded.
*
* @param project
* the project to load onto.
* @param mainNodes
* the mainNodes to check for the configuration related options.
*
* @return true if the import was successful, false otherwise.
* */
private boolean loadConfigurationData(final IProject project, final NodeList mainNodes) {
final Document targetDocument = ProjectDocumentHandlingUtility.getDocument(project);
Node activeConfigurationNode = ProjectFileHandler.getNodebyName(mainNodes, ProjectFormatConstants.ACTIVE_CONFIGURATION_NODE);
String activeConfiguration = ProjectFormatConstants.DEFAULT_CONFIGURATION_NAME;
if (activeConfigurationNode != null) {
activeConfiguration = activeConfigurationNode.getTextContent();
} else {
activeConfiguration = "Default";
}
try {
project.setPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER,
ProjectBuildPropertyData.ACTIVECONFIGURATION), activeConfiguration);
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace(
"While setting `" + activeConfiguration + "' as configuration for project `" + project.getName() + "'", e);
}
// Remove possible target configuration nodes in existence
removeConfigurationNodes(targetDocument.getDocumentElement());
Node targetActiveConfiguration = targetDocument.createElement(ProjectFormatConstants.ACTIVE_CONFIGURATION_NODE);
targetActiveConfiguration.appendChild(targetDocument.createTextNode(activeConfiguration));
targetDocument.getDocumentElement().appendChild(targetActiveConfiguration);
Node targetConfigurationsRoot = targetDocument.createElement(ProjectFormatConstants.CONFIGURATIONS_NODE);
targetDocument.getDocumentElement().appendChild(targetConfigurationsRoot);
Node configurationsNode = ProjectFileHandler.getNodebyName(mainNodes, ProjectFormatConstants.CONFIGURATIONS_NODE);
if (configurationsNode == null) {
ProjectDocumentHandlingUtility.saveDocument(project);
ProjectBuildPropertyData.setProjectAlreadyExported(project, false);
ProjectFileHandler handler = new ProjectFileHandler(project);
handler.loadProjectSettingsFromDocument(targetDocument);
return true;
}
NodeList configurationsNodeList = configurationsNode.getChildNodes();
for (int i = 0, size = configurationsNodeList.getLength(); i < size; i++) {
Node configurationNode = configurationsNodeList.item(i);
if (configurationNode.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
NamedNodeMap attributeMap = configurationNode.getAttributes();
if (attributeMap == null) {
continue;
}
Node nameNode = attributeMap.getNamedItem(ProjectFormatConstants.CONFIGURATION_NAME_ATTRIBUTE);
if (nameNode == null) {
displayError("Import failed", "Error while importing project " + project.getName()
+ " the name attribute of a referenced project is missing");
return false;
}
String configurationName = nameNode.getTextContent();
if (ProjectFormatConstants.DEFAULT_CONFIGURATION_NAME.equals(configurationName)) {
copyConfigurationData(targetDocument.getDocumentElement(), configurationNode);
} else {
Element targetConfiguration = targetDocument.createElement(ProjectFormatConstants.CONFIGURATION_NODE);
targetConfiguration.setAttribute(ProjectFormatConstants.CONFIGURATION_NAME_ATTRIBUTE, configurationName);
targetConfigurationsRoot.appendChild(targetConfiguration);
copyConfigurationData(targetConfiguration, configurationNode);
}
}
ProjectDocumentHandlingUtility.saveDocument(project);
ProjectBuildPropertyData.setProjectAlreadyExported(project, false);
ProjectFileHandler handler = new ProjectFileHandler(project);
handler.loadProjectSettingsFromDocument(targetDocument);
return true;
}
/**
* Remove those child nodes of the provided node, which are related to
* handling configuration data.
*
* @param rootNode
* the node to use.
* */
private void removeConfigurationNodes(final Node rootNode) {
NodeList rootNodeList = rootNode.getChildNodes();
Node tempNode = ProjectFileHandler.getNodebyName(rootNodeList, ProjectFormatConstants.CONFIGURATIONS_NODE);
if (tempNode != null) {
rootNode.removeChild(tempNode);
}
tempNode = ProjectFileHandler.getNodebyName(rootNodeList, ProjectFileHandler.PROJECTPROPERTIESXMLNODE);
if (tempNode != null) {
rootNode.removeChild(tempNode);
}
tempNode = ProjectFileHandler.getNodebyName(rootNodeList, ProjectFileHandler.FOLDERPROPERTIESXMLNODE);
if (tempNode != null) {
rootNode.removeChild(tempNode);
}
tempNode = ProjectFileHandler.getNodebyName(rootNodeList, ProjectFileHandler.FILEPROPERTIESXMLNODE);
if (tempNode != null) {
rootNode.removeChild(tempNode);
}
tempNode = ProjectFileHandler.getNodebyName(rootNodeList, ProjectFormatConstants.ACTIVE_CONFIGURATION_NODE);
if (tempNode != null) {
rootNode.removeChild(tempNode);
}
}
/**
* Copies the configuration related data from the source node, to the target
* node.
*
* @param targetRoot
* the node where the configuration data should be moved to.
* @param sourceRoot
* the node from where the configuration data is moved.
* */
private void copyConfigurationData(final Element targetRoot, final Node sourceRoot) {
final Document document = targetRoot.getOwnerDocument();
final NodeList rootList = sourceRoot.getChildNodes();
Node targetNode = null;
for (int i = 0, size = rootList.getLength(); i < size; i++) {
Node tempNode = rootList.item(i);
String nodeName = tempNode.getNodeName();
if (ProjectFileHandler.PROJECTPROPERTIESXMLNODE.equals(nodeName) || ProjectFileHandler.FOLDERPROPERTIESXMLNODE.equals(nodeName)
|| ProjectFileHandler.FILEPROPERTIESXMLNODE.equals(nodeName)) {
targetNode = document.importNode(tempNode, true);
ProjectFileHandler.clearNode(targetNode);
targetRoot.appendChild(targetNode);
}
}
}
class ProjectSelector implements Runnable {
private String projectName;
private IProject project = null;
private boolean cancelled = false;
public ProjectSelector(final String projectName) {
this.projectName = projectName;
}
public String getProjectName() {
return projectName;
}
public IProject getProject() {
return project;
}
public boolean isCancelled() {
return cancelled;
}
@Override
public void run() {
NewProjectNameDialog dialog = new NewProjectNameDialog(shell, projectName);
if (dialog.open() == Window.OK) {
projectName = dialog.getName();
project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
if (project.exists()) {
cancelled = true;
}
} else {
cancelled = true;
}
}
}
/**
* Create a new project based on the information found in the provided
* document.
* */
private IProject createProject(final Node mainElement, final boolean treatExistingProjectAsError) {
NodeList mainNodes = mainElement.getChildNodes();
Node projectNameNode = ProjectFileHandler.getNodebyName(mainNodes, ProjectFormatConstants.PROJECTNAME_NODE);
if (null == projectNameNode) {
TITANDebugConsole.getConsole().newMessageStream()
.println("The name of the project could not be found in the project descriptor, it will not be created.");
return null;
}
String originalProjectName = projectNameNode.getFirstChild().getTextContent();
String projectName = originalProjectName;
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
if (project.exists()) {
if (!treatExistingProjectAsError || headless) {
if(!project.isOpen()) {
try {
project.open(null);
} catch(CoreException e) {
ErrorReporter.logError("An existing project with the name " + projectName + " cannot be opened!");
}
}
ErrorReporter.logWarning("A project with the name " + projectName + " already exists, skipping it!");
//It will be skipped =>
return null;
}
//Error dialog:
//gets a new project name instead of the existing one:
ProjectSelector temp = new ProjectSelector(projectName);
Display.getDefault().syncExec(temp);
if (temp.cancelled) {
return null;
}
projectName = temp.getProjectName();
project = temp.getProject();
}
finalProjectNames.put(originalProjectName, projectName);
project = createNewProject(project, projectName);
if (project == null) {
TITANDebugConsole.getConsole().newMessageStream().println("There was an error while creating the project " + projectName);
return null;
}
try {
TITANNature.addTITANBuilderToProject(project);
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace("While adding builder to `" + project.getName() + "'", e);
}
return project;
}
/**
* Load the project information document from the provided file and
* recursively for all project files mentioned in the referenced projects
* section.
*
* @param file
* the file to load the data from.
* @param validator
* the xml validator. can be <code>null</code>
*
* @return true if there were no errors, false otherwise.
* */
private boolean loadURIDocuments(final URI file, final Validator validator) {
if (projectsToImport.containsKey(file)) {
return true;
}
if (!"file".equals(file.getScheme()) && !"".equals(file.getScheme())) {
ErrorReporter.logError("Loading of project information is only supported for local files right now. " + file.toString()
+ " could not be loaded");
return false;
}
Document document = getDocumentFromFile(file.getPath());
if (document == null) {
final StringBuilder builder = new StringBuilder("It was not possible to load the imported project file: '" + file.toString()
+ "'\n");
for (int i = importChain.size() - 1; i >= 0; --i) {
builder.append("imported by: '");
builder.append(importChain.get(i).toString());
builder.append("'\n");
}
ErrorReporter.logError(builder.toString());
return false;
}
if (validator != null) {
try {
validator.validate(new StreamSource(new File(file)));
} catch (final Exception e) {
ErrorReporter.logExceptionStackTrace(
"Error while importing from file " + file + ": " + System.getProperty("line.separator"), e);
return false;
}
}
ProjectFileHandler.clearNode(document);
projectsToImport.put(file, document);
Element mainElement = document.getDocumentElement();
NodeList mainNodes = mainElement.getChildNodes();
Node referencedProjectsNode = ProjectFileHandler.getNodebyName(mainNodes, ProjectFormatConstants.REFERENCED_PROJECTS_NODE);
if (referencedProjectsNode == null) {
return true;
}
final IPath projectFileFolderPath = new Path(file.getPath()).removeLastSegments(1);
NodeList referencedProjectsList = referencedProjectsNode.getChildNodes();
boolean result = true;
for (int i = 0, size = referencedProjectsList.getLength(); i < size; i++) {
Node referencedProjectNode = referencedProjectsList.item(i);
if (referencedProjectNode.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
NamedNodeMap attributeMap = referencedProjectNode.getAttributes();
if (attributeMap == null) {
continue;
}
Node nameNode = attributeMap.getNamedItem(ProjectFormatConstants.REFERENCED_PROJECT_NAME_ATTRIBUTE);
if (nameNode == null) {
displayError("Import failed", "Error while importing from file " + file
+ " the name attribute of a referenced project is missing");
return false;
}
final String projectName = nameNode.getTextContent();
Node locationNode = attributeMap.getNamedItem(ProjectFormatConstants.REFERENCED_PROJECT_LOCATION_ATTRIBUTE);
if (locationNode == null) {
displayError("Import failed", "Error while importing from file " + file
+ " the location attribute of the referenced project " + projectName + " is not given.");
return false;
}
String unresolvedProjectLocationURI = locationNode.getTextContent();
URI absoluteURI = TITANPathUtilities.resolvePath(unresolvedProjectLocationURI, URIUtil.toURI(projectFileFolderPath));
String fileName;
// Determine tpdname
Node tpdNameNode = attributeMap.getNamedItem(ProjectFormatConstants.REFERENCED_PROJECT_TPD_NAME_ATTRIBUTE);
if(tpdNameNode != null) {
fileName = tpdNameNode.getTextContent();
}else {
fileName = projectName + ".tpd";
}
tpdNameAttrMap.put(projectName, fileName);
if (searchPaths != null && !searchPaths.isEmpty()) {
File f = new File(absoluteURI);
IPath unresolvedProjectLocationURIPath = new Path(unresolvedProjectLocationURI);
if(!unresolvedProjectLocationURIPath.isAbsolute() && (!f.exists() || f.isDirectory())) {;
// Try search paths
for (String path : searchPaths) {
String filePath = path;
if(path.charAt(path.length() - 1) != '/') {
filePath += "/";
}
filePath += fileName;
String systemPath = new Path(filePath).toOSString();
f = new File(systemPath);
// tpd found
if (f.exists() && !f.isDirectory()) {
absoluteURI = URIUtil.toURI(systemPath);
tpdURIMap.put(projectName, unresolvedProjectLocationURI);
break;
}
}
}
}
if (absoluteURI!=null && !"file".equals(absoluteURI.getScheme())) {
final StringBuilder builder = new StringBuilder(
"Loading of project information is only supported for local files right now. " + absoluteURI.toString()
+ " could not be loaded\n");
for (int j = importChain.size() - 1; j >= 0; --j) {
builder.append("imported by: '");
builder.append(importChain.get(j).toString());
builder.append("'\n");
}
ErrorReporter.logError(builder.toString());
continue;
}
importChain.add(file);
// if( !projectsWithUnresolvedName.containsKey(absoluteURI) ) {
// projectsWithUnresolvedName.put(absoluteURI, unresolvedProjectLocationURI);
result &= loadURIDocuments(absoluteURI, validator);
importChain.remove(importChain.size() - 1);
}
return result;
}
private void displayError(final String title, final String message) {
if (!headless) {
ErrorReporter.parallelErrorDisplayInMessageDialog(title, message);
}
ErrorReporter.logError(message);
}
/**
* Extracts an XML document from the provided file.
*
* @param file
* the file to read from.
* @return the extracted XML document, or null if there were some error.
* */
public Document getDocumentFromFile(final String file) {
final LSInput lsInput = domImplLS.createLSInput();
Document document = null;
try {
FileInputStream istream = new FileInputStream(file);
lsInput.setByteStream(istream);
document = parser.parse(lsInput);
istream.close();
} catch (Exception e) {
ErrorReporter.logExceptionStackTrace("While getting the document from `" + file + "'", e);
}
return document;
}
/**
* Creating a new project.
*
* @return the new project created.
*/
IProject createNewProject(final IProject newProjectHandle, final String name) {
IProject newProject;
final IWorkspace workspace = ResourcesPlugin.getWorkspace();
final IProjectDescription description = workspace.newProjectDescription(name);
TITANNature.addTITANNatureToProject(description);
if (headless) {
try {
createProject(description, newProjectHandle, new NullProgressMonitor());
} catch (CoreException e) {
ErrorReporter.logExceptionStackTrace("While creating project `" + newProjectHandle.getName() + "'", e);
}
} else {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
try {
final WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
@Override
protected void execute(final IProgressMonitor monitor) throws CoreException {
createProject(description, newProjectHandle, monitor);
}
};
new ProgressMonitorDialog(null).run(true, true, op);
} catch (InterruptedException e) {
return;
} catch (final InvocationTargetException e) {
displayError(CREATION_FAILED, e.getMessage());
ErrorReporter.logExceptionStackTrace("While creating project `" + newProjectHandle.getName() + "'", e);
return;
}
}
});
}
newProject = newProjectHandle;
return newProject;
}
/**
* Creating a new project.
*
* @param description
* - IProjectDescription that belongs to the newly created
* project.
* @param projectHandle
* - a project handle that is used to create the new project.
* @param monitor
* - reference to the monitor object
* @exception CoreException
* thrown if access to the resources throws a CoreException.
* @exception OperationCanceledException
* if the operation was canceled by the user.
*/
protected void createProject(final IProjectDescription description, final IProject projectHandle, final IProgressMonitor monitor)
throws CoreException {
final SubMonitor progress = SubMonitor.convert(monitor, 3);
try {
progress.setTaskName(CREATING_PROJECT);
projectHandle.create(description, progress.newChild(1));
if (progress.isCanceled()) {
throw new OperationCanceledException();
}
projectHandle.open(IResource.BACKGROUND_REFRESH, progress.newChild(1));
projectHandle.refreshLocal(IResource.DEPTH_ONE, progress.newChild(1));
} finally {
progress.done();
}
}
}
|
package com.mebigfatguy.fbcontrib.detect;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.Type;
import com.mebigfatguy.fbcontrib.utils.BugType;
import com.mebigfatguy.fbcontrib.utils.SignatureUtils;
import com.mebigfatguy.fbcontrib.utils.TernaryPatcher;
import com.mebigfatguy.fbcontrib.utils.Values;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.OpcodeStack.CustomUserValue;
import edu.umd.cs.findbugs.OpcodeStack.Item;
import edu.umd.cs.findbugs.ba.ClassContext;
/**
* looks for uses of log4j or slf4j where the class specified when creating the
* logger is not the same as the class in which this logger is used. Also looks
* for using concatenation with slf4j logging rather than using the
* parameterized interface.
*/
@CustomUserValue
public class LoggerOddities extends BytecodeScanningDetector {
private static JavaClass THROWABLE_CLASS;
private static Set<String> LOGGER_METHODS;
private static final Pattern BAD_FORMATTING_ANCHOR = Pattern.compile("\\{[0-9]\\}");
private static final Pattern FORMATTER_ANCHOR = Pattern.compile("\\{\\}");
static {
try {
THROWABLE_CLASS = Repository.lookupClass("java/lang/Throwable");
LOGGER_METHODS = new HashSet<String>();
LOGGER_METHODS.add("trace");
LOGGER_METHODS.add("debug");
LOGGER_METHODS.add("info");
LOGGER_METHODS.add("warn");
LOGGER_METHODS.add("error");
LOGGER_METHODS.add("fatal");
} catch (ClassNotFoundException cnfe) {
THROWABLE_CLASS = null;
}
}
private final BugReporter bugReporter;
private OpcodeStack stack;
private String nameOfThisClass;
/**
* constructs a LO detector given the reporter to report bugs on.
*
* @param bugReporter
* the sync of bug reports
*/
public LoggerOddities(final BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
/**
* implements the visitor to discover what the class name is if it is a
* normal class, or the owning class, if the class is an anonymous class.
*
* @param classContext
* the context object of the currently parsed class
*/
@Override
public void visitClassContext(ClassContext classContext) {
try {
stack = new OpcodeStack();
nameOfThisClass = classContext.getJavaClass().getClassName();
int subclassIndex = nameOfThisClass.indexOf('$');
while (subclassIndex >= 0) {
String simpleName = nameOfThisClass.substring(subclassIndex + 1);
try {
Integer.parseInt(simpleName);
nameOfThisClass = nameOfThisClass.substring(0, subclassIndex);
subclassIndex = nameOfThisClass.indexOf('$');
} catch (NumberFormatException nfe) {
subclassIndex = -1;
}
}
nameOfThisClass = nameOfThisClass.replace('.', '/');
super.visitClassContext(classContext);
} finally {
stack = null;
}
}
/**
* implements the visitor to reset the stack
*
* @param obj
* the context object of the currently parsed code block
*/
@Override
public void visitCode(Code obj) {
stack.resetForMethodEntry(this);
Method m = getMethod();
if (Values.CONSTRUCTOR.equals(m.getName())) {
Type[] types = Type.getArgumentTypes(m.getSignature());
for (Type t : types) {
String parmSig = t.getSignature();
if ("Lorg/slf4j/Logger;".equals(parmSig) || "Lorg/apache/log4j/Logger;".equals(parmSig) || "Lorg/apache/commons/logging/Log;".equals(parmSig)) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_SUSPECT_LOG_PARAMETER.name(), NORMAL_PRIORITY).addClass(this).addMethod(this));
}
}
}
super.visitCode(obj);
}
/**
* implements the visitor to look for calls to Logger.getLogger with the
* wrong class name
*
* @param seen
* the opcode of the currently parsed instruction
*/
@Override
public void sawOpcode(int seen) {
String ldcClassName = null;
String seenMethodName = null;
int exMessageReg = -1;
Integer arraySize = null;
try {
stack.precomputation(this);
if ((seen == LDC) || (seen == LDC_W)) {
Constant c = getConstantRefOperand();
if (c instanceof ConstantClass) {
ConstantPool pool = getConstantPool();
ldcClassName = ((ConstantUtf8) pool.getConstant(((ConstantClass) c).getNameIndex())).getBytes();
}
} else if (seen == INVOKESTATIC) {
lookForSuspectClasses();
} else if (((seen == INVOKEVIRTUAL) || (seen == INVOKEINTERFACE)) && (THROWABLE_CLASS != null)) {
String mthName = getNameConstantOperand();
if ("getName".equals(mthName)) {
if (stack.getStackDepth() >= 1) {
// Foo.class.getName() is being called, so we pass the
// name of the class to the current top of the stack
// (the name of the class is currently on the top of the
// stack, but won't be on the stack at all next opcode)
Item stackItem = stack.getStackItem(0);
ldcClassName = (String) stackItem.getUserValue();
}
} else if ("getMessage".equals(mthName)) {
String callingClsName = getClassConstantOperand();
JavaClass cls = Repository.lookupClass(callingClsName);
if (cls.instanceOf(THROWABLE_CLASS)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item exItem = stack.getStackItem(0);
exMessageReg = exItem.getRegisterNumber();
}
}
} else if (LOGGER_METHODS.contains(mthName)) {
checkForProblemsWithLoggerMethods();
} else if ("toString".equals(mthName)) {
String callingClsName = getClassConstantOperand();
if (("java/lang/StringBuilder".equals(callingClsName) || "java/lang/StringBuffer".equals(callingClsName))) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
// if the stringbuilder was previously stored, don't
// report it
if (item.getRegisterNumber() < 0) {
seenMethodName = mthName;
}
}
}
}
} else if (seen == INVOKESPECIAL) {
checkForLoggerParam();
} else if (seen == ANEWARRAY) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item sizeItem = stack.getStackItem(0);
Object con = sizeItem.getConstant();
if (con instanceof Integer) {
arraySize = (Integer) con;
}
}
} else if (seen == AASTORE) {
if (stack.getStackDepth() >= 3) {
OpcodeStack.Item arrayItem = stack.getStackItem(2);
Integer size = (Integer) arrayItem.getUserValue();
if ((size != null) && (size > 0)) {
if (hasExceptionOnStack()) {
arrayItem.setUserValue(-size);
}
}
}
}
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
} finally {
TernaryPatcher.pre(stack, seen);
stack.sawOpcode(this, seen);
TernaryPatcher.post(stack, seen);
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
if (ldcClassName != null) {
item.setUserValue(ldcClassName);
} else if (seenMethodName != null) {
item.setUserValue(seenMethodName);
} else if (exMessageReg >= 0) {
item.setUserValue(Integer.valueOf(exMessageReg));
} else if (arraySize != null) {
item.setUserValue(arraySize);
}
}
}
}
private void checkForProblemsWithLoggerMethods() throws ClassNotFoundException {
String callingClsName = getClassConstantOperand();
if (callingClsName.endsWith("Log") || (callingClsName.endsWith("Logger"))) {
String sig = getSigConstantOperand();
if ("(Ljava/lang/String;Ljava/lang/Throwable;)V".equals(sig) || "(Ljava/lang/Object;Ljava/lang/Throwable;)V".equals(sig)) {
if (stack.getStackDepth() >= 2) {
OpcodeStack.Item exItem = stack.getStackItem(0);
OpcodeStack.Item msgItem = stack.getStackItem(1);
Object exReg = msgItem.getUserValue();
if (exReg instanceof Integer) {
if (((Integer) exReg).intValue() == exItem.getRegisterNumber()) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_STUTTERED_MESSAGE.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addSourceLine(this));
}
}
}
} else if ("(Ljava/lang/Object;)V".equals(sig)) {
if (stack.getStackDepth() > 0) {
final JavaClass clazz = stack.getStackItem(0).getJavaClass();
if ((clazz != null) && clazz.instanceOf(THROWABLE_CLASS)) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_LOGGER_LOST_EXCEPTION_STACK_TRACE.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this));
}
}
} else if ("org/slf4j/Logger".equals(callingClsName)) {
String signature = getSigConstantOperand();
if ("(Ljava/lang/String;)V".equals(signature) || "(Ljava/lang/String;Ljava/lang/Object;)V".equals(signature)
|| "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V".equals(signature)
|| "(Ljava/lang/String;[Ljava/lang/Object;)V".equals(signature)) {
int numParms = Type.getArgumentTypes(signature).length;
if (stack.getStackDepth() >= numParms) {
OpcodeStack.Item formatItem = stack.getStackItem(numParms - 1);
Object con = formatItem.getConstant();
if (con instanceof String) {
Matcher m = BAD_FORMATTING_ANCHOR.matcher((String) con);
if (m.find()) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_INVALID_FORMATTING_ANCHOR.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this));
} else {
int actualParms = getSLF4JParmCount(signature);
if (actualParms != -1) {
int expectedParms = countAnchors((String) con);
boolean hasEx = hasExceptionOnStack();
if ((!hasEx && (expectedParms != actualParms))
|| (hasEx && ((expectedParms != (actualParms - 1)) && (expectedParms != actualParms)))) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_INCORRECT_NUMBER_OF_ANCHOR_PARAMETERS.name(), NORMAL_PRIORITY)
.addClass(this).addMethod(this).addSourceLine(this).addString("Expected: " + expectedParms)
.addString("Actual: " + actualParms));
}
}
}
} else if ("toString".equals(formatItem.getUserValue())) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_APPENDED_STRING_IN_FORMAT_STRING.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this));
}
}
}
}
}
}
private void checkForLoggerParam() {
if (Values.CONSTRUCTOR.equals(getNameConstantOperand())) {
String cls = getClassConstantOperand();
if ((cls.startsWith("java/") || cls.startsWith("javax/")) && cls.endsWith("Exception")) {
String sig = getSigConstantOperand();
Type[] types = Type.getArgumentTypes(sig);
if (types.length <= stack.getStackDepth()) {
for (int i = 0; i < types.length; i++) {
if ("Ljava/lang/String;".equals(types[i].getSignature())) {
OpcodeStack.Item item = stack.getStackItem(types.length - i - 1);
String cons = (String) item.getConstant();
if ((cons != null) && cons.contains("{}")) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_EXCEPTION_WITH_LOGGER_PARMS.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this));
break;
}
}
}
}
}
}
}
private void lookForSuspectClasses() {
String callingClsName = getClassConstantOperand();
String mthName = getNameConstantOperand();
String loggingClassName = null;
int loggingPriority = NORMAL_PRIORITY;
if ("org/slf4j/LoggerFactory".equals(callingClsName) && "getLogger".equals(mthName)) {
String signature = getSigConstantOperand();
if ("(Ljava/lang/Class;)Lorg/slf4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getUserValue();
}
} else if ("(Ljava/lang/String;)Lorg/slf4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getConstant();
if (loggingClassName != null) {
loggingClassName = loggingClassName.replace('.', '/');
}
loggingPriority = LOW_PRIORITY;
}
}
} else if ("org/apache/log4j/Logger".equals(callingClsName) && "getLogger".equals(mthName)) {
String signature = getSigConstantOperand();
if ("(Ljava/lang/Class;)Lorg/apache/log4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getUserValue();
}
} else if ("(Ljava/lang/String;)Lorg/apache/log4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getConstant();
Object userValue = item.getUserValue();
if (loggingClassName != null) {
// first look at the constant passed in
loggingClassName = loggingClassName.replace('.', '/');
loggingPriority = LOW_PRIORITY;
} else if (userValue instanceof String) {
// try the user value, which may have been set by a call
// to Foo.class.getName()
loggingClassName = (String) userValue;
loggingClassName = loggingClassName.replace('.', '/');
}
}
} else if ("(Ljava/lang/String;Lorg/apache/log4j/spi/LoggerFactory;)Lorg/apache/log4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 1) {
OpcodeStack.Item item = stack.getStackItem(1);
loggingClassName = (String) item.getConstant();
if (loggingClassName != null) {
loggingClassName = loggingClassName.replace('.', '/');
}
loggingPriority = LOW_PRIORITY;
}
}
} else if ("org/apache/commons/logging/LogFactory".equals(callingClsName) && "getLog".equals(mthName)) {
String signature = getSigConstantOperand();
if ("(Ljava/lang/Class;)Lorg/apache/commons/logging/Log;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getUserValue();
}
} else if ("(Ljava/lang/String;)Lorg/apache/commons/logging/Log;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getConstant();
if (loggingClassName != null) {
loggingClassName = loggingClassName.replace('.', '/');
}
loggingPriority = LOW_PRIORITY;
}
}
}
if (loggingClassName != null) {
if (stack.getStackDepth() > 0) {
if (!loggingClassName.equals(nameOfThisClass)) {
boolean isPrefix = nameOfThisClass.startsWith(loggingClassName);
boolean isAnonClassPrefix;
if (isPrefix) {
String anonClass = nameOfThisClass.substring(loggingClassName.length());
isAnonClassPrefix = anonClass.matches("(\\$\\d+)+");
} else {
isAnonClassPrefix = false;
}
if (!isAnonClassPrefix) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_SUSPECT_LOG_CLASS.name(), loggingPriority).addClass(this).addMethod(this)
.addSourceLine(this).addString(loggingClassName).addString(nameOfThisClass));
}
}
}
}
}
/**
* returns the number of anchors {} in a string
*
* @param formatString
* the format string
* @return the number of anchors
*/
private static int countAnchors(String formatString) {
Matcher m = FORMATTER_ANCHOR.matcher(formatString);
int count = 0;
int start = 0;
while (m.find(start)) {
++count;
start = m.end();
}
return count;
}
/**
* returns the number of parameters slf4j is expecting to inject into the
* format string
*
* @param signature
* the method signature of the error, warn, info, debug statement
* @return the number of expected parameters
*/
private int getSLF4JParmCount(String signature) {
if ("(Ljava/lang/String;Ljava/lang/Object;)V".equals(signature))
return 1;
if ("(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V".equals(signature))
return 2;
OpcodeStack.Item item = stack.getStackItem(0);
Integer size = (Integer) item.getUserValue();
if (size != null) {
return Math.abs(size.intValue());
}
return -1;
}
/**
* returns whether an exception object is on the stack slf4j will find this,
* and not include it in the parm list so i we find one, just don't report
*
* @return whether or not an exception i present
*/
private boolean hasExceptionOnStack() {
try {
for (int i = 0; i < stack.getStackDepth() - 1; i++) {
OpcodeStack.Item item = stack.getStackItem(i);
String sig = item.getSignature();
if (sig.startsWith("L")) {
String name = SignatureUtils.stripSignature(sig);
JavaClass cls = Repository.lookupClass(name);
if (cls.instanceOf(THROWABLE_CLASS))
return true;
} else if (sig.startsWith("[")) {
Integer sz = (Integer) item.getUserValue();
if ((sz != null) && (sz.intValue() < 0))
return true;
}
}
return false;
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
return true;
}
}
}
|
package org.sagebionetworks.bridge.dynamodb;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.sagebionetworks.bridge.BridgeUtils;
import org.sagebionetworks.bridge.config.BridgeConfig;
import org.sagebionetworks.bridge.dao.NotificationTopicDao;
import org.sagebionetworks.bridge.exceptions.EntityNotFoundException;
import org.sagebionetworks.bridge.models.notifications.NotificationTopic;
import org.sagebionetworks.bridge.models.studies.StudyIdentifier;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression;
import com.amazonaws.services.dynamodbv2.datamodeling.QueryResultPage;
import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.services.sns.model.CreateTopicRequest;
import com.amazonaws.services.sns.model.CreateTopicResult;
import com.amazonaws.services.sns.model.DeleteTopicRequest;
import com.google.common.collect.ImmutableList;
@Component
public class DynamoNotificationTopicDao implements NotificationTopicDao {
private static Logger LOG = LoggerFactory.getLogger(DynamoNotificationTopicDao.class);
private DynamoDBMapper mapper;
private AmazonSNSClient snsClient;
private BridgeConfig config;
@Resource(name = "notificationTopicMapper")
final void setNotificationTopicMapper(DynamoDBMapper mapper) {
this.mapper = mapper;
}
@Resource(name = "snsClient")
final void setSnsClient(AmazonSNSClient snsClient) {
this.snsClient = snsClient;
}
@Resource(name = "bridgeConfig")
public void setBridgeConfig(BridgeConfig bridgeConfig) {
this.config = bridgeConfig;
}
@Override
public List<NotificationTopic> listTopics(StudyIdentifier studyId) {
checkNotNull(studyId);
DynamoNotificationTopic hashKey = new DynamoNotificationTopic();
hashKey.setStudyId(studyId.getIdentifier());
DynamoDBQueryExpression<DynamoNotificationTopic> query = new DynamoDBQueryExpression<DynamoNotificationTopic>()
.withConsistentRead(false).withHashKeyValues(hashKey);
QueryResultPage<DynamoNotificationTopic> resultPage = mapper.queryPage(DynamoNotificationTopic.class, query);
return ImmutableList.copyOf(resultPage.getResults());
}
@Override
public NotificationTopic getTopic(StudyIdentifier studyId, String guid) {
checkNotNull(studyId);
checkNotNull(guid);
DynamoNotificationTopic hashKey = new DynamoNotificationTopic();
hashKey.setStudyId(studyId.getIdentifier());
hashKey.setGuid(guid);
DynamoNotificationTopic topic = mapper.load(hashKey);
if (topic == null) {
throw new EntityNotFoundException(NotificationTopic.class);
}
return topic;
}
@Override
public NotificationTopic createTopic(NotificationTopic topic) {
checkNotNull(topic);
// Create SNS topic first. If SNS fails, an exception is thrown. If DDB call fails, the SNS topic is orphaned
// but that will not break the data integrity of Bridge data.
topic.setGuid(BridgeUtils.generateGuid());
String snsTopicName = createSnsTopicName(topic);
CreateTopicRequest request = new CreateTopicRequest().withName(snsTopicName);
CreateTopicResult result = snsClient.createTopic(request);
topic.setTopicARN(result.getTopicArn());
mapper.save(topic);
return topic;
}
@Override
public NotificationTopic updateTopic(StudyIdentifier studyId, NotificationTopic topic) {
checkNotNull(topic);
checkNotNull(topic.getGuid());
NotificationTopic existing = getTopic(studyId, topic.getGuid());
existing.setName(topic.getName());
mapper.save(existing);
return existing;
}
@Override
public void deleteTopic(StudyIdentifier studyId, String guid) {
checkNotNull(studyId);
checkNotNull(guid);
NotificationTopic existing = getTopic(studyId, guid);
// Delete the DDB record first. If it fails an exception is thrown. If SNS fails, the SNS topic
// is not deleted, but the DDB record has successfully deleted, so suppress the exception (just
// log it) because the topic has been deleted from Bridge without a referential integrity problem.
DynamoNotificationTopic hashKey = new DynamoNotificationTopic();
hashKey.setStudyId(studyId.getIdentifier());
hashKey.setGuid(guid);
mapper.delete(hashKey);
try {
DeleteTopicRequest request = new DeleteTopicRequest().withTopicArn(existing.getTopicARN());
snsClient.deleteTopic(request);
} catch(AmazonServiceException e) {
LOG.warn("Bridge topic '" + existing.getName() + "' in study '" + existing.getStudyId()
+ "' deleted, but SNS topic deletion threw exception", e);
}
}
/**
* So we can find these in the AWS console, we give these a specifically formatted name.
*/
private String createSnsTopicName(NotificationTopic topic) {
return topic.getStudyId() + "-" + config.getEnvironment().name().toLowerCase() + "-" + topic.getGuid();
}
}
|
package org.opentosca.planbuilder.helpers;
import java.util.HashMap;
import java.util.Map;
import org.opentosca.planbuilder.handlers.BuildPlanHandler;
import org.opentosca.planbuilder.model.plan.BuildPlan;
import org.opentosca.planbuilder.model.plan.TemplateBuildPlan;
import org.opentosca.planbuilder.model.tosca.AbstractNodeTemplate;
import org.opentosca.planbuilder.model.tosca.AbstractRelationshipTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class PropertyVariableInitializer {
private final static Logger LOG = LoggerFactory.getLogger(PropertyVariableInitializer.class);
private BuildPlanHandler planHandler;
public class PropertyMap {
// the internal map TemplateId -> PropertyLocalName,VariableName
private Map<String, Map<String, String>> internalMap;
/**
* Constructor
*/
public PropertyMap() {
this.internalMap = new HashMap<String, Map<String, String>>();
}
/**
* Adds a mapping from TemplateId to Property LocalName and VariableName
*
* @param templateId the Id of the Template
* @param propertyName a localName of Template Property
* @param propertyVariableName a variable name
* @return true if adding was successful, else false
*/
public boolean addPropertyMapping(String templateId, String propertyName, String propertyVariableName) {
if (this.internalMap.containsKey(templateId)) {
// template has already properties set
Map<String, String> propertyMappingMap = this.internalMap.get(templateId);
if (propertyMappingMap.containsKey(propertyName)) {
// this is an error, because we don't map properties to two
// variables
return false;
} else {
// add property and propertyVariableName
propertyMappingMap.put(propertyName, propertyVariableName);
// FIXME ? don't know yet if the retrieved map is backed in
// the internalMap
this.internalMap.put(templateId, propertyMappingMap);
return true;
}
} else {
// template has no properties assigned
Map<String, String> propertyMappingMap = new HashMap<String, String>();
propertyMappingMap.put(propertyName, propertyVariableName);
this.internalMap.put(templateId, propertyMappingMap);
return true;
}
}
/**
* Returns all mappings from Property localName to variable name for a
* given TemplateId
*
* @param templateid the Id of a Template
* @return a Map from String to String representing Property localName
* as key and variable name as value
*/
public Map<String, String> getPropertyMappingMap(String templateid) {
return this.internalMap.get(templateid);
}
}
/**
* Constructor
*
* @param planHandler a BuildPlanHandler for the class
* @param templateHandler a TemplateBuildPlanHandler for the class
*/
public PropertyVariableInitializer(BuildPlanHandler planHandler) {
this.planHandler = planHandler;
}
/**
* Initializes the BuildPlan with variables for Template Properties and
* returns the Mappings for the Properties and variables
*
* @param buildPlan the BuildPlan to initialize
* @return a PropertyMap which holds mappings from Template to Template
* Property and BuildPlan variable
*/
public PropertyMap initializePropertiesAsVariables(BuildPlan buildPlan) {
PropertyMap map = new PropertyMap();
for (TemplateBuildPlan templatePlan : buildPlan.getTemplateBuildPlans()) {
this.initializePropertiesAsVariables(map, templatePlan);
}
return map;
}
/**
* Initializes Properties inside the given PropertyMap of the given
* TemplateBuildPlan
*
* @param map a PropertyMap to save the mappings to
* @param templatePlan the TemplateBuildPlan to initialize its properties
*/
public void initializePropertiesAsVariables(PropertyMap map, TemplateBuildPlan templatePlan) {
if (templatePlan.getRelationshipTemplate() != null) {
// template corresponds to a relationshiptemplate
this.initPropsAsVarsInRelationship(map, templatePlan);
} else {
this.initPropsAsVarsInNode(map, templatePlan);
}
}
/**
* Initializes Property variables and mappings for a TemplateBuildPlan which
* handles a RelationshipTemplate
*
* @param map the PropertyMap to save the result to
* @param templatePlan a TemplateBuildPlan which handles a
* RelationshipTemplate
*/
private void initPropsAsVarsInRelationship(PropertyMap map, TemplateBuildPlan templatePlan) {
AbstractRelationshipTemplate relationshipTemplate = templatePlan.getRelationshipTemplate();
if (relationshipTemplate.getProperties() != null) {
Element propertyElement = relationshipTemplate.getProperties().getDOMElement();
for (int i = 0; i < propertyElement.getChildNodes().getLength(); i++) {
if (propertyElement.getChildNodes().item(i).getNodeType() == Node.TEXT_NODE) {
continue;
}
String propName = propertyElement.getChildNodes().item(i).getLocalName();
String propVarName = relationshipTemplate.getId() + "_" + propertyElement.getChildNodes().item(i).getLocalName();
map.addPropertyMapping(relationshipTemplate.getId(), propName, "prop_" + propVarName);
// String value =
// propertyElement.getChildNodes().item(i).getFirstChild().getNodeValue();
String value = "";
for (int j = 0; j < propertyElement.getChildNodes().item(i).getChildNodes().getLength(); j++) {
if (propertyElement.getChildNodes().item(i).getChildNodes().item(j).getNodeType() == Node.TEXT_NODE) {
value += propertyElement.getChildNodes().item(i).getChildNodes().item(j).getNodeValue();
}
}
PropertyVariableInitializer.LOG.debug("Setting property variable " + propVarName);
PropertyVariableInitializer.LOG.debug("with value: " + value);
// tempID_PropLocalName as property variable name
this.planHandler.addPropertyVariable(propVarName, templatePlan.getBuildPlan());
if (!value.trim().isEmpty() && !value.trim().equals("")) {
// init the variable with the node value
this.planHandler.initializePropertyVariable(propVarName, value, templatePlan.getBuildPlan());
}
}
}
}
/**
* Initializes Property variables for the given TemplateBuildPlan which
* handles a NodeTemplate
*
* @param map a PropertyMap to save the result/mappings to
* @param templatePlan a TemplateBuildPlan which handles a NodeTemplate
*/
private void initPropsAsVarsInNode(PropertyMap map, TemplateBuildPlan templatePlan) {
AbstractNodeTemplate nodeTemplate = templatePlan.getNodeTemplate();
if (nodeTemplate.getProperties() != null) {
Element propertyElement = nodeTemplate.getProperties().getDOMElement();
for (int i = 0; i < propertyElement.getChildNodes().getLength(); i++) {
if (propertyElement.getChildNodes().item(i).getNodeType() == Node.TEXT_NODE) {
continue;
}
String propName = propertyElement.getChildNodes().item(i).getLocalName();
String propVarName = nodeTemplate.getId() + "_" + propertyElement.getChildNodes().item(i).getLocalName();
// TODO that "prop_" is a huge hack cause official only the
// buildplanhandler knows about the "prop_" piece
map.addPropertyMapping(nodeTemplate.getId(), propName, "prop_" + propVarName);
String value = "";
for (int j = 0; j < propertyElement.getChildNodes().item(i).getChildNodes().getLength(); j++) {
if (propertyElement.getChildNodes().item(i).getChildNodes().item(j).getNodeType() == Node.TEXT_NODE) {
value += propertyElement.getChildNodes().item(i).getChildNodes().item(j).getNodeValue();
}
}
PropertyVariableInitializer.LOG.debug("Setting property variable " + propVarName);
PropertyVariableInitializer.LOG.debug("with value: " + value);
// tempID_PropLocalName as property variable name
this.planHandler.addPropertyVariable(propVarName, templatePlan.getBuildPlan());
// init the variable with the node value
this.planHandler.initializePropertyVariable(propVarName, value, templatePlan.getBuildPlan());
}
}
}
}
|
package com.palette.battlebattle.simulator;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.palette.battlebattle.simulator.card.Card;
import com.palette.battlebattle.simulator.card.CardTester.Result;
public class ResultMatrix {
private List<String> cardNames;
private List<ResultMatrixResult> cardResults;
private class ResultMatrixResult {
private int totalWins = 0;
private int totalGames = 0;
private final String[] data;
public ResultMatrixResult(String[] data) {
this.data = data;
}
}
public ResultMatrix(List<Class<? extends Card>> cards) {
cardNames = cards.stream().map(Class::getSimpleName).sorted().collect(Collectors.toList());
cardResults = new ArrayList<>(cardNames.size());
for (int i = 0; i < cardNames.size(); ++i) {
cardResults.add(new ResultMatrixResult(new String[cardNames.size()]));
}
}
public void insertResult(Result one, Result two, int totalGames) {
int colPos = getPositionOfCard(one.getName());
int rowPos = getPositionOfCard(two.getName());
// First result
ResultMatrixResult firstResult = cardResults.get(colPos);
firstResult.totalGames += totalGames;
firstResult.totalWins += one.getWins();
String[] column = firstResult.data;
column[rowPos] = String.format("%.2f%%", (double) one.getWins()/totalGames * 100f);
// Second result
ResultMatrixResult secondResult = cardResults.get(rowPos);
secondResult.totalGames += totalGames;
secondResult.totalWins += two.getWins();
String[] column2 = secondResult.data;
column2[colPos] = String.format("%.2f%%", (double) two.getWins()/totalGames * 100f);
}
private int getPositionOfCard(String name) {
return cardNames.indexOf(name);
}
public String getPrettyMatrix() {
StringBuilder output = new StringBuilder("Card,Win Rate");
for (String name : cardNames) {
output.append("," + name);
}
output.append(System.lineSeparator());
for (int i = 0; i < cardResults.size(); ++i) {
ResultMatrixResult result = cardResults.get(i);
String[] cardResult = result.data;
output.append(cardNames.get(i) + ","
+ String.format("%.2f%%", (double) result.totalWins / result.totalGames * 100f));
for (int j = 0; j < cardResult.length; ++j) {
output.append("," + cardResult[j]);
}
output.append(System.lineSeparator());
}
return output.toString();
}
}
|
package com.intellij.execution.configurations;
import com.intellij.execution.process.UnixProcessManager;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.EnvironmentUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
/**
* @author Sergey Simonchik
*/
public class PathEnvironmentVariableUtil {
public static final String PATH_ENV_VAR_NAME = "PATH";
private static final String ourFixedMacPathEnvVarValue;
static {
ourFixedMacPathEnvVarValue = calcFixedMacPathEnvVarValue();
}
private PathEnvironmentVariableUtil() {
}
@Nullable
public static String getFixedPathEnvVarValueOnMac() {
return ourFixedMacPathEnvVarValue;
}
private static String calcFixedMacPathEnvVarValue() {
if (SystemInfo.isMac) {
final String originalPath = getOriginalPathEnvVarValue();
Map<? extends String, ? extends String> envVars = UnixProcessManager.getOrLoadConsoleEnvironment();
String consolePath = envVars.get(PATH_ENV_VAR_NAME);
return mergePaths(ContainerUtil.newArrayList(originalPath, consolePath));
}
return null;
}
@Nullable
private static String mergePaths(@NotNull List<String> pathStrings) {
LinkedHashSet<String> paths = ContainerUtil.newLinkedHashSet();
for (String pathString : pathStrings) {
if (pathString != null) {
List<String> locals = StringUtil.split(pathString, File.pathSeparator, true, true);
for (String local : locals) {
paths.add(local);
}
}
}
if (paths.isEmpty()) {
return null;
}
return StringUtil.join(paths, File.pathSeparator);
}
@Nullable
private static String getOriginalPathEnvVarValue() {
Map<String, String> originalEnvVars = EnvironmentUtil.getEnvironmentProperties();
return originalEnvVars.get(PATH_ENV_VAR_NAME);
}
@NotNull
private static String getReliablePath() {
final String value;
if (SystemInfo.isMac) {
value = getFixedPathEnvVarValueOnMac();
}
else {
value = getOriginalPathEnvVarValue();
}
return StringUtil.notNullize(value);
}
/**
* Finds an executable file with the specified base name, that is located in a directory
* listed in PATH environment variable.
*
* @param fileBaseName file base name
* @return {@code File} instance or null if not found
*/
@Nullable
public static File findInPath(@NotNull String fileBaseName) {
String pathEnvVarValue = getReliablePath();
List<String> paths = StringUtil.split(pathEnvVarValue, File.pathSeparator, true, true);
for (String path : paths) {
File dir = new File(path);
if (dir.isAbsolute() && dir.isDirectory()) {
File file = new File(dir, fileBaseName);
if (file.isFile() && file.canExecute()) {
return file;
}
}
}
return null;
}
}
|
package ca.antonious.habittracker.models;
import java.util.Date;
import java.util.UUID;
public class HabitCompletion {
private String id;
private Date completionTime;
public HabitCompletion(Date completionTime) {
setId(UUID.randomUUID().toString());
setCompletionTime(completionTime);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getCompletionTime() {
return completionTime;
}
public void setCompletionTime(Date completionTime) {
this.completionTime = completionTime;
}
}
|
package com.quollwriter.ui.charts;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import org.jfree.chart.*;
import org.jfree.ui.*;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.labels.XYToolTipGenerator;
import org.jfree.data.time.*;
import org.jfree.data.xy.XYDataset;
import org.jfree.chart.renderer.xy.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.*;
import com.quollwriter.*;
import com.quollwriter.data.*;
import com.quollwriter.ui.events.*;
import com.quollwriter.ui.*;
import com.quollwriter.ui.panels.*;
import com.quollwriter.db.*;
import com.quollwriter.ui.renderers.*;
import com.quollwriter.ui.components.Header;
import com.quollwriter.ui.components.ActionAdapter;
import com.quollwriter.ui.components.FormItem;
public class SessionWordCountChart extends AbstractQuollChart<AbstractViewer>
{
public static final String CHART_TYPE = "session-word-count";
public static final String CHART_TITLE = "Session Word Count";
private JFreeChart chart = null;
private JComponent controls = null;
private JComboBox displayB = null;
private JCheckBox showAvg = null;
private JCheckBox showTarget = null;
private JComponent detail = null;
public SessionWordCountChart (AbstractViewer v)
{
super (v);
}
public void init (StatisticsPanel wcp)
throws GeneralException
{
super.init (wcp);
this.createControls ();
}
private void createControls ()
{
final SessionWordCountChart _this = this;
Box b = new Box (BoxLayout.Y_AXIS);
b.setOpaque (false);
Header h = UIUtils.createBoldSubHeader (Environment.replaceObjectNames ("For"),
null);
h.setAlignmentY (Component.TOP_ALIGNMENT);
b.add (h);
Vector displayItems = new Vector ();
displayItems.add ("This week");
displayItems.add ("Last week");
displayItems.add ("This month");
displayItems.add ("Last month");
displayItems.add ("All time");
b.add (Box.createVerticalStrut (5));
this.displayB = new JComboBox (displayItems);
this.displayB.setAlignmentX (Component.LEFT_ALIGNMENT);
this.displayB.setMaximumSize (displayB.getPreferredSize ());
this.displayB.setAlignmentY (Component.TOP_ALIGNMENT);
this.displayB.addActionListener (new ActionAdapter ()
{
public void actionPerformed (ActionEvent ev)
{
_this.updateChart ();
}
});
Box db = new Box (BoxLayout.X_AXIS);
db.setAlignmentX (Component.LEFT_ALIGNMENT);
db.setAlignmentY (Component.TOP_ALIGNMENT);
db.add (Box.createHorizontalStrut (5));
db.add (this.displayB);
db.setMaximumSize (db.getPreferredSize ());
b.add (db);
b.add (Box.createVerticalStrut (10));
this.showAvg = UIUtils.createCheckBox ("Show Average",
new ActionListener ()
{
@Override
public void actionPerformed (ActionEvent ev)
{
_this.updateChart ();
}
});
this.showTarget = UIUtils.createCheckBox ("Show Target",
new ActionListener ()
{
@Override
public void actionPerformed (ActionEvent ev)
{
TargetsData targets = Environment.getUserTargets ();
if ((targets.getMySessionWriting () == 0)
)
{
UIUtils.createQuestionPopup (_this.viewer,
"Set up Target",
Constants.TARGET_ICON_NAME,
"You currently have no writing targets set up.<br /><br />Would you like to set the targets now?<br /><br />Note: Targets can be accessed at any time from the {Project} menu.",
"Yes, show me",
"No, not now",
new ActionListener ()
{
@Override public void actionPerformed (ActionEvent ev)
{
try
{
_this.viewer.viewTargets ();
} catch (Exception e) {
UIUtils.showErrorMessage (_this.viewer,
"Unable to show targets.");
Environment.logError ("Unable to show targets",
e);
}
}
},
null,
null,
null);
_this.showTarget.setSelected (false);
return;
}
_this.updateChart ();
}
});
Box opts = new Box (BoxLayout.Y_AXIS);
b.add (opts);
opts.setBorder (UIUtils.createPadding (0, 5, 0, 0));
opts.add (this.showAvg);
opts.add (this.showTarget);
this.controls = b;
}
private void createChart ()
throws GeneralException
{
int days = -1;
Date minDate = null;
Date maxDate = new Date ();
// This week.
if (this.displayB.getSelectedIndex () == 0)
{
// Work out how many days there have been this week.
GregorianCalendar gc = new GregorianCalendar ();
days = gc.get (Calendar.DAY_OF_WEEK) - gc.getFirstDayOfWeek ();
if (days < 0)
{
days -= 7;
}
gc.add (Calendar.DATE,
-1 * days);
minDate = gc.getTime ();
}
// Last week
if (this.displayB.getSelectedIndex () == 1)
{
GregorianCalendar gc = new GregorianCalendar ();
days = gc.get (Calendar.DAY_OF_WEEK) - gc.getFirstDayOfWeek ();
if (days < 0)
{
days -= 7;
}
gc.add (Calendar.DATE,
(-1 * days) - 1);
maxDate = gc.getTime ();
days += 7;
gc.add (Calendar.DATE,
-6);
minDate = gc.getTime ();
}
// This month.
if (this.displayB.getSelectedIndex () == 2)
{
GregorianCalendar gc = new GregorianCalendar ();
days = gc.get (Calendar.DATE);
gc.set (Calendar.DATE,
1);
minDate = gc.getTime ();
}
// Last month.
if (this.displayB.getSelectedIndex () == 3)
{
GregorianCalendar gc = new GregorianCalendar ();
gc.add (Calendar.MONTH,
-1);
days = gc.getActualMaximum (Calendar.DATE);
gc.set (Calendar.DATE,
days);
maxDate = gc.getTime ();
gc.set (Calendar.DATE,
1);
minDate = gc.getTime ();
}
// All time
if (this.displayB.getSelectedIndex () == 4)
{
days = -1;
}
long sessions = 0;
long totalWords = 0;
long totalTime = 0;
long sessionsAboveTarget = 0;
long longSessions = 0;
long maxTime = 0;
long maxWords = 0;
Session maxWordsSession = null;
Session longestSession = null;
int target = Environment.getUserTargets ().getMySessionWriting ();
final TimePeriodValuesCollection ds = new TimePeriodValuesCollection ();
try
{
TimePeriodValues vals = new TimePeriodValues ("Sessions");
for (Session s : Environment.getSessions (days))
{
int wc = s.getWordCount ();
if (wc == 0)
{
continue;
}
if (wc > target)
{
sessionsAboveTarget++;
}
if (days == -1)
{
if (minDate == null)
{
minDate = s.getStart ();
}
if (s.getStart ().before (minDate))
{
minDate = s.getStart ();
}
}
long time = s.getEnd ().getTime () - s.getStart ().getTime ();
totalTime += time;
totalWords += wc;
sessions++;
if (time > 60 * 60 * 1000)
{
longSessions++;
}
if (time > maxTime)
{
maxTime = time;
longestSession = s;
}
if (wc > maxWords)
{
maxWords = wc;
maxWordsSession = s;
}
vals.add (new SimpleTimePeriod (s.getStart (),
s.getEnd ()),
wc);
}
ds.addSeries (vals);
} catch (Exception e)
{
Environment.logError ("Unable to get sessions",
e);
UIUtils.showErrorMessage (this.parent,
"Unable to sessions");
return;
}
if (minDate == null)
{
minDate = new Date ();
}
this.chart = QuollChartUtils.createTimeSeriesChart ("Date",
"Word Count",
ds);
this.chart.removeLegend ();
XYPlot xyplot = (XYPlot) this.chart.getPlot ();
PeriodAxis axis = (PeriodAxis) xyplot.getDomainAxis ();
if (minDate != null)
{
axis.setLowerBound (minDate.getTime ());
axis.setUpperBound (maxDate.getTime ());
}
QuollChartUtils.customizePlot (xyplot);
if (this.showAvg.isSelected ())
{
long avgWords = (sessions > 0 ? totalWords / sessions : 0);
String t = "";
if (target > 0)
{
double diffAvg = avgWords - target;
t = String.format (", %s%s target",
(diffAvg < 0 ? "" : "+"),
Environment.formatNumber ((long) diffAvg));
}
xyplot.addRangeMarker (QuollChartUtils.createMarker (String.format ("Avg %s%s",
Environment.formatNumber (avgWords),
t),
avgWords,
0));
}
if (this.showTarget.isSelected ())
{
if (target > maxWords)
{
((NumberAxis) xyplot.getRangeAxis()).setUpperBound (target + 100);
}
xyplot.addRangeMarker (QuollChartUtils.createMarker (String.format ("Target %s",
Environment.formatNumber (target)),
target,
-1));
}
this.chart.setBackgroundPaint (UIUtils.getComponentColor ());
final SimpleDateFormat dateFormat = new SimpleDateFormat ("hh:mm a, EEE, dd MMM yyyy");
XYToolTipGenerator ttgen = new StandardXYToolTipGenerator ()
{
public String generateToolTip (XYDataset dataset,
int series,
int item)
{
TimePeriodValuesCollection tsc = (TimePeriodValuesCollection) dataset;
TimePeriodValues ts = tsc.getSeries (series);
Number n = ts.getValue (item);
StringBuilder b = new StringBuilder ();
b.append (dateFormat.format (ts.getTimePeriod (item).getStart ()));
b.append (", ");
b.append (Utils.formatAsDuration (n.intValue ()));
return b.toString ();
}
};
((XYBarRenderer) xyplot.getRenderer ()).setSeriesToolTipGenerator (0,
ttgen);
Set<JComponent> items = new LinkedHashSet ();
items.add (this.createDetailLabel (String.format ("%s - Session%s",
Environment.formatNumber (sessions),
(sessions == 1 ? "" : "s"))));
if (this.showTarget.isSelected ())
{
items.add (this.createDetailLabel (String.format ("%s - Sessions above word target",
Environment.formatNumber (sessionsAboveTarget))));
}
if (sessions > 0)
{
// Work out number of sessions over target.
items.add (this.createDetailLabel (String.format ("%s - Session%s over 1 hr",
Environment.formatNumber (longSessions),
(longSessions == 1 ? "" : "s"))));
items.add (this.createDetailLabel (String.format ("%s words, %s - Average session",
Environment.formatNumber (totalWords / sessions),
Utils.formatAsDuration (totalTime / sessions))));
items.add (this.createDetailLabel (String.format ("%s words, %s, %s, - Longest session",
Environment.formatNumber (longestSession.getWordCount ()),
Utils.formatAsDuration (longestSession.getSessionDuration ()),
Environment.formatDateTime (longestSession.getStart ()))));
items.add (this.createDetailLabel (String.format ("%s words, %s, %s - Session with most words",
Environment.formatNumber (maxWordsSession.getWordCount ()),
Utils.formatAsDuration (maxWordsSession.getSessionDuration ()),
Environment.formatDateTime (maxWordsSession.getStart ()))));
}
this.detail = QuollChartUtils.createDetailPanel (items);
}
public String getTitle ()
{
return CHART_TITLE;
}
public String getType ()
{
return CHART_TYPE;
}
public JComponent getControls (boolean update)
throws GeneralException
{
if (update)
{
this.controls = null;
}
if (this.controls == null)
{
this.createControls ();
}
return this.controls;
}
public JFreeChart getChart (boolean update)
throws GeneralException
{
if (update)
{
this.chart = null;
}
if (this.chart == null)
{
this.createChart ();
}
return this.chart;
}
public JComponent getDetail (boolean update)
throws GeneralException
{
if (update)
{
this.detail = null;
}
if (this.detail == null)
{
this.createChart ();
}
return this.detail;
}
public String toString ()
{
return Environment.replaceObjectNames (this.getTitle ());
}
}
|
package nl.b3p.viewer.stripes;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.NoResultException;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.After;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.StrictBinding;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.Validate;
import nl.b3p.viewer.config.app.ApplicationLayer;
import nl.b3p.viewer.config.app.ConfiguredAttribute;
import nl.b3p.viewer.config.services.AttributeDescriptor;
import nl.b3p.viewer.config.services.Layer;
import nl.b3p.viewer.config.services.SimpleFeatureType;
import nl.b3p.viewer.config.services.WFSFeatureSource;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.data.store.DataFeatureCollection;
import org.geotools.data.wfs.WFSDataStore;
import org.geotools.data.wfs.WFSDataStoreFactory;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.factory.GeoTools;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.sort.SortBy;
import org.opengis.filter.sort.SortOrder;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Matthijs Laan
*/
@UrlBinding("/action/appLayer")
@StrictBinding
public class AppLayerActionBean implements ActionBean {
private static final int MAX_FEATURES = 50;
private ActionBeanContext context;
@Validate
private ApplicationLayer appLayer;
private Layer layer = null;
@Validate
private int limit;
@Validate
private int page;
@Validate
private int start;
@Validate
private String dir;
@Validate
private String sort;
@Validate
private boolean arrays;
@Validate
private boolean debug;
//<editor-fold defaultstate="collapsed" desc="getters en setters">
public ActionBeanContext getContext() {
return context;
}
public void setContext(ActionBeanContext context) {
this.context = context;
}
public ApplicationLayer getAppLayer() {
return appLayer;
}
public void setAppLayer(ApplicationLayer appLayer) {
this.appLayer = appLayer;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public boolean isArrays() {
return arrays;
}
public void setArrays(boolean arrays) {
this.arrays = arrays;
}
//</editor-fold>
@After(stages=LifecycleStage.BindingAndValidation)
public void loadLayer() {
// TODO check if user has rights to appLayer
try {
layer = (Layer)Stripersist.getEntityManager().createQuery("from Layer where service = :service and name = :n order by virtual desc")
.setParameter("service", appLayer.getService())
.setParameter("n", appLayer.getLayerName())
.setMaxResults(1)
.getSingleResult();
} catch(NoResultException nre) {
}
}
public Resolution attributes() throws JSONException {
JSONObject json = new JSONObject();
json.put("success", Boolean.FALSE);
String error = null;
if(appLayer == null) {
error = "Invalid parameters";
} else {
Map<String,AttributeDescriptor> featureTypeAttributes = new HashMap<String,AttributeDescriptor>();
if(layer != null) {
SimpleFeatureType ft = layer.getFeatureType();
if(ft != null) {
for(AttributeDescriptor ad: ft.getAttributes()) {
featureTypeAttributes.put(ad.getName(), ad);
}
}
}
JSONArray attributes = new JSONArray();
for(ConfiguredAttribute ca: appLayer.getAttributes()) {
JSONObject j = ca.toJSONObject();
AttributeDescriptor ad = featureTypeAttributes.get(ca.getAttributeName());
if(ad != null) {
j.put("alias", ad.getAlias());
j.put("type", ad.getType());
}
attributes.put(j);
}
json.put("attributes", attributes);
json.put("success", Boolean.TRUE);
}
if(error != null) {
json.put("error", error);
}
return new StreamingResolution("application/json", new StringReader(json.toString()));
}
public Resolution store() throws JSONException, Exception {
JSONObject json = new JSONObject();
JSONArray features = new JSONArray();
json.put("features", features);
try {
int total = 0;
if(layer != null && layer.getFeatureType() != null) {
FeatureSource fs;
if(isDebug() && layer.getFeatureType().getFeatureSource() instanceof WFSFeatureSource) {
Map extraDataStoreParams = new HashMap();
extraDataStoreParams.put(WFSDataStoreFactory.TRY_GZIP.key, Boolean.FALSE);
fs = ((WFSFeatureSource)layer.getFeatureType().getFeatureSource()).openGeoToolsFeatureSource(layer.getFeatureType(), extraDataStoreParams);
} else {
fs = layer.getFeatureType().openGeoToolsFeatureSource();
}
boolean startIndexSupported = fs.getQueryCapabilities().isOffsetSupported();
Query q = new Query(fs.getName().toString());
FilterFactory2 ff2 = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
if(sort != null) {
String sortAttribute = sort;
if(arrays) {
int i = Integer.parseInt(sort);
int j = 0;
for(ConfiguredAttribute ca: appLayer.getAttributes()) {
if(ca.isVisible()) {
if(j == i) {
sortAttribute = ca.getAttributeName();
}
j++;
}
}
}
q.setSortBy(new SortBy[] {
ff2.sort(sortAttribute, "DESC".equals(dir) ? SortOrder.DESCENDING : SortOrder.ASCENDING)
});
}
total = fs.getCount(q);
if(total == -1) {
total = MAX_FEATURES;
}
q.setStartIndex(start);
q.setMaxFeatures(Math.min(limit + (startIndexSupported ? 0 : start),MAX_FEATURES));
FeatureCollection fc = fs.getFeatures(q);
if(!fc.isEmpty()) {
int featureCount;
if(fc instanceof DataFeatureCollection) {
featureCount = ((DataFeatureCollection)fc).getCount();
} else {
featureCount = fc.size(); /* This method swallows exceptions */
}
if(featureCount < (startIndexSupported ? limit : start + limit)) {
total = start + (startIndexSupported ? featureCount : featureCount - start);
}
FeatureIterator<SimpleFeature> it = fc.features();
try {
while(it.hasNext()) {
SimpleFeature f = it.next();
if(!startIndexSupported && start > 0) {
start
continue;
}
if(arrays) {
JSONArray j = new JSONArray();
for(ConfiguredAttribute ca: appLayer.getAttributes()) {
if(ca.isVisible()) {
j.put(f.getAttribute(ca.getAttributeName()));
}
}
features.put(j);
} else {
JSONObject j = new JSONObject();
for(ConfiguredAttribute ca: appLayer.getAttributes()) {
if(ca.isVisible()) {
String name = ca.getAttributeName();
j.put(name, f.getAttribute(name));
}
}
features.put(j);
}
}
} finally {
it.close();
fs.getDataStore().dispose();
}
}
}
json.put("total", total);
} catch(Exception e) {
json.put("success", false);
String message = "Fout bij ophalen features: " + e.toString();
Throwable cause = e.getCause();
while(cause != null) {
message += "; " + cause.toString();
cause = cause.getCause();
}
json.put("message", message);
}
return new StreamingResolution("application/json", new StringReader(json.toString()));
}
}
|
package org.jkiss.dbeaver.ext.mysql.tools;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IExportWizard;
import org.eclipse.ui.IWorkbench;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.ext.mysql.MySQLDataSourceProvider;
import org.jkiss.dbeaver.ext.mysql.MySQLMessages;
import org.jkiss.dbeaver.ext.mysql.MySQLServerHome;
import org.jkiss.dbeaver.ext.mysql.MySQLUtils;
import org.jkiss.dbeaver.ext.mysql.model.MySQLCatalog;
import org.jkiss.dbeaver.ext.mysql.model.MySQLTableBase;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.utils.ContentUtils;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.dbeaver.ui.dialogs.DialogUtils;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.dialogs.tools.AbstractToolWizard;
import java.io.*;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
class MySQLExportWizard extends AbstractToolWizard<MySQLCatalog> implements IExportWizard {
public enum DumpMethod {
ONLINE,
LOCK_ALL_TABLES,
NORMAL
}
private File outputFile;
DumpMethod method;
boolean noCreateStatements;
boolean addDropStatements = true;
boolean disableKeys = true;
boolean extendedInserts = true;
boolean dumpEvents;
boolean comments;
public boolean removeDefiner;
public List<MySQLDatabaseExportInfo> objects = new ArrayList<>();
private MySQLExportWizardPageObjects objectsPage;
private MySQLExportWizardPageSettings settingsPage;
public MySQLExportWizard(MySQLCatalog catalog) {
super(catalog, MySQLMessages.tools_db_export_wizard_task_name);
this.method = DumpMethod.NORMAL;
this.outputFile = new File(DialogUtils.getCurDialogFolder(), catalog.getName() + "-" + RuntimeUtils.getCurrentTimeStamp() + ".sql"); //$NON-NLS-1$ //$NON-NLS-2$
}
public File getOutputFile()
{
return outputFile;
}
public void setOutputFile(File outputFile)
{
DialogUtils.setCurDialogFolder(outputFile.getParentFile().getAbsolutePath());
this.outputFile = outputFile;
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
setWindowTitle(MySQLMessages.tools_db_export_wizard_title);
setNeedsProgressMonitor(true);
objectsPage = new MySQLExportWizardPageObjects(this);
settingsPage = new MySQLExportWizardPageSettings(this);
}
@Override
public void addPages() {
super.addPages();
addPage(objectsPage);
addPage(settingsPage);
addPage(logPage);
}
@Override
public IWizardPage getNextPage(IWizardPage page) {
if (page == settingsPage) {
return null;
}
return super.getNextPage(page);
}
@Override
public IWizardPage getPreviousPage(IWizardPage page) {
if (page == logPage) {
return null;
}
return super.getPreviousPage(page);
}
@Override
public void onSuccess() {
UIUtils.showMessageBox(
getShell(),
MySQLMessages.tools_db_export_wizard_title,
NLS.bind(MySQLMessages.tools_db_export_wizard_message_export_completed, getDatabaseObject().getName()),
SWT.ICON_INFORMATION);
UIUtils.launchProgram(outputFile.getAbsoluteFile().getParentFile().getAbsolutePath());
}
@Override
public void fillProcessParameters(List<String> cmd) throws IOException
{
File dumpBinary = MySQLUtils.getHomeBinary(getClientHome(), "mysqldump"); //$NON-NLS-1$
String dumpPath = dumpBinary.getAbsolutePath();
cmd.add(dumpPath);
switch (method) {
case LOCK_ALL_TABLES:
cmd.add("--lock-all-tables"); //$NON-NLS-1$
break;
case ONLINE:
cmd.add("--single-transaction"); //$NON-NLS-1$
break;
}
if (noCreateStatements) {
cmd.add("--no-create-info"); //$NON-NLS-1$
} else {
cmd.add("--routines"); //$NON-NLS-1$
}
if (addDropStatements) cmd.add("--add-drop-table"); //$NON-NLS-1$
if (disableKeys) cmd.add("--disable-keys"); //$NON-NLS-1$
if (extendedInserts) cmd.add("--extended-insert"); //$NON-NLS-1$
if (dumpEvents) cmd.add("--events"); //$NON-NLS-1$
if (comments) cmd.add("--comments"); //$NON-NLS-1$
}
@Override
public boolean performFinish() {
final File dir = outputFile.getParentFile();
if (!dir.exists()) {
if (!dir.mkdirs()) {
logPage.setMessage("Can't create directory '" + dir.getAbsolutePath() + "'", IMessageProvider.ERROR);
getContainer().updateMessage();
return false;
}
}
objectsPage.saveState();
return super.performFinish();
}
@Override
public MySQLServerHome findServerHome(String clientHomeId)
{
return MySQLDataSourceProvider.getServerHome(clientHomeId);
}
@Override
protected List<String> getCommandLine() throws IOException
{
return MySQLToolScript.getMySQLToolCommandLine(this);
}
@Override
public boolean isVerbose()
{
return true;
}
@Override
protected void startProcessHandler(DBRProgressMonitor monitor, ProcessBuilder processBuilder, Process process)
{
logPage.startLogReader(
processBuilder,
process.getErrorStream());
new DumpCopierJob(monitor, process.getInputStream()).start();
}
class DumpCopierJob extends Thread {
private DBRProgressMonitor monitor;
private InputStream input;
protected DumpCopierJob(DBRProgressMonitor monitor, InputStream stream)
{
super(MySQLMessages.tools_db_export_wizard_job_dump_log_reader);
this.monitor = monitor;
this.input = stream;
}
@Override
public void run()
{
monitor.beginTask(MySQLMessages.tools_db_export_wizard_monitor_export_db, 100);
long totalBytesDumped = 0;
long prevStatusUpdateTime = 0;
byte[] buffer = new byte[10000];
try {
NumberFormat numberFormat = NumberFormat.getInstance();
try (OutputStream output = new FileOutputStream(outputFile)){
for (;;) {
int count = input.read(buffer);
if (count <= 0) {
break;
}
totalBytesDumped += count;
long currentTime = System.currentTimeMillis();
if (currentTime - prevStatusUpdateTime > 300) {
monitor.subTask(NLS.bind(MySQLMessages.tools_db_export_wizard_monitor_bytes, numberFormat.format(totalBytesDumped)));
prevStatusUpdateTime = currentTime;
}
output.write(buffer, 0, count);
}
output.flush();
}
} catch (IOException e) {
logPage.appendLog(e.getMessage());
}
finally {
monitor.done();
}
}
}
class DumpFilterJob extends Thread {
private DBRProgressMonitor monitor;
private InputStream input;
protected DumpFilterJob(DBRProgressMonitor monitor, InputStream stream)
{
super(MySQLMessages.tools_db_export_wizard_job_dump_log_reader);
this.monitor = monitor;
this.input = stream;
}
@Override
public void run()
{
monitor.beginTask(MySQLMessages.tools_db_export_wizard_monitor_export_db, 100);
long prevStatusUpdateTime = 0;
try {
NumberFormat numberFormat = NumberFormat.getInstance();
LineNumberReader reader = new LineNumberReader(new InputStreamReader(input, ContentUtils.DEFAULT_CHARSET));
try (OutputStream output = new FileOutputStream(outputFile)) {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
for (;;) {
String line = reader.readLine();
if (line == null) {
break;
}
long currentTime = System.currentTimeMillis();
if (currentTime - prevStatusUpdateTime > 300) {
monitor.subTask("Saved " + numberFormat.format(reader.getLineNumber()) + " lines");
prevStatusUpdateTime = currentTime;
}
line = filterLine(line);
writer.write(line);
writer.newLine();
}
output.flush();
}
} catch (IOException e) {
logPage.appendLog(e.getMessage());
}
finally {
monitor.done();
}
}
@NotNull
private String filterLine(@NotNull String line) {
return line;
}
}
}
|
package com.cloud.test;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.cloud.host.Status;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.NetworkOffering.GuestIpType;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDaoImpl;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.dao.DiskOfferingDaoImpl;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.net.NfsUtils;
public class DatabaseConfig {
private static final Logger s_logger = Logger.getLogger(DatabaseConfig.class.getName());
private String _configFileName = null;
private String _currentObjectName = null;
private String _currentFieldName = null;
private Map<String, String> _currentObjectParams = null;
private static Map<String, String> s_configurationDescriptions = new HashMap<String, String>();
private static Map<String, String> s_configurationComponents = new HashMap<String, String>();
private static Map<String, String> s_defaultConfigurationValues = new HashMap<String, String>();
// Change to HashSet
private static HashSet<String> objectNames = new HashSet<String>();
private static HashSet<String> fieldNames = new HashSet<String>();
// Maintain an IPRangeConfig object to handle IP related logic
private final IPRangeConfig iprc = ComponentLocator.inject(IPRangeConfig.class);
// Maintain a PodZoneConfig object to handle Pod/Zone related logic
private final PodZoneConfig pzc = ComponentLocator.inject(PodZoneConfig.class);
// Global variables to store network.throttling.rate and multicast.throttling.rate from the configuration table
// Will be changed from null to a non-null value if the value existed in the configuration table
private String _networkThrottlingRate = null;
private String _multicastThrottlingRate = null;
private int _poolId = 2;
static {
// initialize the objectNames ArrayList
objectNames.add("zone");
objectNames.add("vlan");
objectNames.add("pod");
objectNames.add("storagePool");
objectNames.add("secondaryStorage");
objectNames.add("serviceOffering");
objectNames.add("diskOffering");
objectNames.add("user");
objectNames.add("pricing");
objectNames.add("configuration");
objectNames.add("privateIpAddresses");
objectNames.add("publicIpAddresses");
// initialize the fieldNames ArrayList
fieldNames.add("id");
fieldNames.add("name");
fieldNames.add("dns1");
fieldNames.add("dns2");
fieldNames.add("internalDns1");
fieldNames.add("internalDns2");
fieldNames.add("guestNetworkCidr");
fieldNames.add("gateway");
fieldNames.add("netmask");
fieldNames.add("vncConsoleIp");
fieldNames.add("zoneId");
fieldNames.add("vlanId");
fieldNames.add("cpu");
fieldNames.add("ramSize");
fieldNames.add("speed");
fieldNames.add("useLocalStorage");
fieldNames.add("diskSpace");
fieldNames.add("nwRate");
fieldNames.add("mcRate");
fieldNames.add("price");
fieldNames.add("username");
fieldNames.add("password");
fieldNames.add("firstname");
fieldNames.add("lastname");
fieldNames.add("email");
fieldNames.add("priceUnit");
fieldNames.add("type");
fieldNames.add("value");
fieldNames.add("podId");
fieldNames.add("podName");
fieldNames.add("ipAddressRange");
fieldNames.add("vlanType");
fieldNames.add("vlanName");
fieldNames.add("cidr");
fieldNames.add("vnet");
fieldNames.add("mirrored");
fieldNames.add("enableHA");
fieldNames.add("displayText");
fieldNames.add("domainId");
fieldNames.add("hostAddress");
fieldNames.add("hostPath");
fieldNames.add("guestIpType");
fieldNames.add("url");
fieldNames.add("storageType");
fieldNames.add("category");
fieldNames.add("tags");
s_configurationDescriptions.put("host.stats.interval", "the interval in milliseconds when host stats are retrieved from agents");
s_configurationDescriptions.put("storage.stats.interval", "the interval in milliseconds when storage stats (per host) are retrieved from agents");
s_configurationDescriptions.put("volume.stats.interval", "the interval in milliseconds when volume stats are retrieved from agents");
s_configurationDescriptions.put("host", "host address to listen on for agent connection");
s_configurationDescriptions.put("port", "port to listen on for agent connection");
//s_configurationDescriptions.put("guest.ip.network", "ip address for the router");
//s_configurationDescriptions.put("guest.netmask", "default netmask for the guest network");
s_configurationDescriptions.put("domain.suffix", "domain suffix for users");
s_configurationDescriptions.put("instance.name", "Name of the deployment instance");
s_configurationDescriptions.put("storage.overprovisioning.factor", "Storage Allocator overprovisioning factor");
s_configurationDescriptions.put("retries.per.host", "The number of times each command sent to a host should be retried in case of failure.");
s_configurationDescriptions.put("integration.api.port", "internal port used by the management server for servicing Integration API requests");
s_configurationDescriptions.put("usage.stats.job.exec.time", "the time at which the usage statistics aggregation job will run as an HH24:MM time, e.g. 00:30 to run at 12:30am");
s_configurationDescriptions.put("usage.stats.job.aggregation.range", "the range of time for aggregating the user statistics specified in minutes (e.g. 1440 for daily, 60 for hourly)");
s_configurationDescriptions.put("consoleproxy.domP.enable", "Obsolete");
s_configurationDescriptions.put("consoleproxy.port", "Obsolete");
s_configurationDescriptions.put("consoleproxy.url.port", "Console proxy port for AJAX viewer");
s_configurationDescriptions.put("consoleproxy.ram.size", "RAM size (in MB) used to create new console proxy VMs");
s_configurationDescriptions.put("consoleproxy.cmd.port", "Console proxy command port that is used to communicate with management server");
s_configurationDescriptions.put("consoleproxy.loadscan.interval", "The time interval(in milliseconds) to scan console proxy working-load info");
s_configurationDescriptions.put("consoleproxy.capacityscan.interval", "The time interval(in millisecond) to scan whether or not system needs more console proxy to ensure minimal standby capacity");
s_configurationDescriptions.put("consoleproxy.capacity.standby", "The minimal number of console proxy viewer sessions that system is able to serve immediately(standby capacity)");
s_configurationDescriptions.put("alert.email.addresses", "comma seperated list of email addresses used for sending alerts");
s_configurationDescriptions.put("alert.smtp.host", "SMTP hostname used for sending out email alerts");
s_configurationDescriptions.put("alert.smtp.port", "port the SMTP server is listening on (default is 25)");
s_configurationDescriptions.put("alert.smtp.useAuth", "If true, use SMTP authentication when sending emails. If false, do not use SMTP authentication when sending emails.");
s_configurationDescriptions.put("alert.smtp.username", "username for SMTP authentication (applies only if alert.smtp.useAuth is true)");
s_configurationDescriptions.put("alert.smtp.password", "password for SMTP authentication (applies only if alert.smtp.useAuth is true)");
s_configurationDescriptions.put("alert.email.sender", "sender of alert email (will be in the From header of the email)");
s_configurationDescriptions.put("memory.capacity.threshold", "percentage (as a value between 0 and 1) of memory utilization above which alerts will be sent about low memory available");
s_configurationDescriptions.put("cpu.capacity.threshold", "percentage (as a value between 0 and 1) of cpu utilization above which alerts will be sent about low cpu available");
s_configurationDescriptions.put("storage.capacity.threshold", "percentage (as a value between 0 and 1) of storage utilization above which alerts will be sent about low storage available");
s_configurationDescriptions.put("public.ip.capacity.threshold", "percentage (as a value between 0 and 1) of public IP address space utilization above which alerts will be sent");
s_configurationDescriptions.put("private.ip.capacity.threshold", "percentage (as a value between 0 and 1) of private IP address space utilization above which alerts will be sent");
s_configurationDescriptions.put("max.account.user.vms", "the maximum number of user VMs that can be deployed for an account");
s_configurationDescriptions.put("max.account.public.ips", "the maximum number of public IPs that can be reserved for an account");
s_configurationDescriptions.put("expunge.interval", "the interval to wait before running the expunge thread");
s_configurationDescriptions.put("network.throttling.rate", "default data transfer rate in megabits per second allowed per user");
s_configurationDescriptions.put("multicast.throttling.rate", "default multicast rate in megabits per second allowed");
s_configurationDescriptions.put("use.local.storage", "Indicates whether to use local storage pools or shared storage pools for user VMs");
s_configurationDescriptions.put("use.local.storage", "Indicates whether to use local storage pools or shared storage pools for system VMs.");
s_configurationDescriptions.put("snapshot.poll.interval", "The time interval in seconds when the management server polls for snapshots to be scheduled.");
s_configurationDescriptions.put("snapshot.recurring.test", "Flag for testing recurring snapshots");
s_configurationDescriptions.put("snapshot.test.minutes.per.hour", "Set it to a smaller value to take more recurring snapshots");
s_configurationDescriptions.put("snapshot.test.hours.per.day", "Set it to a smaller value to take more recurring snapshots");
s_configurationDescriptions.put("snapshot.test.days.per.week", "Set it to a smaller value to take more recurring snapshots");
s_configurationDescriptions.put("snapshot.test.days.per.month", "Set it to a smaller value to take more recurring snapshots");
s_configurationDescriptions.put("snapshot.test.weeks.per.month", "Set it to a smaller value to take more recurring snapshots");
s_configurationDescriptions.put("snapshot.test.months.per.year", "Set it to a smaller value to take more recurring snapshots");
s_configurationDescriptions.put("network.type", "The type of network that this deployment will use.");
s_configurationDescriptions.put("hypervisor.type", "The type of hypervisor that this deployment will use.");
s_configurationComponents.put("host.stats.interval", "management-server");
s_configurationComponents.put("storage.stats.interval", "management-server");
s_configurationComponents.put("volume.stats.interval", "management-server");
s_configurationComponents.put("integration.api.port", "management-server");
s_configurationComponents.put("usage.stats.job.exec.time", "management-server");
s_configurationComponents.put("usage.stats.job.aggregation.range", "management-server");
s_configurationComponents.put("consoleproxy.domP.enable", "management-server");
s_configurationComponents.put("consoleproxy.port", "management-server");
s_configurationComponents.put("consoleproxy.url.port", "management-server");
s_configurationComponents.put("router.cleanup.interval", "management-server");
s_configurationComponents.put("alert.email.addresses", "management-server");
s_configurationComponents.put("alert.smtp.host", "management-server");
s_configurationComponents.put("alert.smtp.port", "management-server");
s_configurationComponents.put("alert.smtp.useAuth", "management-server");
s_configurationComponents.put("alert.smtp.username", "management-server");
s_configurationComponents.put("alert.smtp.password", "management-server");
s_configurationComponents.put("alert.email.sender", "management-server");
s_configurationComponents.put("memory.capacity.threshold", "management-server");
s_configurationComponents.put("cpu.capacity.threshold", "management-server");
s_configurationComponents.put("storage.capacity.threshold", "management-server");
s_configurationComponents.put("public.ip.capacity.threshold", "management-server");
s_configurationComponents.put("private.ip.capacity.threshold", "management-server");
s_configurationComponents.put("capacity.check.period", "management-server");
s_configurationComponents.put("max.account.user.vms", "management-server");
s_configurationComponents.put("max.account.public.ips", "management-server");
s_configurationComponents.put("network.throttling.rate", "management-server");
s_configurationComponents.put("multicast.throttling.rate", "management-server");
s_configurationComponents.put("account.cleanup.interval", "management-server");
s_configurationComponents.put("expunge.delay", "UserVmManager");
s_configurationComponents.put("expunge.interval", "UserVmManager");
s_configurationComponents.put("host", "AgentManager");
s_configurationComponents.put("port", "AgentManager");
// s_configurationComponents.put("guest.ip.network", "AgentManager");
// s_configurationComponents.put("guest.netmask", "AgentManager");
s_configurationComponents.put("domain", "AgentManager");
s_configurationComponents.put("instance.name", "AgentManager");
s_configurationComponents.put("storage.overprovisioning.factor", "StorageAllocator");
s_configurationComponents.put("retries.per.host", "AgentManager");
s_configurationComponents.put("start.retry", "AgentManager");
s_configurationComponents.put("wait", "AgentManager");
s_configurationComponents.put("ping.timeout", "AgentManager");
s_configurationComponents.put("ping.interval", "AgentManager");
s_configurationComponents.put("alert.wait", "AgentManager");
s_configurationComponents.put("update.wait", "AgentManager");
s_configurationComponents.put("domain.suffix", "AgentManager");
s_configurationComponents.put("consoleproxy.ram.size", "AgentManager");
s_configurationComponents.put("consoleproxy.cmd.port", "AgentManager");
s_configurationComponents.put("consoleproxy.loadscan.interval", "AgentManager");
s_configurationComponents.put("consoleproxy.capacityscan.interval", "AgentManager");
s_configurationComponents.put("consoleproxy.capacity.standby", "AgentManager");
s_configurationComponents.put("consoleproxy.session.max", "AgentManager");
s_configurationComponents.put("consoleproxy.session.timeout", "AgentManager");
s_configurationComponents.put("expunge.workers", "UserVmManager");
s_configurationComponents.put("stop.retry.interval", "HighAvailabilityManager");
s_configurationComponents.put("restart.retry.interval", "HighAvailabilityManager");
s_configurationComponents.put("investigate.retry.interval", "HighAvailabilityManager");
s_configurationComponents.put("migrate.retry.interval", "HighAvailabilityManager");
s_configurationComponents.put("storage.overwrite.provisioning", "UserVmManager");
s_configurationComponents.put("init", "none");
s_configurationComponents.put("system.vm.use.local.storage", "ManagementServer");
s_configurationComponents.put("use.local.storage", "ManagementServer");
s_configurationComponents.put("snapshot.poll.interval", "SnapshotManager");
s_configurationComponents.put("snapshot.recurring.test", "SnapshotManager");
s_configurationComponents.put("snapshot.test.minutes.per.hour", "SnapshotManager");
s_configurationComponents.put("snapshot.test.hours.per.day", "SnapshotManager");
s_configurationComponents.put("snapshot.test.days.per.week", "SnapshotManager");
s_configurationComponents.put("snapshot.test.days.per.month", "SnapshotManager");
s_configurationComponents.put("snapshot.test.weeks.per.month", "SnapshotManager");
s_configurationComponents.put("snapshot.test.months.per.year", "SnapshotManager");
s_configurationComponents.put("network.type", "ManagementServer");
s_configurationComponents.put("hypervisor.type", "ManagementServer");
s_defaultConfigurationValues.put("host.stats.interval", "60000");
s_defaultConfigurationValues.put("storage.stats.interval", "60000");
//s_defaultConfigurationValues.put("volume.stats.interval", "-1");
s_defaultConfigurationValues.put("port", "8250");
s_defaultConfigurationValues.put("integration.api.port", "8096");
s_defaultConfigurationValues.put("usage.stats.job.exec.time", "00:15"); // run at 12:15am
s_defaultConfigurationValues.put("usage.stats.job.aggregation.range", "1440"); // do a daily aggregation
// s_defaultConfigurationValues.put("guest.ip.network", "10.1.1.1");
// s_defaultConfigurationValues.put("guest.netmask", "255.255.255.0");
s_defaultConfigurationValues.put("storage.overprovisioning.factor", "2");
s_defaultConfigurationValues.put("retries.per.host", "2");
s_defaultConfigurationValues.put("ping.timeout", "2.5");
s_defaultConfigurationValues.put("ping.interval", "60");
s_defaultConfigurationValues.put("snapshot.poll.interval", "300");
s_defaultConfigurationValues.put("snapshot.recurring.test", "false");
s_defaultConfigurationValues.put("snapshot.test.minutes.per.hour", "60");
s_defaultConfigurationValues.put("snapshot.test.hours.per.day", "24");
s_defaultConfigurationValues.put("snapshot.test.days.per.week", "7");
s_defaultConfigurationValues.put("snapshot.test.days.per.month", "30");
s_defaultConfigurationValues.put("snapshot.test.weeks.per.month", "4");
s_defaultConfigurationValues.put("snapshot.test.months.per.year", "12");
s_defaultConfigurationValues.put("alert.wait", "1800");
s_defaultConfigurationValues.put("update.wait", "600");
s_defaultConfigurationValues.put("max.account.user.vms", "20");
s_defaultConfigurationValues.put("max.account.public.ips", "20");
s_defaultConfigurationValues.put("expunge.interval", "86400");
s_defaultConfigurationValues.put("instance.name", "VM");
s_defaultConfigurationValues.put("expunge.workers", "1");
s_defaultConfigurationValues.put("stop.retry.interval", "600");
s_defaultConfigurationValues.put("restart.retry.interval", "600");
s_defaultConfigurationValues.put("investigate.retry.interval", "60");
s_defaultConfigurationValues.put("migrate.retry.interval", "120");
// s_defaultConfigurationValues.put("network.throttling.rate", "200");
// s_defaultConfigurationValues.put("multicast.throttling.rate", "10");
s_defaultConfigurationValues.put("account.cleanup.interval", "86400");
s_defaultConfigurationValues.put("system.vm.use.local.storage", "false");
s_defaultConfigurationValues.put("use.local.storage", "false");
s_defaultConfigurationValues.put("init", "false");
s_defaultConfigurationValues.put("network.type", "vnet");
s_defaultConfigurationValues.put("hypervisor.type", "kvm");
}
protected DatabaseConfig() {
}
/**
* @param args - name of server-setup.xml file which contains the bootstrap data
*/
public static void main(String[] args) {
System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
System.setProperty("javax.xml.parsers.SAXParserFactory", "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
File file = PropertiesUtil.findConfigFile("log4j-cloud.xml");
if(file != null) {
System.out.println("Log4j configuration from : " + file.getAbsolutePath());
DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000);
} else {
System.out.println("Configure log4j with default properties");
}
if (args.length < 1) {
s_logger.error("error starting database config, missing initial data file");
} else {
try {
DatabaseConfig config = ComponentLocator.inject(DatabaseConfig.class, args[0]);
config.doVersionCheck();
config.doConfig();
System.exit(0);
} catch (Exception ex) {
System.out.print("Error Caught");
ex.printStackTrace();
s_logger.error("error", ex);
}
}
}
public DatabaseConfig(String configFileName) {
_configFileName = configFileName;
}
private void doVersionCheck() {
try {
String warningMsg = "\nYou are using an outdated format for server-setup.xml. Please switch to the new format.\n";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder dbuilder = dbf.newDocumentBuilder();
File configFile = new File(_configFileName);
Document d = dbuilder.parse(configFile);
NodeList nodeList = d.getElementsByTagName("version");
if (nodeList.getLength() == 0) {
System.out.println(warningMsg);
return;
}
Node firstNode = nodeList.item(0);
String version = firstNode.getTextContent();
if (!version.equals("2.0")) {
System.out.println(warningMsg);
}
} catch (ParserConfigurationException parserException) {
parserException.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (SAXException saxException) {
saxException.printStackTrace();
}
}
@DB
protected void doConfig() {
Transaction txn = Transaction.currentTxn();
try {
File configFile = new File(_configFileName);
SAXParserFactory spfactory = SAXParserFactory.newInstance();
SAXParser saxParser = spfactory.newSAXParser();
DbConfigXMLHandler handler = new DbConfigXMLHandler();
handler.setParent(this);
txn.start();
// Save user configured values for all fields
saxParser.parse(configFile, handler);
// Save default values for configuration fields
saveVMTemplate();
saveRootDomain();
saveDefaultConfiguations();
txn.commit();
// Save network.throttling.rate and multicast.throttling.rate for all service offerings, if these values are in the configuration table
saveThrottlingRates();
// Check pod CIDRs against each other, and against the guest ip network/netmask
pzc.checkAllPodCidrSubnets();
txn.commit();
} catch (Exception ex) {
System.out.print("ERROR IS"+ex);
s_logger.error("error", ex);
txn.rollback();
}
}
private void setCurrentObjectName(String name) {
_currentObjectName = name;
}
private void saveCurrentObject() {
if ("zone".equals(_currentObjectName)) {
saveZone();
} else if ("vlan".equals(_currentObjectName)) {
saveVlan();
} else if ("pod".equals(_currentObjectName)) {
savePod();
} else if ("serviceOffering".equals(_currentObjectName)) {
saveServiceOffering();
} else if ("diskOffering".equals(_currentObjectName)) {
saveDiskOffering();
} else if ("user".equals(_currentObjectName)) {
saveUser();
} else if ("configuration".equals(_currentObjectName)) {
saveConfiguration();
} else if ("storagePool".equals(_currentObjectName)) {
saveStoragePool();
} else if ("secondaryStorage".equals(_currentObjectName)) {
saveSecondaryStorage();
}
_currentObjectParams = null;
}
@DB
public void saveSecondaryStorage() {
long dataCenterId = Long.parseLong(_currentObjectParams.get("zoneId"));
String url = _currentObjectParams.get("url");
String mountPoint;
try {
mountPoint = NfsUtils.url2Mount(url);
} catch (URISyntaxException e1) {
return;
}
String insertSql1 = "INSERT INTO `host` (`id`, `name`, `status` , `type` , `private_ip_address`, `private_netmask` ,`private_mac_address` , `storage_ip_address` ,`storage_netmask`, `storage_mac_address`, `data_center_id`, `version`, `sequence`, `dom0_memory`, `last_ping`, `resource`, `guid`, `hypervisor_type`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
String insertSqlHostDetails = "INSERT INTO `host_details` (`id`, `host_id`, `name`, `value`) VALUES(?,?,?,?)";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql1);
stmt.setLong(1, 0);
stmt.setString(2, url);
stmt.setString(3, "UP");
stmt.setString(4, "SecondaryStorage");
stmt.setString(5, "192.168.122.1");
stmt.setString(6, "255.255.255.0");
stmt.setString(7, "92:ff:f5:ad:23:e1");
stmt.setString(8, "192.168.122.1");
stmt.setString(9, "255.255.255.0");
stmt.setString(10, "92:ff:f5:ad:23:e1");
stmt.setLong(11, dataCenterId);
stmt.setString(12, "1.9.7");
stmt.setLong(13, 1);
stmt.setLong(14, 0);
stmt.setLong(15, 1238425896);
boolean nfs = false;
if (url.startsWith("nfs")) {
nfs = true;
}
if (nfs) {
stmt.setString(16, "com.cloud.storage.resource.NfsSecondaryStorageResource");
} else {
stmt.setString(16, "com.cloud.storage.secondary.LocalSecondaryStorageResource");
}
stmt.setString(17, url);
stmt.setString(18, "None");
stmt.executeUpdate();
stmt = txn.prepareAutoCloseStatement(insertSqlHostDetails);
stmt.setLong(1, 1);
stmt.setLong(2, 1);
stmt.setString(3, "mount.parent");
if (nfs) {
stmt.setString(4, "/mnt");
} else
stmt.setString(4, "/");
stmt.executeUpdate();
stmt.setLong(1, 2);
stmt.setLong(2, 1);
stmt.setString(3, "mount.path");
if (nfs) {
stmt.setString(4, mountPoint);
} else
stmt.setString(4, url.replaceFirst("file:/", ""));
stmt.executeUpdate();
stmt.setLong(1, 3);
stmt.setLong(2, 1);
stmt.setString(3, "orig.url");
stmt.setString(4, url);
stmt.executeUpdate();
} catch (SQLException ex) {
System.out.println("Error creating secondary storage: " + ex.getMessage());
return;
}
}
@DB
public void saveStoragePool() {
String name = _currentObjectParams.get("name");
long dataCenterId = Long.parseLong(_currentObjectParams.get("zoneId"));
long podId = Long.parseLong(_currentObjectParams.get("podId"));
String hostAddress = _currentObjectParams.get("hostAddress");
String hostPath = _currentObjectParams.get("hostPath");
String storageType = _currentObjectParams.get("storageType");
String uuid = UUID.nameUUIDFromBytes(new String(hostAddress+hostPath).getBytes()).toString();
String insertSql1 = "INSERT INTO `storage_pool` (`id`, `name`, `uuid` , `pool_type` , `port`, `data_center_id` ,`available_bytes` , `capacity_bytes` ,`host_address`, `path`, `created`, `pod_id`,`status` ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
// String insertSql2 = "INSERT INTO `netfs_storage_pool` VALUES (?,?,?)";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql1);
stmt.setLong(1, _poolId++);
stmt.setString(2, name);
stmt.setString(3, uuid);
if (storageType == null)
stmt.setString(4, "NetworkFileSystem");
else
stmt.setString(4, storageType);
stmt.setLong(5, 111);
stmt.setLong(6, dataCenterId);
stmt.setLong(7,0);
stmt.setLong(8,0);
stmt.setString(9, hostAddress);
stmt.setString(10, hostPath);
stmt.setDate(11, new Date(new java.util.Date().getTime()));
stmt.setLong(12, podId);
stmt.setString(13, Status.Up.toString());
stmt.executeUpdate();
// stmt = txn.prepareAutoCloseStatement(insertSql2);
// stmt.setLong(1, 2);
// stmt.setString(2, hostAddress);
// stmt.setString(3, hostPath);
// stmt.executeUpdate();
} catch (SQLException ex) {
System.out.println("Error creating storage pool: " + ex.getMessage());
s_logger.error("error creating service offering", ex);
return;
}
}
private void saveZone() {
long id = Long.parseLong(_currentObjectParams.get("id"));
String name = _currentObjectParams.get("name");
//String description = _currentObjectParams.get("description");
String dns1 = _currentObjectParams.get("dns1");
String dns2 = _currentObjectParams.get("dns2");
String internalDns1 = _currentObjectParams.get("internalDns1");
String internalDns2 = _currentObjectParams.get("internalDns2");
String vnetRange = _currentObjectParams.get("vnet");
String guestNetworkCidr = _currentObjectParams.get("guestNetworkCidr");
// Check that all IPs are valid
String ipError = "Please enter a valid IP address for the field: ";
if (!IPRangeConfig.validOrBlankIP(dns1)) printError(ipError + "dns1");
if (!IPRangeConfig.validOrBlankIP(dns2)) printError(ipError + "dns2");
if (!IPRangeConfig.validOrBlankIP(internalDns1)) printError(ipError + "internalDns1");
if (!IPRangeConfig.validOrBlankIP(internalDns2)) printError(ipError + "internalDns2");
if (!IPRangeConfig.validCIDR(guestNetworkCidr)) printError("Please enter a valid value for guestNetworkCidr");
int vnetStart = -1;
int vnetEnd = -1;
if (vnetRange != null) {
String[] tokens = vnetRange.split("-");
vnetStart = Integer.parseInt(tokens[0]);
vnetEnd = Integer.parseInt(tokens[1]);
}
pzc.saveZone(false, id, name, dns1, dns2, internalDns1, internalDns2, vnetStart, vnetEnd, guestNetworkCidr);
}
private void saveVlan() {
String zoneId = _currentObjectParams.get("zoneId");
String vlanId = _currentObjectParams.get("vlanId");
String gateway = _currentObjectParams.get("gateway");
String netmask = _currentObjectParams.get("netmask");
String publicIpRange = _currentObjectParams.get("ipAddressRange");
String vlanType = _currentObjectParams.get("vlanType");
String vlanPodName = _currentObjectParams.get("podName");
String ipError = "Please enter a valid IP address for the field: ";
if (!IPRangeConfig.validOrBlankIP(gateway)) printError(ipError + "gateway");
if (!IPRangeConfig.validOrBlankIP(netmask)) printError(ipError + "netmask");
// Check that the given IP address range was valid
if (!checkIpAddressRange(publicIpRange)) printError("Please enter a valid public IP range.");
// Split the IP address range
String[] ipAddressRangeArray = publicIpRange.split("\\-");
String startIP = ipAddressRangeArray[0];
String endIP = null;
if (ipAddressRangeArray.length > 1) endIP = ipAddressRangeArray[1];
// If a netmask was provided, check that the startIP, endIP, and gateway all belong to the same subnet
if (netmask != null && netmask != "") {
if (endIP != null) {
if (!IPRangeConfig.sameSubnet(startIP, endIP, netmask)) printError("Start and end IPs for the public IP range must be in the same subnet, as per the provided netmask.");
}
if (gateway != null && gateway != "") {
if (!IPRangeConfig.sameSubnet(startIP, gateway, netmask)) printError("The start IP for the public IP range must be in the same subnet as the gateway, as per the provided netmask.");
if (endIP != null) {
if (!IPRangeConfig.sameSubnet(endIP, gateway, netmask)) printError("The end IP for the public IP range must be in the same subnet as the gateway, as per the provided netmask.");
}
}
}
long zoneDbId = Long.parseLong(zoneId);
String zoneName = PodZoneConfig.getZoneName(zoneDbId);
pzc.modifyVlan(zoneName, true, vlanId, gateway, netmask, vlanPodName, vlanType, publicIpRange);
long vlanDbId = pzc.getVlanDbId(zoneName, vlanId);
iprc.saveIPRange("public", -1, zoneDbId, vlanDbId, startIP, endIP);
}
private void savePod() {
long id = Long.parseLong(_currentObjectParams.get("id"));
String name = _currentObjectParams.get("name");
long dataCenterId = Long.parseLong(_currentObjectParams.get("zoneId"));
String privateIpRange = _currentObjectParams.get("ipAddressRange");
String gateway = _currentObjectParams.get("gateway");
String cidr = _currentObjectParams.get("cidr");
String zoneName = PodZoneConfig.getZoneName(dataCenterId);
String startIP = null;
String endIP = null;
String vlanRange = _currentObjectParams.get("vnet");
int vlanStart = -1;
int vlanEnd = -1;
if (vlanRange != null) {
String[] tokens = vlanRange.split("-");
vlanStart = Integer.parseInt(tokens[0]);
vlanEnd = Integer.parseInt(tokens[1]);
}
// Get the individual cidrAddress and cidrSize values
String[] cidrPair = cidr.split("\\/");
String cidrAddress = cidrPair[0];
String cidrSize = cidrPair[1];
long cidrSizeNum = Long.parseLong(cidrSize);
// Check that the gateway is in the same subnet as the CIDR
if (!IPRangeConfig.sameSubnetCIDR(gateway, cidrAddress, cidrSizeNum)) {
printError("For pod " + name + " in zone " + zoneName + " , please ensure that your gateway is in the same subnet as the pod's CIDR address.");
}
pzc.savePod(false, id, name, dataCenterId, gateway, cidr, vlanStart, vlanEnd);
if (privateIpRange != null) {
// Check that the given IP address range was valid
if (!checkIpAddressRange(privateIpRange)) printError("Please enter a valid private IP range.");
String[] ipAddressRangeArray = privateIpRange.split("\\-");
startIP = ipAddressRangeArray[0];
endIP = null;
if (ipAddressRangeArray.length > 1) endIP = ipAddressRangeArray[1];
}
// Check that the start IP and end IP match up with the CIDR
if (!IPRangeConfig.sameSubnetCIDR(startIP, endIP, cidrSizeNum)) {
printError("For pod " + name + " in zone " + zoneName + ", please ensure that your start IP and end IP are in the same subnet, as per the pod's CIDR size.");
}
if (!IPRangeConfig.sameSubnetCIDR(startIP, cidrAddress, cidrSizeNum)) {
printError("For pod " + name + " in zone " + zoneName + ", please ensure that your start IP is in the same subnet as the pod's CIDR address.");
}
if (!IPRangeConfig.sameSubnetCIDR(endIP, cidrAddress, cidrSizeNum)) {
printError("For pod " + name + " in zone " + zoneName + ", please ensure that your end IP is in the same subnet as the pod's CIDR address.");
}
if (privateIpRange != null) {
// Save the IP address range
iprc.saveIPRange("private", id, dataCenterId, -1, startIP, endIP);
}
}
@DB
protected void saveServiceOffering() {
long id = Long.parseLong(_currentObjectParams.get("id"));
String name = _currentObjectParams.get("name");
String displayText = _currentObjectParams.get("displayText");
int cpu = Integer.parseInt(_currentObjectParams.get("cpu"));
int ramSize = Integer.parseInt(_currentObjectParams.get("ramSize"));
int speed = Integer.parseInt(_currentObjectParams.get("speed"));
String useLocalStorageValue = _currentObjectParams.get("useLocalStorage");
String hypervisorType = _currentObjectParams.get("hypervisorType");
// int nwRate = Integer.parseInt(_currentObjectParams.get("nwRate"));
// int mcRate = Integer.parseInt(_currentObjectParams.get("mcRate"));
int nwRate = 200;
int mcRate = 10;
boolean ha = Boolean.parseBoolean(_currentObjectParams.get("enableHA"));
boolean mirroring = Boolean.parseBoolean(_currentObjectParams.get("mirrored"));
String guestIpType = _currentObjectParams.get("guestIpType");
NetworkOffering.GuestIpType type = null;
if (guestIpType == null) {
type = NetworkOffering.GuestIpType.Virtualized;
} else {
type = NetworkOffering.GuestIpType.valueOf(guestIpType);
}
boolean useLocalStorage;
if (useLocalStorageValue != null) {
if (Boolean.parseBoolean(useLocalStorageValue)) {
useLocalStorage = true;
} else {
useLocalStorage = false;
}
} else {
useLocalStorage = false;
}
ServiceOfferingVO serviceOffering = new ServiceOfferingVO(name, cpu, ramSize, speed, nwRate, mcRate, ha, displayText, type, useLocalStorage, false, null, hypervisorType);
ServiceOfferingDaoImpl dao = ComponentLocator.inject(ServiceOfferingDaoImpl.class);
try {
dao.persist(serviceOffering);
} catch (Exception e) {
s_logger.error("error creating service offering", e);
}
/*
String insertSql = "INSERT INTO `cloud`.`service_offering` (id, name, cpu, ram_size, speed, nw_rate, mc_rate, created, ha_enabled, mirrored, display_text, guest_ip_type, use_local_storage) " +
"VALUES (" + id + ",'" + name + "'," + cpu + "," + ramSize + "," + speed + "," + nwRate + "," + mcRate + ",now()," + ha + "," + mirroring + ",'" + displayText + "','" + guestIpType + "','" + useLocalStorage + "')";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
s_logger.error("error creating service offering", ex);
return;
}
*/
}
@DB
protected void saveDiskOffering() {
long id = Long.parseLong(_currentObjectParams.get("id"));
long domainId = Long.parseLong(_currentObjectParams.get("domainId"));
String name = _currentObjectParams.get("name");
String displayText = _currentObjectParams.get("displayText");
int diskSpace = Integer.parseInt(_currentObjectParams.get("diskSpace"));
// boolean mirroring = Boolean.parseBoolean(_currentObjectParams.get("mirrored"));
String tags = _currentObjectParams.get("tags");
String useLocal = _currentObjectParams.get("useLocal");
boolean local = false;
if (useLocal != null) {
local = Boolean.parseBoolean(useLocal);
}
if (tags != null && tags.length() > 0) {
String[] tokens = tags.split(",");
StringBuilder newTags = new StringBuilder();
for (String token : tokens) {
newTags.append(token.trim()).append(",");
}
newTags.delete(newTags.length() - 1, newTags.length());
tags = newTags.toString();
}
DiskOfferingVO diskOffering = new DiskOfferingVO(domainId, name, displayText, diskSpace, tags);
diskOffering.setUseLocalStorage(local);
DiskOfferingDaoImpl offering = ComponentLocator.inject(DiskOfferingDaoImpl.class);
try {
offering.persist(diskOffering);
} catch (Exception e) {
s_logger.error("error creating disk offering", e);
}
/*
String insertSql = "INSERT INTO `cloud`.`disk_offering` (id, domain_id, name, display_text, disk_size, mirrored, tags) " +
"VALUES (" + id + "," + domainId + ",'" + name + "','" + displayText + "'," + diskSpace + "," + mirroring + ", ? )";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.setString(1, tags);
stmt.executeUpdate();
} catch (SQLException ex) {
s_logger.error("error creating disk offering", ex);
return;
}
*/
}
@DB
protected void saveThrottlingRates() {
boolean saveNetworkThrottlingRate = (_networkThrottlingRate != null);
boolean saveMulticastThrottlingRate = (_multicastThrottlingRate != null);
if (!saveNetworkThrottlingRate && !saveMulticastThrottlingRate) return;
String insertNWRateSql = "UPDATE `cloud`.`service_offering` SET `nw_rate` = ?";
String insertMCRateSql = "UPDATE `cloud`.`service_offering` SET `mc_rate` = ?";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt;
if (saveNetworkThrottlingRate) {
stmt = txn.prepareAutoCloseStatement(insertNWRateSql);
stmt.setString(1, _networkThrottlingRate);
stmt.executeUpdate();
}
if (saveMulticastThrottlingRate) {
stmt = txn.prepareAutoCloseStatement(insertMCRateSql);
stmt.setString(1, _multicastThrottlingRate);
stmt.executeUpdate();
}
} catch (SQLException ex) {
s_logger.error("error saving network and multicast throttling rates to all service offerings", ex);
return;
}
}
// no configurable values for VM Template, hard-code the defaults for now
private void saveVMTemplate() {
/*
long id = 1;
String uniqueName = "routing";
String name = "DomR Template";
int isPublic = 0;
String path = "template/private/u000000/os/routing";
String type = "ext3";
int requiresHvm = 0;
int bits = 64;
long createdByUserId = 1;
int isReady = 1;
String insertSql = "INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, path, created, type, hvm, bits, created_by, ready) " +
"VALUES (" + id + ",'" + uniqueName + "','" + name + "'," + isPublic + ",'" + path + "',now(),'" + type + "'," +
requiresHvm + "," + bits + "," + createdByUserId + "," + isReady + ")";
Transaction txn = Transaction.open();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
s_logger.error("error creating vm template: " + ex);
} finally {
txn.close();
}
*/
/*
// do it again for console proxy template
id = 2;
uniqueName = "consoleproxy";
name = "Console Proxy Template";
isPublic = 0;
path = "template/private/u000000/os/consoleproxy";
type = "ext3";
insertSql = "INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, path, created, type, hvm, bits, created_by, ready) " +
"VALUES (" + id + ",'" + uniqueName + "','" + name + "'," + isPublic + ",'" + path + "',now(),'" + type + "'," +
requiresHvm + "," + bits + "," + createdByUserId + "," + isReady + ")";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
s_logger.error("error creating vm template: " + ex);
} finally {
txn.close();
}
*/
}
@DB
protected void saveUser() {
// insert system account
String insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (1, 'system', '1', '1')";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
s_logger.error("error creating system account", ex);
}
// insert system user
insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) VALUES (1, 'system', '', 1, 'system', 'cloud', now())";
txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
s_logger.error("error creating system user", ex);
}
// insert admin user
long id = Long.parseLong(_currentObjectParams.get("id"));
String username = _currentObjectParams.get("username");
String firstname = _currentObjectParams.get("firstname");
String lastname = _currentObjectParams.get("lastname");
String password = _currentObjectParams.get("password");
String email = _currentObjectParams.get("email");
if (email == null || email.equals("")) printError("An email address for each user is required.");
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
s_logger.error("error saving user", e);
return;
}
md5.reset();
BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes()));
String pwStr = pwInt.toString(16);
int padding = 32 - pwStr.length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < padding; i++) {
sb.append('0'); // make sure the MD5 password is 32 digits long
}
sb.append(pwStr);
// create an account for the admin user first
insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (" + id + ", '" + username + "', '1', '1')";
txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
s_logger.error("error creating account", ex);
}
// now insert the user
insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, email, created) " +
"VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "','" + email + "',now())";
txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
s_logger.error("error creating user", ex);
}
}
private void saveDefaultConfiguations() {
for (String name : s_defaultConfigurationValues.keySet()) {
String value = s_defaultConfigurationValues.get(name);
saveConfiguration(name, value, null);
}
}
private void saveConfiguration() {
String name = _currentObjectParams.get("name");
String value = _currentObjectParams.get("value");
String category = _currentObjectParams.get("category");
saveConfiguration(name, value, category);
}
@DB
protected void saveConfiguration(String name, String value, String category) {
String instance = "DEFAULT";
String description = s_configurationDescriptions.get(name);
String component = s_configurationComponents.get(name);
if (category == null) {
category = "Advanced";
}
String instanceNameError = "Please enter a non-blank value for the field: ";
if (name.equals("instance.name")) {
if (value == null || value.isEmpty() || !value.matches("^[A-Za-z0-9]{1,8}$"))
printError(instanceNameError + "configuration: instance.name can not be empty and can only contain numbers and alphabets up to 8 characters long");
}
if (name.equals("network.throttling.rate")) {
if (value != null && !value.isEmpty()) _networkThrottlingRate = value;
}
if (name.equals("multicast.throttling.rate")) {
if (value != null && !value.isEmpty()) _multicastThrottlingRate = value;
}
String insertSql = "INSERT INTO `cloud`.`configuration` (instance, component, name, value, description, category) " +
"VALUES ('" + instance + "','" + component + "','" + name + "','" + value + "','" + description + "','" + category + "')";
String selectSql = "SELECT name FROM cloud.configuration WHERE name = '" + name + "'";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql);
ResultSet result = stmt.executeQuery();
Boolean hasRow = result.next();
if (!hasRow) {
stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
}
} catch (SQLException ex) {
s_logger.error("error creating configuration", ex);
}
}
private boolean checkIpAddressRange(String ipAddressRange) {
String[] ipAddressRangeArray = ipAddressRange.split("\\-");
String startIP = ipAddressRangeArray[0];
String endIP = null;
if (ipAddressRangeArray.length > 1) endIP = ipAddressRangeArray[1];
if (!IPRangeConfig.validIP(startIP)) {
s_logger.error("The private IP address: " + startIP + " is invalid.");
return false;
}
if (!IPRangeConfig.validOrBlankIP(endIP)) {
s_logger.error("The private IP address: " + endIP + " is invalid.");
return false;
}
if (!IPRangeConfig.validIPRange(startIP, endIP)) {
s_logger.error("The IP range " + startIP + " -> " + endIP + " is invalid.");
return false;
}
return true;
}
@DB
protected void saveRootDomain() {
String insertSql = "insert into `cloud`.`domain` (id, name, parent, owner, path, level) values (1, 'ROOT', NULL, 2, '/', 0)";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
s_logger.error("error creating ROOT domain", ex);
}
/*
String updateSql = "update account set domain_id = 1 where id = 2";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareStatement(updateSql);
stmt.executeUpdate();
} catch (SQLException ex) {
s_logger.error("error updating admin user", ex);
} finally {
txn.close();
}
updateSql = "update account set domain_id = 1 where id = 1";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareStatement(updateSql);
stmt.executeUpdate();
} catch (SQLException ex) {
s_logger.error("error updating system user", ex);
} finally {
txn.close();
}
*/
}
class DbConfigXMLHandler extends DefaultHandler {
private DatabaseConfig _parent = null;
public void setParent(DatabaseConfig parent) {
_parent = parent;
}
@Override
public void endElement(String s, String s1, String s2)
throws SAXException {
if (DatabaseConfig.objectNames.contains(s2) || "object".equals(s2)) {
_parent.saveCurrentObject();
} else if (DatabaseConfig.fieldNames.contains(s2) || "field".equals(s2)) {
_currentFieldName = null;
}
}
@Override
public void startElement(String s, String s1, String s2,
Attributes attributes) throws SAXException {
if ("object".equals(s2)) {
_parent.setCurrentObjectName(convertName(attributes.getValue("name")));
} else if ("field".equals(s2)) {
if (_currentObjectParams == null) {
_currentObjectParams = new HashMap<String, String>();
}
_currentFieldName = convertName(attributes.getValue("name"));
} else if (DatabaseConfig.objectNames.contains(s2)) {
_parent.setCurrentObjectName(s2);
} else if (DatabaseConfig.fieldNames.contains(s2)) {
if (_currentObjectParams == null) {
_currentObjectParams = new HashMap<String, String>();
}
_currentFieldName = s2;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if ((_currentObjectParams != null) && (_currentFieldName != null)) {
String currentFieldVal = new String(ch, start, length);
_currentObjectParams.put(_currentFieldName, currentFieldVal);
}
}
private String convertName(String name) {
if (name.contains(".")){
String[] nameArray = name.split("\\.");
for (int i = 1; i < nameArray.length; i++) {
String word = nameArray[i];
nameArray[i] = word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
}
name = "";
for (int i = 0; i < nameArray.length; i++) {
name = name.concat(nameArray[i]);
}
}
return name;
}
}
public static List<String> genReturnList(String success, String message) {
List<String> returnList = new ArrayList<String>(2);
returnList.add(0, success);
returnList.add(1, message);
return returnList;
}
public static void printError(String message) {
System.out.println(message);
System.exit(1);
}
public static String getDatabaseValueString(String selectSql, String name, String errorMsg) {
Transaction txn = Transaction.open("getDatabaseValueString");
PreparedStatement stmt = null;
try {
stmt = txn.prepareAutoCloseStatement(selectSql);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
String value = rs.getString(name);
return value;
}
else return null;
} catch (SQLException e) {
System.out.println("Exception: " + e.getMessage());
printError(errorMsg);
} finally {
txn.close();
}
return null;
}
public static long getDatabaseValueLong(String selectSql, String name, String errorMsg) {
Transaction txn = Transaction.open("getDatabaseValueLong");
PreparedStatement stmt = null;
try {
stmt = txn.prepareAutoCloseStatement(selectSql);
ResultSet rs = stmt.executeQuery();
if (rs.next()) return rs.getLong(name);
else return -1;
} catch (SQLException e) {
System.out.println("Exception: " + e.getMessage());
printError(errorMsg);
} finally {
txn.close();
}
return -1;
}
public static void saveSQL(String sql, String errorMsg) {
Transaction txn = Transaction.open("saveSQL");
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(sql);
stmt.executeUpdate();
} catch (SQLException ex) {
System.out.println("SQL Exception: " + ex.getMessage());
printError(errorMsg);
} finally {
txn.close();
}
}
}
|
// Location.java
package loci.common;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
public class Location {
// -- Static fields --
/** Map from given filenames to actual filenames. */
private static HashMap<String, Object> idMap = new HashMap<String, Object>();
// -- Fields --
private boolean isURL = true;
private URL url;
private File file;
// -- Constructors --
public Location(String pathname) {
try {
url = new URL(getMappedId(pathname));
}
catch (MalformedURLException e) {
isURL = false;
}
if (!isURL) file = new File(getMappedId(pathname));
}
public Location(File file) {
isURL = false;
this.file = file;
}
public Location(String parent, String child) {
this(parent + "/" + child);
}
public Location(Location parent, String child) {
this(parent.getAbsolutePath(), child);
}
// -- Location API methods --
/**
* Maps the given id to the actual filename on disk. Typically actual
* filenames are used for ids, making this step unnecessary, but in some
* cases it is useful; e.g., if the file has been renamed to conform to a
* standard naming scheme and the original file extension is lost, then
* using the original filename as the id assists format handlers with type
* identification and pattern matching, and the id can be mapped to the
* actual filename for reading the file's contents.
* @see #getMappedId(String)
*/
public static void mapId(String id, String filename) {
if (id == null) return;
if (filename == null) idMap.remove(id);
else idMap.put(id, filename);
LogTools.debug("Location.mapId: " + id + " -> " + filename);
}
/** Maps the given id to the given random access handle. */
public static void mapFile(String id, IRandomAccess ira) {
if (id == null) return;
if (ira == null) idMap.remove(id);
else idMap.put(id, ira);
LogTools.debug("Location.mapFile: " + id + " -> " + ira);
}
/**
* Gets the actual filename on disk for the given id. Typically the id itself
* is the filename, but in some cases may not be; e.g., if OMEIS has renamed
* a file from its original name to a standard location such as Files/101,
* the original filename is useful for checking the file extension and doing
* pattern matching, but the renamed filename is required to read its
* contents.
* @see #mapId(String, String)
*/
public static String getMappedId(String id) {
if (idMap == null) return id;
String filename = null;
if (id != null && (idMap.get(id) instanceof String)) {
filename = (String) idMap.get(id);
}
return filename == null ? id : filename;
}
/** Gets the random access handle for the given id. */
public static IRandomAccess getMappedFile(String id) {
if (idMap == null) return null;
IRandomAccess ira = null;
if (id != null && (idMap.get(id) instanceof IRandomAccess)) {
ira = (IRandomAccess) idMap.get(id);
}
return ira;
}
public static HashMap<String, Object> getIdMap() { return idMap; }
public static void setIdMap(HashMap<String, Object> map) {
if (map == null) throw new IllegalArgumentException("map cannot be null");
idMap = map;
}
/**
* Gets an IRandomAccess object that can read from the given file.
* @see IRandomAccess
*/
public static IRandomAccess getHandle(String id) throws IOException {
return getHandle(id, false);
}
/**
* Gets an IRandomAccess object that can read from or write to the given file.
* @see IRandomAccess
*/
public static IRandomAccess getHandle(String id, boolean writable)
throws IOException
{
IRandomAccess handle = getMappedFile(id);
if (handle == null) {
String mapId = getMappedId(id);
File f = new File(mapId).getAbsoluteFile();
if (id.startsWith("http:
handle = new URLHandle(mapId, writable ? "w" : "r");
}
else if (ZipHandle.isZipFile(id)) {
handle = new ZipHandle(mapId);
}
else if (GZipHandle.isGZipFile(id)) {
handle = new GZipHandle(mapId);
}
else if (BZip2Handle.isBZip2File(id)) {
handle = new BZip2Handle(mapId);
}
else {
handle = new FileHandle(f, writable ? "rw" : "r");
}
}
LogTools.debug("Location.getHandle: " + id + " -> " + handle);
return handle;
}
/**
* Return a list of all of the files in this directory. If 'noDotFiles' is
* set to true, then file names beginning with '.' are omitted.
*
* @see java.io.File#list()
*/
public String[] list(boolean noDotFiles) {
ArrayList<String> files = new ArrayList<String>();
if (isURL) {
if (!isDirectory()) return null;
try {
URLConnection c = url.openConnection();
InputStream is = c.getInputStream();
boolean foundEnd = false;
while (!foundEnd) {
byte[] b = new byte[is.available()];
is.read(b);
String s = new String(b);
if (s.toLowerCase().indexOf("</html>") != -1) foundEnd = true;
while (s.indexOf("a href") != -1) {
int ndx = s.indexOf("a href") + 8;
String f = s.substring(ndx, s.indexOf("\"", ndx));
s = s.substring(s.indexOf("\"", ndx) + 1);
Location check = new Location(getAbsolutePath(), f);
if (check.exists() && (!noDotFiles || !f.startsWith("."))) {
files.add(check.getName());
}
}
}
}
catch (IOException e) {
return null;
}
}
String[] f = file.list();
if (f == null) return null;
for (String file : f) {
if (!noDotFiles || !file.startsWith(".")) files.add(file);
}
return files.toArray(new String[files.size()]);
}
// -- File API methods --
/* @see java.io.File#canRead() */
public boolean canRead() {
return isURL ? true : file.canRead();
}
/* @see java.io.File#canWrite() */
public boolean canWrite() {
return isURL ? false : file.canWrite();
}
/* @see java.io.File#createNewFile() */
public boolean createNewFile() throws IOException {
if (isURL) throw new IOException("Unimplemented");
return file.createNewFile();
}
/* @see java.io.File#delete() */
public boolean delete() {
return isURL ? false : file.delete();
}
/* @see java.io.File#deleteOnExit() */
public void deleteOnExit() {
if (!isURL) file.deleteOnExit();
}
/* @see java.io.File#equals(Object) */
public boolean equals(Object obj) {
return isURL ? url.equals(obj) : file.equals(obj);
}
/* @see java.io.File#exists() */
public boolean exists() {
if (isURL) {
try {
url.getContent();
return true;
}
catch (IOException e) {
return false;
}
}
return file.exists();
}
/* @see java.io.File#getAbsoluteFile() */
public Location getAbsoluteFile() {
return new Location(getAbsolutePath());
}
/* @see java.io.File#getAbsolutePath() */
public String getAbsolutePath() {
return isURL ? url.toExternalForm() : file.getAbsolutePath();
}
/* @see java.io.File#getCanonicalFile() */
public Location getCanonicalFile() throws IOException {
return getAbsoluteFile();
}
/* @see java.io.File#getCanonicalPath() */
public String getCanonicalPath() throws IOException {
return isURL ? getAbsolutePath() : file.getCanonicalPath();
}
/* @see java.io.File#getName() */
public String getName() {
if (isURL) {
String name = url.getFile();
name = name.substring(name.lastIndexOf("/") + 1);
return name;
}
return file.getName();
}
/* @see java.io.File#getParent() */
public String getParent() {
if (isURL) {
String absPath = getAbsolutePath();
absPath = absPath.substring(0, absPath.lastIndexOf("/"));
return absPath;
}
return file.getParent();
}
/* @see java.io.File#getParentFile() */
public Location getParentFile() {
return new Location(getParent());
}
/* @see java.io.File#getPath() */
public String getPath() {
return isURL ? url.getHost() + url.getPath() : file.getPath();
}
/* @see java.io.File#isAbsolute() */
public boolean isAbsolute() {
return isURL ? true : file.isAbsolute();
}
/* @see java.io.File#isDirectory() */
public boolean isDirectory() {
return isURL ? lastModified() == 0 : file.isDirectory();
}
/* @see java.io.File#isFile() */
public boolean isFile() {
return isURL ? lastModified() > 0 : file.isFile();
}
/* @see java.io.File#isHidden() */
public boolean isHidden() {
return isURL ? false : file.isHidden();
}
/* @see java.io.File#lastModified() */
public long lastModified() {
if (isURL) {
try {
return url.openConnection().getLastModified();
}
catch (IOException e) { return 0; }
}
return file.lastModified();
}
/* @see java.io.File#length() */
public long length() {
if (isURL) {
try {
return url.openConnection().getContentLength();
}
catch (IOException e) { return 0; }
}
return file.length();
}
/* @see java.io.File#list() */
public String[] list() {
return list(false);
}
/* @see java.io.File#listFiles() */
public Location[] listFiles() {
String[] s = list();
if (s == null) return null;
Location[] f = new Location[s.length];
for (int i=0; i<f.length; i++) {
f[i] = new Location(getAbsolutePath(), s[i]);
f[i] = f[i].getAbsoluteFile();
}
return f;
}
/* @see java.io.File#toURL() */
public URL toURL() throws MalformedURLException {
return isURL ? url : file.toURI().toURL();
}
// -- Object API methods --
/* @see java.lang.Object#toString() */
public String toString() {
return isURL ? url.toString() : file.toString();
}
}
|
package com.untamedears.JukeAlert.storage;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import org.bukkit.Location;
import org.bukkit.Material;
import com.untamedears.JukeAlert.model.LoggedAction;
import com.untamedears.JukeAlert.model.Snitch;
public class JukeInfoBatch {
// Parent class
public JukeAlertLogger JAL;
// Max queue size before auto flush
public final int max_batch_size = 100;
// Current queue size
public int batch_current = 0;
public JukeInfoBatch(JukeAlertLogger _jal) {
this.JAL=_jal;
}
// Current working set is stored here
private PreparedStatement currentSet = null;
// Add a set of data
public void addSet(Snitch snitch, Material material, Location loc, Date date, LoggedAction action, String initiatedUser, String victimUser) {
// Check if starting a new batch
if(this.currentSet==null) {
this.currentSet = this.JAL.getNewInsertSnitchLogStmt();
}
// Add params
try {
currentSet.setInt(1, snitch.getId());
currentSet.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()));
currentSet.setByte(3, (byte) action.getLoggedActionId());
currentSet.setString(4, initiatedUser);
if (victimUser != null) {
currentSet.setString(5, victimUser);
} else {
currentSet.setNull(5, java.sql.Types.VARCHAR);
}
if (loc != null) {
currentSet.setInt(6, loc.getBlockX());
currentSet.setInt(7, loc.getBlockY());
currentSet.setInt(8, loc.getBlockZ());
} else {
currentSet.setNull(6, java.sql.Types.INTEGER);
currentSet.setNull(7, java.sql.Types.INTEGER);
currentSet.setNull(8, java.sql.Types.INTEGER);
}
if (material != null) {
currentSet.setShort(9, (short) material.getId());
} else {
currentSet.setNull(9, java.sql.Types.SMALLINT);
}
currentSet.addBatch();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// If we're above the limit, execute all inserts
if(++batch_current >= this.max_batch_size) {
this.flush();
}
}
public void flush() {
PreparedStatement executeMe = this.currentSet;
this.currentSet=null;
batch_current=0;
if(executeMe) {
try {
executeMe.executeBatch();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
package com.blabbertabber.blabbertabber;
import junit.framework.TestCase;
public class MainActivityTest extends TestCase {
public void setUp() throws Exception {
super.setUp();
}
public void tearDown() throws Exception {
}
public void testOnCreate() throws Exception {
throw new Exception("Holy cow!!! What went wrong here?");
}
public void testOnCreateOptionsMenu() throws Exception {
}
public void testOnOptionsItemSelected() throws Exception {
}
}
|
package org.concord.otrunk.user;
import java.util.Hashtable;
import org.concord.framework.otrunk.OTID;
import org.concord.otrunk.datamodel.OTDataCollection;
import org.concord.otrunk.datamodel.OTDataList;
import org.concord.otrunk.datamodel.OTDataMap;
import org.concord.otrunk.datamodel.OTDataObject;
import org.concord.otrunk.datamodel.OTDataObjectType;
import org.concord.otrunk.datamodel.OTDatabase;
import org.concord.otrunk.datamodel.OTObjectRevision;
import org.concord.otrunk.datamodel.OTRelativeID;
/**
* OTUserDataObject
* Class name and description
*
* Date created: Aug 24, 2004
*
* @author scott<p>
*
*/
public class OTUserDataObject
implements OTDataObject
{
private OTDataObject authoringObject;
private OTDataObject stateObject = null;
private OTTemplateDatabase database;
private Hashtable resourceCollections = new Hashtable();
public OTUserDataObject(OTDataObject authoringObject,
OTTemplateDatabase db)
{
this.authoringObject = authoringObject;
database = db;
}
public OTDatabase getDatabase()
{
return database;
}
public OTDataObject getAuthoringObject()
{
return authoringObject;
}
public void setStateObject(OTDataObject stateObject)
{
this.stateObject = stateObject;
}
public OTDataObject getExistingUserObject()
{
if(stateObject != null) {
return stateObject;
} else {
// I don't know if I should do this but it should speed things
stateObject = database.getStateObject(authoringObject);
return stateObject;
}
}
/* (non-Javadoc)
* @see org.concord.otrunk.OTDataObject#getGlobalId()
*/
public OTID getGlobalId()
{
OTID dbId = database.getDatabaseId();
// The object can represent two types of data objects
// it is either a bridge between an authored object (template object)
// and the user modifications to that object object
// or it is a wrapper around a user created object
OTID otherId = null;
if(authoringObject != null) {
otherId = authoringObject.getGlobalId();
} else {
otherId = stateObject.getGlobalId();
}
return new OTRelativeID(dbId, otherId);
}
/* (non-Javadoc)
* @see org.concord.otrunk.OTDataObject#getCurrentRevision()
*/
public OTObjectRevision getCurrentRevision()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.concord.otrunk.OTDataObject#getResource(java.lang.String)
*/
public Object getResource(String key)
{
// first look in the userObject
// then look in the authoringObject
Object value = null;
OTDataObject userObject = getExistingUserObject();
if (userObject != null) {
value = userObject.getResource(key);
if(value != null) {
return value;
}
}
if(authoringObject == null) {
return null;
}
return authoringObject.getResource(key);
}
/* (non-Javadoc)
* @see org.concord.otrunk.OTDataObject#getResourceKeys()
*/
public String[] getResourceKeys()
{
// if this is called then it isn't clear what to do, I guess
// some combination of the two objects.
// it is needed to implement generic object copying
// if we had access to the objects data description we could use
// that in this case, but assuming we don't have that
// we need to go through all the keys of the userobject and
// all the keys of the author object and combine them, an easy
// way is to use a hashtable
Hashtable keyTable = new Hashtable();
OTDataObject userObject = getExistingUserObject();
if (userObject != null) {
String [] userKeys = userObject.getResourceKeys();
for(int i=0; i<userKeys.length; i++){
// we can put any object, but lets use the userObject
// so we might take advantage of that later
keyTable.put(userKeys[i], userObject);
}
}
if(authoringObject != null) {
String [] authorKeys = authoringObject.getResourceKeys();
for(int i=0; i<authorKeys.length; i++){
Object oldValue = keyTable.get(authorKeys[i]);
if(oldValue == null){
keyTable.put(authorKeys[i], authoringObject);
}
}
}
Object [] keys = keyTable.keySet().toArray();
String [] strKeys = new String [keys.length];
System.arraycopy(keys, 0, strKeys, 0, keys.length);
return strKeys;
}
public OTDataObject getUserObject()
{
OTDataObject userObject = getExistingUserObject();
if(userObject == null) {
userObject = database.createStateObject(authoringObject);
System.err.println("created userStateObject: " + userObject.getGlobalId());
}
return userObject;
}
/* (non-Javadoc)
* @see org.concord.otrunk.OTDataObject#setResource(java.lang.String, java.lang.Object)
*/
public boolean setResource(String key, Object resource)
{
Object oldObject = getResource(key);
if(oldObject != null &&
oldObject.equals(resource)){
return false;
}
// Need to check if the object being passed in
// is a user version of an authored object
// and that user version has not changed
// The only way to do this now is to get the OTDataObject
// from our database for the old object, and then get
// its id. This call will be wasteful if a new object
// is being set to replace the old object without ever
// accessing the old object.
if(oldObject instanceof OTID){
try {
OTDataObject oldDataObject =
database.getOTDataObject(this, (OTID)oldObject);
if(oldDataObject.getGlobalId().equals(resource)){
return false;
}
} catch (Exception e){
e.printStackTrace();
}
}
// special hack for -0.0 and 0.0
// see the docs for Float.equals()
if(oldObject instanceof Float &&
resource instanceof Float) {
if(((Float)oldObject).floatValue() ==
((Float)resource).floatValue()){
return false;
}
}
// get the existing user object or create a new one
OTDataObject userObject = getUserObject();
resource = resolveIDResource(resource);
userObject.setResource(key, resource);
return true;
}
/**
* This method is to handle the case where a resource is an
* id. Some of the passed in ids will be from our template
* database. So they are really just temporary ids. These ids are
* relative ids, where the root is the id of the template db and
* the relative part is the id of the original object
*
* We want to store the id of the original object. So this method
* should be called on any resource that could be an id.
*
* If this isn't working properly then an id will be stored that
* doesn't exist.
*
* @param resource
* @return
*/
public Object resolveIDResource(Object resource)
{
if(resource instanceof OTRelativeID) {
OTRelativeID relID = (OTRelativeID)resource;
if(database.getDatabaseId().equals(relID.getRootId())) {
// This is an id that came from our database
// so get the relative part of the id which is
// either an id in the
// authored database or an id of a brand new object in
// the user database
return relID.getRelativeId();
}
}
return resource;
}
public OTDataCollection getResourceCollection(String key,
Class collectionClass)
{
OTDataCollection collection =
(OTDataCollection)resourceCollections.get(key);
if(collection != null) {
return collection;
}
// This might need to be getResourceCollection instead of
// getResource. But I wanted to know if the list has been
// set yet.
Object resourceObj = null;
if(authoringObject != null) {
resourceObj = authoringObject.getResource(key);
}
// Here is the tricky part. We want to make a pseudo
// list so that the real list isn't created unless it is really
// used.
if(collectionClass.equals(OTDataList.class)) {
collection =
new OTUserDataList(this, (OTDataList)resourceObj, key);
} else if(collectionClass.equals(OTDataMap.class)) {
collection =
new OTUserDataMap(this, (OTDataMap)resourceObj, key);
}
resourceCollections.put(key, collection);
return collection;
}
public OTDataObjectType getType()
{
// first look in the userObject
// then look in the authoringObject
OTDataObject userObject = getExistingUserObject();
if (userObject != null) {
return userObject.getType();
}
if(authoringObject == null) {
throw new IllegalStateException("Can't have a null userObject and null authoringObject");
}
return authoringObject.getType();
}
}
|
package imcode.server.parser ;
import java.util.LinkedList ;
import java.util.Properties ;
import org.apache.oro.text.regex.* ;
public class NodeList extends LinkedList {
final static String CVS_REV = "$Revision$" ;
final static String CVS_DATE = "$Date$" ;
private static Pattern ELEMENT_PATTERN ;
private static Pattern ATTRIBUTES_PATTERN ;
static {
try {
Perl5Compiler patternCompiler = new Perl5Compiler() ;
ELEMENT_PATTERN = patternCompiler.compile("<\\?imcms:([-\\w]+)(.*?)\\s*\\?>(.*?)<\\?\\/imcms:\\1\\?>", Perl5Compiler.SINGLELINE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
ATTRIBUTES_PATTERN = patternCompiler.compile("\\s+(\\w+)\\s*=\\s*([\"'])(.*?)\\2", Perl5Compiler.READ_ONLY_MASK) ;
} catch (MalformedPatternException ignored) {
// I ignore the exception because i know that these patterns work, and that the exception will never be thrown.
}
}
/** Parse a String of data into nodes. **/
public NodeList(String data) {
PatternMatcher patternMatcher = new Perl5Matcher() ;
PatternMatcherInput input = new PatternMatcherInput(data) ;
int lastEndOffset = 0 ;
while (patternMatcher.contains(input,ELEMENT_PATTERN)) {
MatchResult matchResult = patternMatcher.getMatch() ;
if (matchResult.beginOffset(0) > lastEndOffset) { // If the part before the first child element has a length longer than 0...
add( new SimpleText( data.substring( lastEndOffset,matchResult.beginOffset(0) ) ) ) ; // ... put it in a text node.
}
lastEndOffset = matchResult.endOffset(0) ;
add( createElementNode( patternMatcher ) ) ;
}
if (data.length() > lastEndOffset) { // Add whatever was left after the last element, no matter if there were any elements.
add( new SimpleText( data.substring(lastEndOffset) ) ) ;
}
}
private Element createElementNode( PatternMatcher patternMatcher ) {
MatchResult matchResult = patternMatcher.getMatch() ;
String name = matchResult.group(1) ;
String attributes_string = matchResult.group(2) ;
String content = matchResult.group(3) ;
return new SimpleElement(name, createAttributes(attributes_string, patternMatcher), new NodeList(content)) ;
}
Properties createAttributes(String attributes_string, PatternMatcher patternMatcher) {
Properties attributes = new Properties();
PatternMatcherInput attributes_input = new PatternMatcherInput(attributes_string) ;
while(patternMatcher.contains(attributes_input,ATTRIBUTES_PATTERN)) {
MatchResult attribute_matres = patternMatcher.getMatch() ;
attributes.setProperty(attribute_matres.group(1), attribute_matres.group(3)) ;
}
return attributes ;
}
}
|
package com.daksh.tmdbsample.movielist;
import android.support.annotation.NonNull;
import com.daksh.tmdbsample.base.BasePresenter;
import com.daksh.tmdbsample.base.BaseView;
import com.daksh.tmdbsample.data.model.Movie;
import java.util.List;
public interface MovieListContract {
interface View extends BaseView<Presenter> {
void showLoading();
void showError();
void showMovies(List<Movie> movies);
void addMovies(List<Movie> movies);
void showSortOrderSelector(int currentSortOrder);
}
interface Presenter extends BasePresenter {
void loadMovies(Integer page);
void openMovieDetails(@NonNull Movie movie);
void setSortOrder(int sortOrder);
}
}
|
package org.jdesktop.swingx.calendar;
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.TimeZone;
import javax.swing.*;
import javax.swing.border.Border;
/**
* Component that displays a month calendar which can be used to select a day
* or range of days. By default the <code>JXMonthView</code> will display a
* single calendar using the current month and year, using
* <code>Calendar.SUNDAY</code> as the first day of the week.
* <p>
* The <code>JXMonthView</code> can be configured to display more than one
* calendar at a time by calling
* <code>setPreferredCalCols</code>/<code>setPreferredCalRows</code>. These
* methods will set the preferred number of calendars to use in each
* column/row. As these values change, the <code>Dimension</code> returned
* from <code>getMinimumSize</code> and <code>getPreferredSize</code> will
* be updated. The following example shows how to create a 2x2 view which is
* contained within a <code>JFrame</code>:
* <pre>
* JXMonthView monthView = new JXMonthView();
* monthView.setPreferredCols(2);
* monthView.setPreferredRows(2);
*
* JFrame frame = new JFrame();
* frame.getContentPane().add(monthView);
* frame.pack();
* frame.setVisible(true);
* </pre>
* <p>
* <code>JXMonthView</code> can be further configured to allow any day of the
* week to be considered the first day of the week. Character
* representation of those days may also be set by providing an array of
* strings.
* <pre>
* monthView.setFirstDayOfWeek(Calendar.MONDAY);
* monthView.setDaysOfTheWeek(
* new String[]{"S", "M", "T", "W", "Th", "F", "S"});
* </pre>
* <p>
* This component supports flagging days. These flagged days, which must be
* provided in sorted order, are displayed in a bold font. This can be used to
* inform the user of such things as scheduled appointment.
* <pre>
* // Create some dates that we want to flag as being important.
* Calendar cal1 = Calendar.getInstance();
* cal1.set(2004, 1, 1);
* Calendar cal2 = Calendar.getInstance();
* cal2.set(2004, 1, 5);
*
* long[] flaggedDates = new long[] {
* cal1.getTimeInMillis(),
* cal2.getTimeInMillis(),
* System.currentTimeMillis()
* };
*
* // Sort them in ascending order.
* java.util.Arrays.sort(flaggedDates);
* monthView.setFlaggedDates(flaggedDates);
* </pre>
* Applications may have the need to allow users to select different ranges of
* dates. There are four modes of selection that are supported, single,
* multiple, week and no selection. Once a selection is made an action is
* fired, with exception of the no selection mode, to inform listeners that
* selection has changed.
* <pre>
* // Change the selection mode to select full weeks.
* monthView.setSelectionMode(JXMonthView.WEEK_SELECTION);
*
* // Add an action listener that will be notified when the user
* // changes selection via the mouse.
* monthView.addActionListener(new ActionListener() {
* public void actionPerformed(ActionEvent e) {
* System.out.println(
* ((JXMonthView)e.getSource()).getSelectedDateSpan());
* }
* });
* </pre>
*
* @author Joshua Outwater
* @version $Revision$
*/
public class JXMonthView extends JComponent {
/** Mode that disallows selection of days from the calendar. */
public static final int NO_SELECTION = 0;
/** Mode that allows for selection of a single day. */
public static final int SINGLE_SELECTION = 1;
/** Mode that allows for selecting of multiple consecutive days. */
public static final int MULTIPLE_SELECTION = 2;
/**
* Mode where selections consisting of more than 7 days will
* snap to a full week.
*/
public static final int WEEK_SELECTION = 3;
/** Return value used to identify when the month down button is pressed. */
public static final int MONTH_DOWN = 1;
/** Return value used to identify when the month up button is pressed. */
public static final int MONTH_UP = 2;
/**
* Insets used in determining the rectangle for the month string
* background.
*/
protected Insets _monthStringInsets = new Insets(0,0,0,0);
private static final int MONTH_DROP_SHADOW = 1;
private static final int MONTH_LINE_DROP_SHADOW = 2;
private static final int WEEK_DROP_SHADOW = 4;
private int _boxPaddingX = 3;
private int _boxPaddingY = 3;
private int _arrowPaddingX = 3;
private int _arrowPaddingY = 3;
private static final int CALENDAR_SPACING = 10;
private static final int DAYS_IN_WEEK = 7;
private static final int MONTHS_IN_YEAR = 12;
/**
* Keeps track of the first date we are displaying. We use this as a
* restore point for the calendar.
*/
private long _firstDisplayedDate;
private int _firstDisplayedMonth;
private int _firstDisplayedYear;
private long _lastDisplayedDate;
private Font _derivedFont;
/** Beginning date of selection. -1 if no date is selected. */
private long _startSelectedDate = -1;
/** End date of selection. -1 if no date is selected. */
private long _endSelectedDate = -1;
/** For multiple selection we need to record the date we pivot around. */
private long _pivotDate = -1;
/** The number of calendars able to be displayed horizontally. */
private int _numCalCols = 1;
/** The number of calendars able to be displayed vertically. */
private int _numCalRows = 1;
private int _minCalCols = 1;
private int _minCalRows = 1;
private long _today;
private long[] _flaggedDates;
private int _selectionMode = SINGLE_SELECTION;
private int _boxHeight;
private int _boxWidth;
private int _monthBoxHeight;
private int _calendarWidth;
private int _calendarHeight;
private int _firstDayOfWeek = Calendar.SUNDAY;
private int _startX;
private int _startY;
private int _dropShadowMask = 0;
private boolean _dirty = false;
private boolean _antiAlias = false;
private boolean _ltr;
private boolean _traversable = false;
private boolean _asKirkWouldSay_FIRE = false;
private Calendar _cal;
private String[] _daysOfTheWeek;
private static String[] _monthsOfTheYear;
private Dimension _dim = new Dimension();
private Rectangle _bounds = new Rectangle();
private Rectangle _dirtyRect = new Rectangle();
private Color _todayBackgroundColor;
private Color _monthStringBackground;
private Color _monthStringForeground;
private Color _daysOfTheWeekForeground;
private Color _selectedBackground;
private SimpleDateFormat _dayOfMonthFormatter = new SimpleDateFormat("d");
private String _actionCommand = "selectionChanged";
private Timer _todayTimer = null;
private ImageIcon _monthDownImage;
private ImageIcon _monthUpImage;
private Hashtable _dayToColorTable = new Hashtable<Integer, Color>();
/**
* Create a new instance of the <code>JXMonthView</code> class using the
* month and year of the current day as the first date to display.
*/
public JXMonthView() {
this(new Date().getTime());
}
/**
* Create a new instance of the <code>JXMonthView</code> class using the
* month and year from <code>initialTime</code> as the first date to
* display.
*
* @param initialTime The first month to display.
*/
public JXMonthView(long initialTime) {
super();
_ltr = getComponentOrientation().isLeftToRight();
// Set up calendar instance.
_cal = Calendar.getInstance(getLocale());
_cal.setFirstDayOfWeek(_firstDayOfWeek);
_cal.setMinimalDaysInFirstWeek(1);
// Keep track of today.
_cal.set(Calendar.HOUR_OF_DAY, 0);
_cal.set(Calendar.MINUTE, 0);
_cal.set(Calendar.SECOND, 0);
_cal.set(Calendar.MILLISECOND, 0);
_today = _cal.getTimeInMillis();
_cal.setTimeInMillis(initialTime);
setFirstDisplayedDate(_cal.getTimeInMillis());
// Get string representation of the months of the year.
_monthsOfTheYear = new DateFormatSymbols().getMonths();
setOpaque(true);
setBackground(Color.WHITE);
setFocusable(true);
_todayBackgroundColor = getForeground();
// Restore original time value.
_cal.setTimeInMillis(_firstDisplayedDate);
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
// Setup the keyboard handler.
InputMap inputMap = getInputMap(JComponent.WHEN_FOCUSED);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "selectPreviousDay");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "selectNextDay");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "selectDayInPreviousWeek");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "selectDayInNextWeek");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.SHIFT_MASK, false), "addPreviousDay");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.SHIFT_MASK, false), "addNextDay");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.SHIFT_MASK, false), "addToPreviousWeek");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.SHIFT_MASK, false), "addToNextWeek");
ActionMap actionMap = getActionMap();
actionMap.put("selectPreviousDay", new KeyboardAction(KeyboardAction.SELECT_PREVIOUS_DAY));
actionMap.put("selectNextDay", new KeyboardAction(KeyboardAction.SELECT_NEXT_DAY));
actionMap.put("selectDayInPreviousWeek", new KeyboardAction(KeyboardAction.SELECT_DAY_PREVIOUS_WEEK));
actionMap.put("selectDayInNextWeek", new KeyboardAction(KeyboardAction.SELECT_DAY_NEXT_WEEK));
actionMap.put("addPreviousDay", new KeyboardAction(KeyboardAction.ADD_PREVIOUS_DAY));
actionMap.put("addNextDay", new KeyboardAction(KeyboardAction.ADD_NEXT_DAY));
actionMap.put("addToPreviousWeek", new KeyboardAction(KeyboardAction.ADD_TO_PREVIOUS_WEEK));
actionMap.put("addToNextWeek", new KeyboardAction(KeyboardAction.ADD_TO_NEXT_WEEK));
updateUI();
}
/**
* Resets the UI property to a value from the current look and feel.
*/
public void updateUI() {
super.updateUI();
String[] daysOfTheWeek =
(String[])UIManager.get("JXMonthView.daysOfTheWeek");
if (daysOfTheWeek == null) {
String[] dateFormatSymbols =
new DateFormatSymbols().getShortWeekdays();
daysOfTheWeek = new String[DAYS_IN_WEEK];
for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) {
daysOfTheWeek[i - 1] = dateFormatSymbols[i];
}
}
setDaysOfTheWeek(daysOfTheWeek);
Color color =
UIManager.getColor("JXMonthView.monthStringBackground");
if (color == null) {
color = new Color(138, 173, 209);
}
setMonthStringBackground(color);
color = UIManager.getColor("JXMonthView.monthStringForeground");
if (color == null) {
color = new Color(68, 68, 68);
}
setMonthStringForeground(color);
color = UIManager.getColor("JXMonthView.daysOfTheWeekForeground");
if (color == null) {
color = new Color(68, 68, 68);
}
setDaysOfTheWeekForeground(color);
color = UIManager.getColor("JXMonthView.selectedBackground");
if (color == null) {
color = new Color(197, 220, 240);
}
setSelectedBackground(color);
Font font = UIManager.getFont("JXMonthView.font");
if (font == null) {
font = UIManager.getFont("Button.font");
}
setFont(font);
String imageLocation =
UIManager.getString("JXMonthView.monthDownFileName");
if (imageLocation == null) {
imageLocation = "resources/month-down.png";
}
_monthDownImage = new ImageIcon(
JXMonthView.class.getResource(imageLocation));
imageLocation = UIManager.getString("JXMonthView.monthUpFileName");
if (imageLocation == null) {
imageLocation = "resources/month-up.png";
}
_monthUpImage = new ImageIcon(
JXMonthView.class.getResource(imageLocation));
}
/**
* Returns the first displayed date.
*
* @return long The first displayed date.
*/
public long getFirstDisplayedDate() {
return _firstDisplayedDate;
}
/**
* Set the first displayed date. We only use the month and year of
* this date. The <code>Calendar.DAY_OF_MONTH</code> field is reset to
* 1 and all other fields, with exception of the year and month ,
* are reset to 0.
*
* @param date The first displayed date.
*/
public void setFirstDisplayedDate(long date) {
long old = _firstDisplayedDate;
_cal.setTimeInMillis(date);
_cal.set(Calendar.DAY_OF_MONTH, 1);
_cal.set(Calendar.HOUR_OF_DAY, 0);
_cal.set(Calendar.MINUTE, 0);
_cal.set(Calendar.SECOND, 0);
_cal.set(Calendar.MILLISECOND, 0);
_firstDisplayedDate = _cal.getTimeInMillis();
_firstDisplayedMonth = _cal.get(Calendar.MONTH);
_firstDisplayedYear = _cal.get(Calendar.YEAR);
calculateLastDisplayedDate();
firePropertyChange("firstDisplayedDate", old, _firstDisplayedDate);
repaint();
}
/**
* Returns the last date able to be displayed. For example, if the last
* visible month was April the time returned would be April 30, 23:59:59.
*
* @return long The last displayed date.
*/
public long getLastDisplayedDate() {
return _lastDisplayedDate;
}
private void calculateLastDisplayedDate() {
long old = _lastDisplayedDate;
_cal.setTimeInMillis(_firstDisplayedDate);
// Figure out the last displayed date.
_cal.add(Calendar.MONTH, ((_numCalCols * _numCalRows) - 1));
_cal.set(Calendar.DAY_OF_MONTH,
_cal.getActualMaximum(Calendar.DAY_OF_MONTH));
_cal.set(Calendar.HOUR_OF_DAY, 23);
_cal.set(Calendar.MINUTE, 59);
_cal.set(Calendar.SECOND, 59);
_lastDisplayedDate = _cal.getTimeInMillis();
firePropertyChange("lastDisplayedDate", old, _lastDisplayedDate);
}
/**
* Moves the <code>date</code> into the visible region of the calendar.
* If the date is greater than the last visible date it will become the
* last visible date. While if it is less than the first visible date
* it will become the first visible date.
*
* @param date Date to make visible.
*/
public void ensureDateVisible(long date) {
if (date < _firstDisplayedDate) {
setFirstDisplayedDate(date);
} else if (date > _lastDisplayedDate) {
_cal.setTimeInMillis(date);
int month = _cal.get(Calendar.MONTH);
int year = _cal.get(Calendar.YEAR);
_cal.setTimeInMillis(_lastDisplayedDate);
int lastMonth = _cal.get(Calendar.MONTH);
int lastYear = _cal.get(Calendar.YEAR);
int diffMonths = month - lastMonth +
((year - lastYear) * 12);
_cal.setTimeInMillis(_firstDisplayedDate);
_cal.add(Calendar.MONTH, diffMonths);
setFirstDisplayedDate(_cal.getTimeInMillis());
}
if (_startSelectedDate != -1 || _endSelectedDate != -1) {
calculateDirtyRectForSelection();
}
}
/**
* Returns a date span of the selected dates. The result will be null if
* no dates are selected.
*/
public DateSpan getSelectedDateSpan() {
DateSpan result = null;
if (_startSelectedDate != -1) {
result = new DateSpan(new Date(_startSelectedDate),
new Date(_endSelectedDate));
}
return result;
}
/**
* Selects the dates in the DateSpan. This method will not change the
* initial date displayed so the caller must update this if necessary.
* If we are in SINGLE_SELECTION mode only the start time from the DateSpan
* will be used. If we are in WEEK_SELECTION mode the span will be
* modified to be valid if necessary.
*
* @param dateSpan DateSpan defining the selected dates. Passing
* <code>null</code> will clear the selection.
*/
public void setSelectedDateSpan(DateSpan dateSpan) {
DateSpan oldSpan = null;
if (_startSelectedDate != -1 && _endSelectedDate != -1) {
oldSpan = new DateSpan(_startSelectedDate, _endSelectedDate);
}
if (dateSpan == null) {
_startSelectedDate = -1;
_endSelectedDate = -1;
} else {
_cal.setTimeInMillis(dateSpan.getStart());
_cal.set(Calendar.HOUR_OF_DAY, 0);
_cal.set(Calendar.MINUTE, 0);
_cal.set(Calendar.SECOND, 0);
_cal.set(Calendar.MILLISECOND, 0);
_startSelectedDate = _cal.getTimeInMillis();
if (_selectionMode == SINGLE_SELECTION) {
_endSelectedDate = _startSelectedDate;
} else {
_cal.setTimeInMillis(dateSpan.getEnd());
_cal.set(Calendar.HOUR_OF_DAY, 0);
_cal.set(Calendar.MINUTE, 0);
_cal.set(Calendar.SECOND, 0);
_cal.set(Calendar.MILLISECOND, 0);
_endSelectedDate = _cal.getTimeInMillis();
if (_selectionMode == WEEK_SELECTION) {
// Make sure if we are over 7 days we span full weeks.
_cal.setTimeInMillis(_startSelectedDate);
int count = 1;
while (_cal.getTimeInMillis() < _endSelectedDate) {
_cal.add(Calendar.DAY_OF_MONTH, 1);
count++;
}
if (count > 7) {
// Make sure start date is on the beginning of the
// week.
_cal.setTimeInMillis(_startSelectedDate);
int dayOfWeek = _cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != _firstDayOfWeek) {
// Move the start date back to the first day of the
// week.
int daysFromStart = dayOfWeek - _firstDayOfWeek;
if (daysFromStart < 0) {
daysFromStart += DAYS_IN_WEEK;
}
_cal.add(Calendar.DAY_OF_MONTH, -daysFromStart);
count += daysFromStart;
_startSelectedDate = _cal.getTimeInMillis();
}
// Make sure we have full weeks. Otherwise modify the
// end date.
int remainder = count % 7;
if (remainder != 0) {
_cal.setTimeInMillis(_endSelectedDate);
_cal.add(Calendar.DAY_OF_MONTH, (7 - remainder));
_endSelectedDate = _cal.getTimeInMillis();
}
}
}
}
// Restore original time value.
_cal.setTimeInMillis(_firstDisplayedDate);
}
repaint(_dirtyRect);
calculateDirtyRectForSelection();
repaint(_dirtyRect);
// Fire property change.
firePropertyChange("selectedDates", oldSpan, dateSpan);
}
/**
* Returns the current selection mode for this JXMonthView.
*
* @return int Selection mode.
*/
public int getSelectionMode() {
return _selectionMode;
}
public void setSelectionMode(int mode) throws IllegalArgumentException {
if (mode != SINGLE_SELECTION && mode != MULTIPLE_SELECTION &&
mode != WEEK_SELECTION && mode != NO_SELECTION) {
throw new IllegalArgumentException(mode +
" is not a valid selection mode");
}
_selectionMode = mode;
}
/**
* An array of longs defining days that should be flagged. This array is
* assumed to be in sorted order from least to greatest.
*/
public void setFlaggedDates(long[] flaggedDates) {
_flaggedDates = flaggedDates;
if (_flaggedDates == null) {
repaint();
return;
}
// Loop through the flaggedDates and set the hour, minute, seconds and
// milliseconds to 0 so we can compare times later.
for (int i = 0; i < _flaggedDates.length; i++) {
_cal.setTimeInMillis(_flaggedDates[i]);
// We only want to compare the day, month and year
// so reset all other values to 0.
_cal.set(Calendar.HOUR_OF_DAY, 0);
_cal.set(Calendar.MINUTE, 0);
_cal.set(Calendar.SECOND, 0);
_cal.set(Calendar.MILLISECOND, 0);
_flaggedDates[i] = _cal.getTimeInMillis();
}
// Restore the time.
_cal.setTimeInMillis(_firstDisplayedDate);
repaint();
}
/**
* Returns the padding used between days in the calendar.
*/
public int getBoxPaddingX() {
return _boxPaddingX;
}
/**
* Sets the number of pixels used to pad the left and right side of a day.
* The padding is applied to both sides of the days. Therefore, if you
* used the padding value of 3, the number of pixels between any two days
* would be 6.
*/
public void setBoxPaddingX(int _boxPaddingX) {
this._boxPaddingX = _boxPaddingX;
_dirty = true;
}
/**
* Returns the padding used above and below days in the calendar.
*/
public int getBoxPaddingY() {
return _boxPaddingY;
}
/**
* Sets the number of pixels used to pad the top and bottom of a day.
* The padding is applied to both the top and bottom of a day. Therefore,
* if you used the padding value of 3, the number of pixels between any
* two days would be 6.
*/
public void setBoxPaddingY(int _boxPaddingY) {
this._boxPaddingY = _boxPaddingY;
_dirty = true;
}
/**
* Returns whether or not the month view supports traversing months.
*
* @return <code>true</code> if month traversing is enabled.
*/
public boolean getTraversable() {
return _traversable;
}
/**
* Set whether or not the month view will display buttons to allow the
* user to traverse to previous or next months.
*
* @param traversable set to true to enable month traversing,
* false otherwise.
*/
public void setTraversable(boolean traversable) {
_traversable = traversable;
_dirty = true;
repaint();
}
public void setDaysOfTheWeek(String[] days)
throws IllegalArgumentException, NullPointerException {
if (days == null) {
throw new NullPointerException("Array of days is null.");
} else if (days.length != 7) {
throw new IllegalArgumentException(
"Array of days is not of length 7 as expected.");
}
// TODO: This could throw off internal size information we should
// call update and then recalculate displayed calendars and start
// positions.
_daysOfTheWeek = days;
_dirty = true;
repaint();
}
/**
* Returns the single character representation for each day of the
* week.
*
* @return Single character representation for the days of the week
*/
public String[] getDaysOfTheWeek() {
String[] days = new String[7];
System.arraycopy(_daysOfTheWeek, 0, days, 0, 7);
return days;
}
/**
* Gets what the first day of the week is; e.g.,
* <code>Calendar.SUNDAY</code> in the U.S., <code>Calendar.MONDAY</code>
* in France.
*
* @return int The first day of the week.
*/
public int getFirstDayOfWeek() {
return _firstDayOfWeek;
}
/**
* Sets what the first day of the week is; e.g.,
* <code>Calendar.SUNDAY</code> in US, <code>Calendar.MONDAY</code>
* in France.
*
* @param firstDayOfWeek The first day of the week.
*
* @see java.util.Calendar
*/
public void setFirstDayOfWeek(int firstDayOfWeek) {
if (firstDayOfWeek == _firstDayOfWeek) {
return;
}
_firstDayOfWeek = firstDayOfWeek;
_cal.setFirstDayOfWeek(_firstDayOfWeek);
repaint();
}
/**
* Gets the time zone.
*
* @return The <code>TimeZone</code> used by the <code>JXMonthView</code>.
*/
public TimeZone getTimeZone() {
return _cal.getTimeZone();
}
/**
* Sets the time zone with the given time zone value.
*
* @param tz The <code>TimeZone</code>.
*/
public void setTimeZone(TimeZone tz) {
_cal.setTimeZone(tz);
}
/**
* Returns true if anti-aliased text is enabled for this component, false
* otherwise.
*
* @return boolean <code>true</code> if anti-aliased text is enabled,
* <code>false</code> otherwise.
*/
public boolean getAntialiased() {
return _antiAlias;
}
/**
* Turns on/off anti-aliased text for this component.
*
* @param antiAlias <code>true</code> for anti-aliased text,
* <code>false</code> to turn it off.
*/
public void setAntialiased(boolean antiAlias) {
if (_antiAlias == antiAlias) {
return;
}
_antiAlias = antiAlias;
repaint();
}
/**
public void setDropShadowMask(int mask) {
_dropShadowMask = mask;
repaint();
}
*/
/**
* Returns the selected background color.
*
* @return the selected background color.
*/
public Color getSelectedBackground() {
return _selectedBackground;
}
/**
* Sets the selected background color to <code>c</code>. The default color
* is <code>138, 173, 209 (Blue-ish)</code>
*
* @param c Selected background.
*/
public void setSelectedBackground(Color c) {
_selectedBackground = c;
}
/**
* Returns the color used when painting the today background.
*
* @return Color Color
*/
public Color getTodayBackground() {
return _todayBackgroundColor;
}
/**
* Sets the color used to draw the bounding box around today. The default
* is the background of the <code>JXMonthView</code> component.
*
* @param c color to set
*/
public void setTodayBackground(Color c) {
_todayBackgroundColor = c;
repaint();
}
/**
* Returns the color used to paint the month string background.
*
* @return Color Color.
*/
public Color getMonthStringBackground() {
return _monthStringBackground;
}
/**
* Sets the color used to draw the background of the month string. The
* default is <code>138, 173, 209 (Blue-ish)</code>.
*
* @param c color to set
*/
public void setMonthStringBackground(Color c) {
_monthStringBackground = c;
repaint();
}
/**
* Returns the color used to paint the month string foreground.
*
* @return Color Color.
*/
public Color getMonthStringForeground() {
return _monthStringForeground;
}
/**
* Sets the color used to draw the foreground of the month string. The
* default is <code>Color.WHITE</code>.
*
* @param c color to set
*/
public void setMonthStringForeground(Color c) {
_monthStringForeground = c;
repaint();
}
/**
* Sets the color used to draw the foreground of each day of the week. These
* are the titles
*
* @param c color to set
*/
public void setDaysOfTheWeekForeground(Color c) {
_daysOfTheWeekForeground = c;
repaint();
}
/**
* @return Color Color
*/
public Color getDaysOfTheWeekForeground() {
return _daysOfTheWeekForeground;
}
/**
* Set the color to be used for painting the specified day of the week.
* Acceptable values are Calendar.SUNDAY - Calendar.SATURDAY.
*
* @dayOfWeek constant value defining the day of the week.
* @c The color to be used for painting the numeric day of the week.
*/
public void setDayForeground(int dayOfWeek, Color c) {
_dayToColorTable.put(dayOfWeek, c);
}
/**
* Return the color that should be used for painting the numerical day of the week.
*
* @param dayOfWeek The day of week to get the color for.
* @return The color to be used for painting the numeric day of the week.
* If this was no color has yet been defined the component foreground color
* will be returned.
*/
public Color getDayForeground(int dayOfWeek) {
Color c;
c = (Color)_dayToColorTable.get(dayOfWeek);
if (c == null) {
c = getForeground();
}
return c;
}
/**
* Returns a copy of the insets used to paint the month string background.
*
* @return Insets Month string insets.
*/
public Insets getMonthStringInsets() {
return (Insets)_monthStringInsets.clone();
}
/**
* Insets used to modify the width/height when painting the background
* of the month string area.
*
* @param insets Insets
*/
public void setMonthStringInsets(Insets insets) {
if (insets == null) {
_monthStringInsets.top = 0;
_monthStringInsets.left = 0;
_monthStringInsets.bottom = 0;
_monthStringInsets.right = 0;
} else {
_monthStringInsets.top = insets.top;
_monthStringInsets.left = insets.left;
_monthStringInsets.bottom = insets.bottom;
_monthStringInsets.right = insets.right;
}
repaint();
}
/**
* Returns the preferred number of columns to paint calendars in.
*
* @return int Columns of calendars.
*/
public int getPreferredCols() {
return _minCalCols;
}
/**
* The preferred number of columns to paint calendars.
*
* @param cols The number of columns of calendars.
*/
public void setPreferredCols(int cols) {
if (cols <= 0) {
return;
}
_minCalCols = cols;
_dirty = true;
revalidate();
repaint();
}
/**
* Returns the preferred number of rows to paint calendars in.
*
* @return int Rows of calendars.
*/
public int getPreferredRows() {
return _minCalRows;
}
/**
* Sets the preferred number of rows to paint calendars.
*
* @param rows The number of rows of calendars.
*/
public void setPreferredRows(int rows) {
if (rows <= 0) {
return;
}
_minCalRows = rows;
_dirty = true;
revalidate();
repaint();
}
private void updateIfNecessary() {
if (_dirty) {
update();
_dirty = false;
}
}
/**
* Calculates size information necessary for laying out the month view.
*/
private void update() {
// Loop through year and get largest representation of the month.
// Keep track of the longest month so we can loop through it to
// determine the width of a date box.
int currDays;
int longestMonth = 0;
int daysInLongestMonth = 0;
int currWidth;
int longestMonthWidth = 0;
// We use a bold font for figuring out size constraints since
// it's larger and flaggedDates will be noted in this style.
_derivedFont = getFont().deriveFont(Font.BOLD);
FontMetrics fm = getFontMetrics(_derivedFont);
_cal.set(Calendar.MONTH, _cal.getMinimum(Calendar.MONTH));
_cal.set(Calendar.DAY_OF_MONTH,
_cal.getActualMinimum(Calendar.DAY_OF_MONTH));
for (int i = 0; i < _cal.getMaximum(Calendar.MONTH); i++) {
currWidth = fm.stringWidth(_monthsOfTheYear[i]);
if (currWidth > longestMonthWidth) {
longestMonthWidth = currWidth;
}
currDays = _cal.getActualMaximum(Calendar.DAY_OF_MONTH);
if (currDays > daysInLongestMonth) {
longestMonth = _cal.get(Calendar.MONTH);
daysInLongestMonth = currDays;
}
_cal.add(Calendar.MONTH, 1);
}
// Loop through the days of the week and adjust the box width
// accordingly.
_boxHeight = fm.getHeight();
for (int i = 0; i < _daysOfTheWeek.length; i++) {
currWidth = fm.stringWidth(_daysOfTheWeek[i]);
if (currWidth > _boxWidth) {
_boxWidth = currWidth;
}
}
// Loop through longest month and get largest representation of the day
// of the month.
_cal.set(Calendar.MONTH, longestMonth);
_cal.set(Calendar.DAY_OF_MONTH,
_cal.getActualMinimum(Calendar.DAY_OF_MONTH));
for (int i = 0; i < daysInLongestMonth; i++) {
currWidth = fm.stringWidth(
_dayOfMonthFormatter.format(_cal.getTime()));
if (currWidth > _boxWidth) {
_boxWidth = currWidth;
}
_cal.add(Calendar.DAY_OF_MONTH, 1);
}
// If the calendar is traversable, check the icon heights and
// adjust the month box height accordingly.
_monthBoxHeight = _boxHeight;
if (_traversable) {
int newHeight = _monthDownImage.getIconHeight() +
_arrowPaddingY + _arrowPaddingY;
if (newHeight > _monthBoxHeight) {
_monthBoxHeight = newHeight;
}
}
// Modify _boxWidth if month string is longer
_dim.width = (_boxWidth + (2 * _boxPaddingX)) * DAYS_IN_WEEK;
if (_dim.width < longestMonthWidth) {
double diff = longestMonthWidth - _dim.width;
if (_traversable) {
diff += _monthDownImage.getIconWidth() +
_monthUpImage.getIconWidth() + (_arrowPaddingX * 4);
}
_boxWidth += Math.ceil(diff / (double)DAYS_IN_WEEK);
_dim.width = (_boxWidth + (2 * _boxPaddingX)) * DAYS_IN_WEEK;
}
// Keep track of calendar width and height for use later.
_calendarWidth = (_boxWidth + (2 * _boxPaddingX)) * DAYS_IN_WEEK;
_calendarHeight = ((_boxPaddingY + _boxHeight + _boxPaddingY) * 7) +
(_boxPaddingY + _monthBoxHeight + _boxPaddingY);
// Calculate minimum width/height for the component.
_dim.height = (_calendarHeight * _minCalRows) +
(CALENDAR_SPACING * (_minCalRows - 1));
_dim.width = (_calendarWidth * _minCalCols) +
(CALENDAR_SPACING * (_minCalCols - 1));
// Add insets to the dimensions.
Insets insets = getInsets();
_dim.width += insets.left + insets.right;
_dim.height += insets.top + insets.bottom;
// Restore calendar.
_cal.setTimeInMillis(_firstDisplayedDate);
calculateNumDisplayedCals();
calculateStartPosition();
if (_startSelectedDate != -1 || _endSelectedDate != -1) {
if (_startSelectedDate > _lastDisplayedDate ||
_startSelectedDate < _firstDisplayedDate) {
// Already does the recalculation for the dirty rect.
ensureDateVisible(_startSelectedDate);
} else {
calculateDirtyRectForSelection();
}
}
}
private void updateToday() {
// Update _today.
_cal.setTimeInMillis(_today);
_cal.add(Calendar.DAY_OF_MONTH, 1);
_today = _cal.getTimeInMillis();
// Restore calendar.
_cal.setTimeInMillis(_firstDisplayedDate);
repaint();
}
/**
* Returns the minimum size needed to display this component.
*
* @return Dimension Minimum size.
*/
@Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
/**
* Returns the preferred size of this component.
*
* @return Dimension Preferred size.
*/
@Override
public Dimension getPreferredSize() {
updateIfNecessary();
return new Dimension(_dim);
}
/**
* Returns the maximum size of this component.
*
* @return Dimension Maximum size.
*/
@Override
public Dimension getMaximumSize() {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
/**
* Sets the border of this component. The Border object is responsible
* for defining the insets for the component (overriding any insets set
* directly on the component) and for optionally rendering any border
* decorations within the bounds of those insets. Borders should be used
* (rather than insets) for creating both decorative and non-decorative
* (such as margins and padding) regions for a swing component. Compound
* borders can be used to nest multiple borders within a single component.
* <p>
* As the border may modify the bounds of the component, setting the border
* may result in a reduced number of displayed calendars.
*
* @param border Border.
*/
@Override
public void setBorder(Border border) {
super.setBorder(border);
_dirty = true;
}
/**
* Moves and resizes this component. The new location of the top-left
* corner is specified by x and y, and the new size is specified by
* width and height.
*
* @param x The new x-coordinate of this component
* @param y The new y-coordinate of this component
* @param width The new width of this component
* @param height The new height of this component
*/
@Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, height);
_dirty = true;
}
/**
* Moves and resizes this component to conform to the new bounding
* rectangle r. This component's new position is specified by r.x and
* r.y, and its new size is specified by r.width and r.height
*
* @param r The new bounding rectangle for this component
*/
@Override
public void setBounds(Rectangle r) {
setBounds(r.x, r.y, r.width, r.height);
}
/**
* Sets the language-sensitive orientation that is to be used to order
* the elements or text within this component. Language-sensitive
* LayoutManager and Component subclasses will use this property to
* determine how to lay out and draw components.
* <p>
* At construction time, a component's orientation is set to
* ComponentOrientation.UNKNOWN, indicating that it has not been
* specified explicitly. The UNKNOWN orientation behaves the same as
* ComponentOrientation.LEFT_TO_RIGHT.
*
* @param o The component orientation.
*/
@Override
public void setComponentOrientation(ComponentOrientation o) {
super.setComponentOrientation(o);
_ltr = o.isLeftToRight();
calculateStartPosition();
calculateDirtyRectForSelection();
}
/**
* Sets the font of this component.
*
* @param font The font to become this component's font; if this parameter
* is null then this component will inherit the font of its parent.
*/
@Override
public void setFont(Font font) {
super.setFont(font);
_dirty = true;
}
/**
* {@inheritDoc}
*/
@Override
public void removeNotify() {
_todayTimer.stop();
super.removeNotify();
}
/**
* {@inheritDoc}
*/
@Override
public void addNotify() {
super.addNotify();
// Setup timer to update the value of _today.
int secondsTillTomorrow = 86400;
if (_todayTimer == null) {
_todayTimer = new Timer(secondsTillTomorrow * 1000,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateToday();
}
});
}
// Modify the initial delay by the current time.
_cal.setTimeInMillis(System.currentTimeMillis());
secondsTillTomorrow = secondsTillTomorrow -
(_cal.get(Calendar.HOUR_OF_DAY) * 3600) -
(_cal.get(Calendar.MINUTE) * 60) -
_cal.get(Calendar.SECOND);
_todayTimer.setInitialDelay(secondsTillTomorrow * 1000);
_todayTimer.start();
// Restore calendar
_cal.setTimeInMillis(_firstDisplayedDate);
}
/**
* {@inheritDoc}
*/
@Override
protected void paintComponent(Graphics g) {
Object oldAAValue = null;
Graphics2D g2 = (g instanceof Graphics2D) ? (Graphics2D)g : null;
if (g2 != null && _antiAlias) {
oldAAValue = g2.getRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
Rectangle clip = g.getClipBounds();
updateIfNecessary();
if (isOpaque()) {
g.setColor(getBackground());
g.fillRect(clip.x, clip.y, clip.width, clip.height);
}
g.setColor(getForeground());
Color shadowColor = g.getColor();
shadowColor = new Color(shadowColor.getRed(), shadowColor.getGreen(),
shadowColor.getBlue(), (int)(.20 * 255));
FontMetrics fm = g.getFontMetrics();
// Reset the calendar.
_cal.setTimeInMillis(_firstDisplayedDate);
// Center the calendars vertically in the available space.
int y = _startY;
for (int row = 0; row < _numCalRows; row++) {
// Center the calendars horizontally in the available space.
int x = _startX;
int tmpX, tmpY;
// Check if this row falls in the clip region.
_bounds.x = 0;
_bounds.y = _startY +
row * (_calendarHeight + CALENDAR_SPACING);
_bounds.width = getWidth();
_bounds.height = _calendarHeight;
if (!_bounds.intersects(clip)) {
_cal.add(Calendar.MONTH, _numCalCols);
y += _calendarHeight + CALENDAR_SPACING;
continue;
}
for (int column = 0; column < _numCalCols; column++) {
String monthName = _monthsOfTheYear[_cal.get(Calendar.MONTH)];
monthName = monthName + " " + _cal.get(Calendar.YEAR);
_bounds.x = (_ltr ? x : x - _calendarWidth);// + 4; //4px of padding on the left
_bounds.y = y + _boxPaddingY;// + 4; //4px of padding on the top
_bounds.width = _calendarWidth;// - 8; //4px of padding on both sides
_bounds.height = _monthBoxHeight; //4px of padding on top
if (_bounds.intersects(clip)) {
// Paint month name background.
paintMonthStringBackground(g, _bounds.x, _bounds.y,
_bounds.width, _bounds.height);
// Paint arrow buttons for traversing months if enabled.
if (_traversable) {
tmpX = _bounds.x + _arrowPaddingX;
tmpY = _bounds.y + (_bounds.height -
_monthDownImage.getIconHeight()) / 2;
g.drawImage(_monthDownImage.getImage(),
tmpX, tmpY, null);
tmpX = _bounds.x + _bounds.width - _arrowPaddingX -
_monthUpImage.getIconWidth();
g.drawImage(_monthUpImage.getImage(), tmpX, tmpY, null);
}
// Paint month name.
Font oldFont = getFont();
FontMetrics oldFM = fm;
g.setFont(_derivedFont);
fm = getFontMetrics(_derivedFont);
g.setColor(_monthStringForeground);
tmpX = _ltr ?
x + (_calendarWidth / 2) -
(fm.stringWidth(monthName) / 2) :
x - (_calendarWidth / 2) -
(fm.stringWidth(monthName) / 2) - 1;
tmpY = _bounds.y + ((_monthBoxHeight - _boxHeight) / 2) +
fm.getAscent();
if ((_dropShadowMask & MONTH_DROP_SHADOW) != 0) {
g.setColor(shadowColor);
g.drawString(monthName, tmpX + 1, tmpY + 1);
g.setColor(_monthStringForeground);
}
g.drawString(monthName, tmpX, tmpY);
g.setFont(oldFont);
fm = oldFM;
}
g.setColor(getDaysOfTheWeekForeground());
_bounds.x = _ltr ? x : x - _calendarWidth;
_bounds.y = y + _boxPaddingY + _monthBoxHeight +
_boxPaddingY + _boxPaddingY;
_bounds.width = _calendarWidth;
_bounds.height = _boxHeight;
if (_bounds.intersects(clip)) {
_cal.set(Calendar.DAY_OF_MONTH,
_cal.getActualMinimum(Calendar.DAY_OF_MONTH));
// Paint short representation of day of the week.
int dayIndex = _firstDayOfWeek - 1;
Font oldFont = g.getFont();
FontMetrics oldFM = fm;
g.setFont(_derivedFont);
fm = getFontMetrics(_derivedFont);
for (int i = 0; i < DAYS_IN_WEEK; i++) {
tmpX = _ltr ?
x + (i * (_boxPaddingX + _boxWidth +
_boxPaddingX)) + _boxPaddingX +
(_boxWidth / 2) -
(fm.stringWidth(_daysOfTheWeek[dayIndex]) /
2) :
x - (i * (_boxPaddingX + _boxWidth +
_boxPaddingX)) - _boxPaddingX -
(_boxWidth / 2) -
(fm.stringWidth(_daysOfTheWeek[dayIndex]) /
2);
tmpY = _bounds.y + fm.getAscent();
if ((_dropShadowMask & WEEK_DROP_SHADOW) != 0) {
g.setColor(shadowColor);
g.drawString(_daysOfTheWeek[dayIndex],
tmpX + 1, tmpY + 1);
g.setColor(getDaysOfTheWeekForeground());
}
g.drawString(_daysOfTheWeek[dayIndex], tmpX, tmpY);
dayIndex++;
if (dayIndex == 7) {
dayIndex = 0;
}
}
g.setFont(oldFont);
fm = oldFM;
}
// Check if the month to paint falls in the clip.
_bounds.x = _startX +
(_ltr ?
column * (_calendarWidth + CALENDAR_SPACING) :
-(column * (_calendarWidth + CALENDAR_SPACING) +
_calendarWidth));
_bounds.y = _startY +
row * (_calendarHeight + CALENDAR_SPACING);
_bounds.width = _calendarWidth;
_bounds.height = _calendarHeight;
// Paint the month if it intersects the clip. If we don't move
// the calendar forward a month as it would have if paintMonth
// was called.
if (_bounds.intersects(clip)) {
paintMonth(g, column, row);
} else {
_cal.add(Calendar.MONTH, 1);
}
x += _ltr ?
_calendarWidth + CALENDAR_SPACING :
-(_calendarWidth + CALENDAR_SPACING);
}
y += _calendarHeight + CALENDAR_SPACING;
}
// Restore the calendar.
_cal.setTimeInMillis(_firstDisplayedDate);
if (g2 != null && _antiAlias) {
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
oldAAValue);
}
}
/**
* Paints a month. It is assumed the calendar, _cal, is already set to the
* first day of the month to be painted.
*
* @param col X (column) the calendar is displayed in.
* @param row Y (row) the calendar is displayed in.
* @param g Graphics object.
*/
private void paintMonth(Graphics g, int col, int row) {
String numericDay;
int days = _cal.getActualMaximum(Calendar.DAY_OF_MONTH);
FontMetrics fm = g.getFontMetrics();
Rectangle clip = g.getClipBounds();
long nextFlaggedDate = -1;
int flaggedDateIndex = 0;
if (_flaggedDates != null && _flaggedDates.length > 0) {
nextFlaggedDate = _flaggedDates[flaggedDateIndex];
}
for (int i = 0; i < days; i++) {
calculateBoundsForDay(_bounds);
if (_bounds.intersects(clip)) {
numericDay = _dayOfMonthFormatter.format(_cal.getTime());
// Paint bounding box around any date that falls within the
// selection.
if (isSelectedDate(_cal.getTimeInMillis())) {
// Keep track of the rectangle for the currently
// selected date so we don't have to recalculate it
// later when it becomes unselected. This is only
// useful for SINGLE_SELECTION mode.
if (_selectionMode == SINGLE_SELECTION) {
_dirtyRect.x = _bounds.x;
_dirtyRect.y = _bounds.y;
_dirtyRect.width = _bounds.width;
_dirtyRect.height = _bounds.height;
}
paintSelectedDayBackground(g, _bounds.x, _bounds.y,
_bounds.width, _bounds.height);
g.setColor(getForeground());
}
// Paint bounding box around today.
if (_cal.getTimeInMillis() == _today) {
paintTodayBackground(g, _bounds.x, _bounds.y,
_bounds.width, _bounds.height);
g.setColor(getForeground());
}
// If the appointment date is less than the current
// calendar date increment to the next appointment.
while (nextFlaggedDate != -1 &&
nextFlaggedDate < _cal.getTimeInMillis()) {
flaggedDateIndex++;
if (flaggedDateIndex < _flaggedDates.length) {
nextFlaggedDate = _flaggedDates[flaggedDateIndex];
} else {
nextFlaggedDate = -1;
}
}
// Paint numeric day of the month.
g.setColor(getDayForeground(_cal.get(Calendar.DAY_OF_WEEK)));
if (nextFlaggedDate != -1 &&
_cal.getTimeInMillis() == nextFlaggedDate) {
Font oldFont = getFont();
FontMetrics oldFM = fm;
g.setFont(_derivedFont);
fm = getFontMetrics(_derivedFont);
g.drawString(numericDay,
_ltr ?
_bounds.x + _boxPaddingX +
_boxWidth - fm.stringWidth(numericDay):
_bounds.x + _boxPaddingX +
_boxWidth - fm.stringWidth(numericDay) - 1,
_bounds.y + _boxPaddingY + fm.getAscent());
g.setFont(oldFont);
fm = oldFM;
} else {
g.drawString(numericDay,
_ltr ?
_bounds.x + _boxPaddingX +
_boxWidth - fm.stringWidth(numericDay):
_bounds.x + _boxPaddingX +
_boxWidth - fm.stringWidth(numericDay) - 1,
_bounds.y + _boxPaddingY + fm.getAscent());
}
}
_cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
protected void paintMonthStringBackground(Graphics g, int x, int y,
int width, int height) {
// Modify bounds by the month string insets.
x = _ltr ? x + _monthStringInsets.left : x + _monthStringInsets.right;
y = y + _monthStringInsets.top;
width = width - _monthStringInsets.left - _monthStringInsets.right;
height = height - _monthStringInsets.top - _monthStringInsets.bottom;
Graphics2D g2 = (Graphics2D)g;
GradientPaint gp = new GradientPaint(x, y + height, new Color(238, 238, 238), x, y, new Color(204, 204, 204));
//paint the border
// g.setColor(_monthStringBackground);
g2.setPaint(gp);
g2.fillRect(x, y, width - 1, height - 1);
g2.setPaint(new Color(153, 153, 153));
g2.drawRect(x, y, width - 1, height - 1);
//TODO The right side of the rect is being clipped
}
/**
* Paints the background for today. The default is a rectangle drawn in
* using the color set by <code>setTodayBackground</code>
*
* @see #setTodayBackground
* @param g Graphics object to paint to.
* @param x x-coordinate of upper left corner.
* @param y y-coordinate of upper left corner.
* @param width width of bounding box for the day.
* @param height height of bounding box for the day.
*/
protected void paintTodayBackground(Graphics g, int x, int y, int width,
int height) {
// g.setColor(_todayBackgroundColor);
// g.drawRect(x, y, width - 1, height - 1);
//paint the gradiented border
GradientPaint gp = new GradientPaint(x, y, new Color(91, 123, 145), x, y + height, new Color(68, 86, 98));
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(gp);
g2.drawRect(x, y, width - 1, height - 1);
}
/**
* Paint the background for a selected day. The default is a filled
* rectangle in the in the component's background color.
*
* @param g Graphics object to paint to.
* @param x x-coordinate of upper left corner.
* @param y y-coordinate of upper left corner.
* @param width width of bounding box for the day.
* @param height height of bounding box for the day.
*/
protected void paintSelectedDayBackground(Graphics g, int x, int y,
int width, int height) {
g.setColor(getSelectedBackground());
g.fillRect(x, y, width, height);
}
/**
* Returns true if the specified time falls within the _startSelectedDate
* and _endSelectedDate range.
*/
private boolean isSelectedDate(long time) {
if (time >= _startSelectedDate && time <= _endSelectedDate) {
return true;
}
return false;
}
/**
* Calculates the _numCalCols/_numCalRows that determine the number of
* calendars that can be displayed.
*/
private void calculateNumDisplayedCals() {
int oldNumCalCols = _numCalCols;
int oldNumCalRows = _numCalRows;
// Determine how many columns of calendars we want to paint.
_numCalCols = 1;
_numCalCols += (getWidth() - _calendarWidth) /
(_calendarWidth + CALENDAR_SPACING);
// Determine how many rows of calendars we want to paint.
_numCalRows = 1;
_numCalRows += (getHeight() - _calendarHeight) /
(_calendarHeight + CALENDAR_SPACING);
if (oldNumCalCols != _numCalCols ||
oldNumCalRows != _numCalRows) {
calculateLastDisplayedDate();
}
}
/**
* Calculates the _startX/_startY position for centering the calendars
* within the available space.
*/
private void calculateStartPosition() {
// Calculate offset in x-axis for centering calendars.
_startX = (getWidth() - ((_calendarWidth * _numCalCols) +
(CALENDAR_SPACING * (_numCalCols - 1)))) / 2;
if (!_ltr) {
_startX = getWidth() - _startX;
}
// Calculate offset in y-axis for centering calendars.
_startY = (getHeight() - ((_calendarHeight * _numCalRows) +
(CALENDAR_SPACING * (_numCalRows - 1 )))) / 2;
}
/**
* Calculate the bounding box for drawing a date. It is assumed that the
* calendar, _cal, is already set to the date you want to find the offset
* for.
*
* @param bounds Bounds of the date to draw in.
*/
private void calculateBoundsForDay(Rectangle bounds) {
int year = _cal.get(Calendar.YEAR);
int month = _cal.get(Calendar.MONTH);
int dayOfWeek = _cal.get(Calendar.DAY_OF_WEEK);
int weekOfMonth = _cal.get(Calendar.WEEK_OF_MONTH);
// Determine what row/column we are in.
int diffMonths = month - _firstDisplayedMonth +
((year - _firstDisplayedYear) * 12);
int calRowIndex = diffMonths / _numCalCols;
int calColIndex = diffMonths - (calRowIndex * _numCalCols);
// Modify the index relative to the first day of the week.
bounds.x = dayOfWeek - _firstDayOfWeek;
if (bounds.x < 0) {
bounds.x += DAYS_IN_WEEK;
}
// Offset for location of the day in the week.
bounds.x = _ltr ?
bounds.x * (_boxPaddingX + _boxWidth + _boxPaddingX) :
(bounds.x + 1) * (_boxPaddingX + _boxWidth + _boxPaddingX);
// Offset for the column the calendar is displayed in.
bounds.x += calColIndex * (_calendarWidth + CALENDAR_SPACING);
// Adjust by centering value.
bounds.x = _ltr ? _startX + bounds.x : _startX - bounds.x;
// Initial offset for Month and Days of the Week display.
bounds.y = _boxPaddingY + _monthBoxHeight + _boxPaddingY +
+ _boxPaddingY + _boxHeight + _boxPaddingY;
// Offset for centering and row the calendar is displayed in.
bounds.y += _startY + calRowIndex *
(_calendarHeight + CALENDAR_SPACING);
// Offset for Week of the Month.
bounds.y += (weekOfMonth - 1) *
(_boxPaddingY + _boxHeight + _boxPaddingY);
bounds.width = _boxPaddingX + _boxWidth + _boxPaddingX;
bounds.height = _boxPaddingY + _boxHeight + _boxPaddingY;
}
/**
* Return a long representing the date at the specified x/y position.
* The date returned will have a valid day, month and year. Other fields
* such as hour, minute, second and milli-second will be set to 0.
*
* @param x X position
* @param y Y position
* @return long The date, -1 if position does not contain a date.
*/
public long getDayAt(int x, int y) {
if (_ltr ? (_startX > x) : (_startX < x) || _startY > y) {
return -1;
}
// Determine which column of calendars we're in.
int calCol = (_ltr ? (x - _startX) : (_startX - x)) /
(_calendarWidth + CALENDAR_SPACING);
// Determine which row of calendars we're in.
int calRow = (y - _startY) / (_calendarHeight + CALENDAR_SPACING);
if (calRow > _numCalRows - 1 || calCol > _numCalCols - 1) {
return -1;
}
// Determine what row (week) in the selected month we're in.
int row = 1;
row += (((y - _startY) -
(calRow * (_calendarHeight + CALENDAR_SPACING))) -
(_boxPaddingY + _monthBoxHeight + _boxPaddingY)) /
(_boxPaddingY + _boxHeight + _boxPaddingY);
// The first two lines in the calendar are the month and the days
// of the week. Ignore them.
row -= 2;
if (row < 0 || row > 5) {
return -1;
}
// Determine which column in the selected month we're in.
int col = ((_ltr ? (x - _startX) : (_startX - x)) -
(calCol * (_calendarWidth + CALENDAR_SPACING))) /
(_boxPaddingX + _boxWidth + _boxPaddingX);
if (col > DAYS_IN_WEEK - 1) {
return -1;
}
// Use the first day of the month as a key point for determining the
// date of our click.
// The week index of the first day will always be 0.
_cal.setTimeInMillis(_firstDisplayedDate);
//_cal.set(Calendar.DAY_OF_MONTH, 1);
_cal.add(Calendar.MONTH, calCol + (calRow * _numCalCols));
int dayOfWeek = _cal.get(Calendar.DAY_OF_WEEK);
int firstDayIndex = dayOfWeek - _firstDayOfWeek;
if (firstDayIndex < 0) {
firstDayIndex += DAYS_IN_WEEK;
}
int daysToAdd = (row * DAYS_IN_WEEK) + (col - firstDayIndex);
if (daysToAdd < 0 || daysToAdd >
(_cal.getActualMaximum(Calendar.DAY_OF_MONTH) - 1)) {
return -1;
}
_cal.add(Calendar.DAY_OF_MONTH, daysToAdd);
long selected = _cal.getTimeInMillis();
// Restore the time.
_cal.setTimeInMillis(_firstDisplayedDate);
return selected;
}
/**
* Returns an index defining which, if any, of the buttons for
* traversing the month was pressed. This method should only be
* called when <code>setTraversable</code> is set to true.
*
* @param x x position of the pointer
* @param y y position of the pointer
* @return MONTH_UP, MONTH_DOWN or -1 when no button is selected.
*/
protected int getTraversableButtonAt(int x, int y) {
if (_ltr ? (_startX > x) : (_startX < x) || _startY > y) {
return -1;
}
// Determine which column of calendars we're in.
int calCol = (_ltr ? (x - _startX) : (_startX - x)) /
(_calendarWidth + CALENDAR_SPACING);
// Determine which row of calendars we're in.
int calRow = (y - _startY) / (_calendarHeight + CALENDAR_SPACING);
if (calRow > _numCalRows - 1 || calCol > _numCalCols - 1) {
return -1;
}
// See if we're in the month string area.
y = ((y - _startY) -
(calRow * (_calendarHeight + CALENDAR_SPACING))) - _boxPaddingY;
if (y < _arrowPaddingY || y > (_monthBoxHeight - _arrowPaddingY)) {
return -1;
}
x = ((_ltr ? (x - _startX) : (_startX - x)) -
(calCol * (_calendarWidth + CALENDAR_SPACING)));
if (x > _arrowPaddingX && x < (_arrowPaddingX +
_monthDownImage.getIconWidth() + _arrowPaddingX)) {
return MONTH_DOWN;
}
if (x > (_calendarWidth - _arrowPaddingX * 2 -
_monthUpImage.getIconWidth()) &&
x < (_calendarWidth - _arrowPaddingX)) {
return MONTH_UP;
}
return -1;
}
private void calculateDirtyRectForSelection() {
if (_startSelectedDate == -1 || _endSelectedDate == -1) {
_dirtyRect.x = 0;
_dirtyRect.y = 0;
_dirtyRect.width = 0;
_dirtyRect.height = 0;
} else {
_cal.setTimeInMillis(_startSelectedDate);
calculateBoundsForDay(_dirtyRect);
_cal.add(Calendar.DAY_OF_MONTH, 1);
Rectangle tmpRect;
while (_cal.getTimeInMillis() <= _endSelectedDate) {
calculateBoundsForDay(_bounds);
tmpRect = _dirtyRect.union(_bounds);
_dirtyRect.x = tmpRect.x;
_dirtyRect.y = tmpRect.y;
_dirtyRect.width = tmpRect.width;
_dirtyRect.height = tmpRect.height;
_cal.add(Calendar.DAY_OF_MONTH, 1);
}
// Restore the time.
_cal.setTimeInMillis(_firstDisplayedDate);
}
}
/**
* Returns the string currently used to identiy fired ActionEvents.
*
* @return String The string used for identifying ActionEvents.
*/
public String getActionCommand() {
return _actionCommand;
}
/**
* Sets the string used to identify fired ActionEvents.
*
* @param actionCommand The string used for identifying ActionEvents.
*/
public void setActionCommand(String actionCommand) {
_actionCommand = actionCommand;
}
/**
* Adds an ActionListener.
* <p>
* The ActionListener will receive an ActionEvent when a selection has
* been made.
*
* @param l The ActionListener that is to be notified
*/
public void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class, l);
}
/**
* Removes an ActionListener.
*
* @param l The action listener to remove.
*/
public void removeActionListener(ActionListener l) {
listenerList.remove(ActionListener.class, l);
}
/**
* Fires an ActionEvent to all listeners.
*/
protected void fireActionPerformed() {
Object[] listeners = listenerList.getListenerList();
ActionEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -=2) {
if (listeners[i] == ActionListener.class) {
if (e == null) {
e = new ActionEvent(JXMonthView.this,
ActionEvent.ACTION_PERFORMED,
_actionCommand);
}
((ActionListener)listeners[i + 1]).actionPerformed(e);
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected void processMouseEvent(MouseEvent e) {
if (!isEnabled()) {
return;
}
if (!hasFocus() && isFocusable()) {
requestFocusInWindow();
}
int id = e.getID();
// Check if one of the month traverse buttons was pushed.
if (id == MouseEvent.MOUSE_PRESSED && _traversable) {
int arrowType = getTraversableButtonAt(e.getX(), e.getY());
if (arrowType == MONTH_DOWN) {
setFirstDisplayedDate(
DateUtils.getPreviousMonth(getFirstDisplayedDate()));
return;
} else if (arrowType == MONTH_UP) {
setFirstDisplayedDate(
DateUtils.getNextMonth(getFirstDisplayedDate()));
return;
}
}
if (_selectionMode == NO_SELECTION) {
return;
}
if (id == MouseEvent.MOUSE_PRESSED) {
long selected = getDayAt(e.getX(), e.getY());
if (selected == -1) {
return;
}
// Update the selected dates.
_startSelectedDate = selected;
_endSelectedDate = selected;
if (_selectionMode == MULTIPLE_SELECTION ||
_selectionMode == WEEK_SELECTION) {
_pivotDate = selected;
}
// Determine the dirty rectangle of the new selected date so we
// draw the bounding box around it. This dirty rect includes the
// visual border of the selected date.
_cal.setTimeInMillis(selected);
calculateBoundsForDay(_bounds);
_cal.setTimeInMillis(_firstDisplayedDate);
// Repaint the old dirty area.
repaint(_dirtyRect);
// Repaint the new dirty area.
repaint(_bounds);
// Update the dirty area.
_dirtyRect.x = _bounds.x;
_dirtyRect.y = _bounds.y;
_dirtyRect.width = _bounds.width;
_dirtyRect.height = _bounds.height;
// Arm so we fire action performed on mouse release.
_asKirkWouldSay_FIRE = true;
} else if (id == MouseEvent.MOUSE_RELEASED) {
if (_asKirkWouldSay_FIRE) {
fireActionPerformed();
}
_asKirkWouldSay_FIRE = false;
}
super.processMouseEvent(e);
}
/**
* {@inheritDoc}
*/
@Override
protected void processMouseMotionEvent(MouseEvent e) {
if (!isEnabled() || _selectionMode == NO_SELECTION) {
return;
}
int id = e.getID();
if (id == MouseEvent.MOUSE_DRAGGED) {
int x = e.getX();
int y = e.getY();
long selected = getDayAt(x, y);
if (selected == -1) {
return;
}
long oldStart = _startSelectedDate;
long oldEnd = _endSelectedDate;
if (_selectionMode == SINGLE_SELECTION) {
if (selected == oldStart) {
return;
}
_startSelectedDate = selected;
_endSelectedDate = selected;
} else {
if (selected <= _pivotDate) {
_startSelectedDate = selected;
_endSelectedDate = _pivotDate;
} else if (selected > _pivotDate) {
_startSelectedDate = _pivotDate;
_endSelectedDate = selected;
}
}
if (_selectionMode == WEEK_SELECTION) {
// Do we span a week.
long start = (selected > _pivotDate) ? _pivotDate : selected;
long end = (selected > _pivotDate) ? selected : _pivotDate;
_cal.setTimeInMillis(start);
int count = 1;
while (_cal.getTimeInMillis() < end) {
_cal.add(Calendar.DAY_OF_MONTH, 1);
count++;
}
if (count > DAYS_IN_WEEK) {
// Move the start date to the first day of the week.
_cal.setTimeInMillis(start);
int dayOfWeek = _cal.get(Calendar.DAY_OF_WEEK);
int daysFromStart = dayOfWeek - _firstDayOfWeek;
if (daysFromStart < 0) {
daysFromStart += DAYS_IN_WEEK;
}
_cal.add(Calendar.DAY_OF_MONTH, -daysFromStart);
_startSelectedDate = _cal.getTimeInMillis();
// Move the end date to the last day of the week.
_cal.setTimeInMillis(end);
dayOfWeek = _cal.get(Calendar.DAY_OF_WEEK);
int lastDayOfWeek = _firstDayOfWeek - 1;
if (lastDayOfWeek == 0) {
lastDayOfWeek = Calendar.SATURDAY;
}
int daysTillEnd = lastDayOfWeek - dayOfWeek;
if (daysTillEnd < 0) {
daysTillEnd += DAYS_IN_WEEK;
}
_cal.add(Calendar.DAY_OF_MONTH, daysTillEnd);
_endSelectedDate = _cal.getTimeInMillis();
}
}
if (oldStart == _startSelectedDate && oldEnd == _endSelectedDate) {
return;
}
// Repaint the old dirty area.
repaint(_dirtyRect);
// Repaint the new dirty area.
calculateDirtyRectForSelection();
repaint(_dirtyRect);
// Set trigger.
_asKirkWouldSay_FIRE = true;
}
super.processMouseMotionEvent(e);
}
/**
* Class that supports keyboard traversal of the JXMonthView component.
*/
private class KeyboardAction extends AbstractAction {
public static final int SELECT_PREVIOUS_DAY = 0;
public static final int SELECT_NEXT_DAY = 1;
public static final int SELECT_DAY_PREVIOUS_WEEK = 2;
public static final int SELECT_DAY_NEXT_WEEK = 3;
public static final int ADD_PREVIOUS_DAY = 4;
public static final int ADD_NEXT_DAY = 5;
public static final int ADD_TO_PREVIOUS_WEEK = 6;
public static final int ADD_TO_NEXT_WEEK = 7;
private int mode;
public KeyboardAction(int mode) {
this.mode = mode;
}
public void actionPerformed(ActionEvent ev) {
if (_startSelectedDate != -1) {
if (mode >=0 && mode <= 3) {
if (getSelectionMode() >= SINGLE_SELECTION) {
traverse(mode);
}
} else if (mode >= 4 && mode <= 7) {
if (getSelectionMode() > SINGLE_SELECTION) {
addToSelection(mode);
}
}
}
}
private void traverse(int mode) {
_cal.setTimeInMillis(_startSelectedDate);
switch (mode) {
case SELECT_PREVIOUS_DAY:
_cal.add(Calendar.DAY_OF_MONTH, -1);
break;
case SELECT_NEXT_DAY:
_cal.add(Calendar.DAY_OF_MONTH, 1);
break;
case SELECT_DAY_PREVIOUS_WEEK:
_cal.add(Calendar.DAY_OF_MONTH, -7);
break;
case SELECT_DAY_NEXT_WEEK:
_cal.add(Calendar.DAY_OF_MONTH, 7);
break;
}
long newStartDate = _cal.getTimeInMillis();
if (newStartDate != _startSelectedDate) {
setSelectedDateSpan(new DateSpan(newStartDate, newStartDate));
ensureDateVisible(newStartDate);
}
// Restore the original time value.
_cal.setTimeInMillis(_firstDisplayedDate);
}
/**
* If we are in a mode that allows for range selection this method
* will extend the currently selected range.
*
* NOTE: This may not be the expected behavior for the keyboard controls
* and we ay need to update this code to act in a way that people expect.
*/
private void addToSelection(int mode) {
long newStartDate = _startSelectedDate;
long newEndDate = _endSelectedDate;
boolean isForward = true;
switch (mode) {
case ADD_PREVIOUS_DAY:
_cal.setTimeInMillis(_startSelectedDate);
_cal.add(Calendar.DAY_OF_MONTH, -1);
newStartDate = _cal.getTimeInMillis();
isForward = false;
break;
case ADD_NEXT_DAY:
_cal.setTimeInMillis(_endSelectedDate);
_cal.add(Calendar.DAY_OF_MONTH, 1);
newEndDate = _cal.getTimeInMillis();
break;
case ADD_TO_PREVIOUS_WEEK:
_cal.setTimeInMillis(_startSelectedDate);
_cal.add(Calendar.DAY_OF_MONTH, -7);
newStartDate = _cal.getTimeInMillis();
isForward = false;
break;
case ADD_TO_NEXT_WEEK:
_cal.setTimeInMillis(_endSelectedDate);
_cal.add(Calendar.DAY_OF_MONTH, 7);
newEndDate = _cal.getTimeInMillis();
break;
}
if (newStartDate != _startSelectedDate || newEndDate != _endSelectedDate) {
setSelectedDateSpan(new DateSpan(newStartDate, newEndDate));
ensureDateVisible(isForward ? newEndDate : newStartDate);
}
// Restore the original time value.
_cal.setTimeInMillis(_firstDisplayedDate);
}
}
}
|
package dialogs;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import components.ImageTableModel;
import components.PictogramTableCellRenderer;
import configuration.TConfiguration;
import configuration.TLanguage;
import database.DB;
import database.DBTasks;
public class ExportSearchFrame extends JDialog {
private JPanel contentPane;
private JTextField term1TextField, term2TextField, term3TextField, imageNameTextField;
private ImageTableModel imageTableModel;
private String[] imageTableHeader;
private JTable table;
private JComboBox AndOr1ComboBox, AndOr2ComboBox;
public final static int IS_INTEGRATED = 0;
private int mode = -1;
private String selectedImageName;
private ExportSearchFrame mainFrame;
private JProgressBar progressBar;
private String queryLoaded;
private JComboBox comboBox;
private JLabel labelTotalImages;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExportSearchFrame frame = new ExportSearchFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public ExportSearchFrame(int mode) {
this.mode = mode;
init();
}
public ExportSearchFrame() {
init();
}
/**
* Create the frame.
*/
private void init() {
TLanguage.initLanguage(TConfiguration.getLanguage());
/*
* imageTableHeader = new String[] {
* TLanguage.getString("EXPORT_SEARCH_FRAME.TITLE"),
* TLanguage.getString("EXPORT_SEARCH_FRAME.FILENAME"),
* TLanguage.getString("EXPORT_SEARCH_FRAME.ASSOCIATED_TERMS") };
*/
imageTableHeader = new String[] { "", "", "", "", "", "" };
this.mainFrame = this;
setTitle(TLanguage.getString("EXPORT_SEARCH_FRAME.TITLE"));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 720, 430);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, TLanguage.getString("EXPORT_SEARCH_FRAME.KEY_TERMS"),
TitledBorder.LEADING,
TitledBorder.TOP, null,
null));
contentPane.add(panel);
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
term1TextField = new JTextField();
panel.add(term1TextField);
term1TextField.setColumns(10);
AndOr1ComboBox = new JComboBox();
AndOr1ComboBox.setModel(new DefaultComboBoxModel(new String[] {
TLanguage.getString("EXPORT_SEARCH_FRAME.AND"),
TLanguage.getString("EXPORT_SEARCH_FRAME.OR") }));
panel.add(AndOr1ComboBox);
term2TextField = new JTextField();
panel.add(term2TextField);
term2TextField.setColumns(10);
AndOr2ComboBox = new JComboBox();
AndOr2ComboBox.setModel(new DefaultComboBoxModel(new String[] { TLanguage.getString("EXPORT_SEARCH_FRAME.AND"),
TLanguage.getString("EXPORT_SEARCH_FRAME.OR") }));
panel.add(AndOr2ComboBox);
term3TextField = new JTextField();
term3TextField.setColumns(10);
panel.add(term3TextField);
JButton btnBuscar = new JButton(TLanguage.getString("EXPORT_SEARCH_FRAME.FIND"));
btnBuscar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!term1TextField.getText().equals("")) {
String query = "SELECT COUNT(*) AS row_count, GROUP_CONCAT(main.word) AS terms, main.nameNN AS name FROM main WHERE main.name IN (SELECT main.name FROM main WHERE word LIKE '"
+ term1TextField.getText() + "'";
// Adding language when is not all
if (comboBox.getSelectedItem().toString()
.compareTo("Todos") != 0) {
query += " AND idL = (SELECT id FROM language WHERE name LIKE '"
+ comboBox.getSelectedItem().toString() + "')";
}
query += ")";
// Second textField
if (!term2TextField.getText().equals("")) {
query += AndOr1ComboBox.getSelectedIndex() == 0 ? " AND " : " OR ";
query += "main.name IN (SELECT main.name FROM main WHERE word LIKE '"
+ term2TextField.getText() + "'";
// Adding language when is not all
if (comboBox.getSelectedItem().toString()
.compareTo("Todos") != 0) {
query += " AND idL = (SELECT id FROM language WHERE name LIKE '"
+ comboBox.getSelectedItem().toString()
+ "')";
}
query += ")";
}
if (!term3TextField.getText().equals("")) {
query += AndOr2ComboBox.getSelectedIndex() == 0 ? " AND " : " OR ";
query += "main.name IN (SELECT main.name FROM main WHERE word LIKE '"
+ term3TextField.getText() + "'";
// Adding language when is not all
if (comboBox.getSelectedItem().toString()
.compareTo("Todos") != 0) {
query += " AND idL = (SELECT id FROM language WHERE name LIKE '"
+ comboBox.getSelectedItem().toString()
+ "')";
}
query += ")";
}
query += " GROUP BY main.name";
queryLoaded = query;
try {
DB db = DB.getInstance();
ResultSet rs = db.query(query);
prepareTermsTable(rs);
} catch (SQLException e) {
e.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null,
TLanguage.getString("EXPORT_SEARCH_FRAME.AT_LEAST_THREE_CHARACTERS_WARNING"),
TLanguage.getString("EXPORT_SEARCH_FRAME.AT_LEAST_THREE_CHARACTERS_WARNING_TITLE"),
JOptionPane.WARNING_MESSAGE);
}
}
});
panel.add(btnBuscar);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new TitledBorder(null, TLanguage.getString("EXPORT_SEARCH_FRAME.BY_IMAGE_NAME"),
TitledBorder.LEADING, TitledBorder.TOP,
null, null));
contentPane.add(panel_1);
JLabel lblNombre = new JLabel(TLanguage.getString("EXPORT_SEARCH_FRAME.NAME"));
panel_1.add(lblNombre);
imageNameTextField = new JTextField();
panel_1.add(imageNameTextField);
imageNameTextField.setColumns(30);
JButton btnBuscar_1 = new JButton(TLanguage.getString("EXPORT_SEARCH_FRAME.FIND"));
btnBuscar_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (imageNameTextField.getText().length() >= 3) {
try {
DB db = DB.getInstance();
String query = "SELECT COUNT(*) AS row_count, GROUP_CONCAT(main.word) AS terms, main.nameNN AS name FROM main WHERE main.name LIKE '"
+ imageNameTextField.getText()
+ "' GROUP BY nameNN";
queryLoaded = query;
ResultSet rs = db.query(query);
prepareTermsTable(rs);
} catch (SQLException e) {
e.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null,
TLanguage.getString("EXPORT_SEARCH_FRAME.AT_LEAST_THREE_CHARACTERS_WARNING"),
TLanguage.getString("EXPORT_SEARCH_FRAME.AT_LEAST_THREE_CHARACTERS_WARNING_TITLE"),
JOptionPane.WARNING_MESSAGE);
}
}
});
panel_1.add(btnBuscar_1);
JPanel panel_5 = new JPanel();
contentPane.add(panel_5);
JLabel lblIdiomaDeLa = new JLabel(
TLanguage.getString("FIND_IMAGE_FRAME.LANGUAGE_OF_THE_SEARCH"));
panel_5.add(lblIdiomaDeLa);
comboBox = new JComboBox();
// We insert all languages selected
comboBox.addItem("Todos");
comboBox.setSelectedIndex(0);
// Filling languages
String query = "SELECT name FROM language ORDER BY id asc";
try {
ResultSet rs = DB.getInstance().query(query);
int pos = 1;
while (rs.next()) {
comboBox.addItem(rs.getString("name"));
if (rs.getString("name")
.compareTo(TConfiguration.getLanguage()) == 0) {
comboBox.setSelectedIndex(pos);
}
pos++;
}
} catch (SQLException e) {
e.printStackTrace();
}
panel_5.add(comboBox);
JPanel panel_6 = new JPanel();
contentPane.add(panel_6);
JLabel lblNewLabel = new JLabel(
TLanguage.getString("FIND_IMAGE_FRAME.TOTAL_IMAGES_FOUND"));
panel_6.add(lblNewLabel);
labelTotalImages = new JLabel("0");
panel_6.add(labelTotalImages);
JPanel panel_2 = new JPanel();
panel_2.setLayout(new BorderLayout(0, 0));
panel_2.setBorder(new TitledBorder(null, TLanguage.getString("EXPORT_SEARCH_FRAME.RESULTS"),
TitledBorder.LEADING,
TitledBorder.TOP, null, null));
contentPane.add(panel_2);
/*
* imageTableModel = new DefaultTableModel(new Object[][] {},
* imageTableHeader) { public java.lang.Class<?> getColumnClass(int
* columnIndex) { return getValueAt(0, columnIndex).getClass(); };
*
* public boolean isCellEditable(int arg0, int arg1) { return false; };
* };
*/
imageTableModel = new ImageTableModel();
table = new JTable(imageTableModel);
table.setRowSelectionAllowed(false);
table.setDefaultRenderer(String.class, new PictogramTableCellRenderer());
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
String imageNameNN = ((ImageTableModel) table.getModel())
.getImageName(row, column);
selectedImageName = imageNameNN;
if (imageNameNN != null) {
if (e.getClickCount() == 2) {
if (mode == ExportSearchFrame.IS_INTEGRATED) {
mainFrame.dispose();
} else {
AddImageFrame f = new AddImageFrame(imageNameNN);
f.setVisible(true);
f.pack();
}
}
}
}
});
// Setting with & height
table.setRowHeight(100);
table.setSize(new Dimension(500, 100));
JScrollPane scrollPane = new JScrollPane(table);
panel_2.add(scrollPane);
JPanel panel_3 = new JPanel();
contentPane.add(panel_3);
if (mode == ExportSearchFrame.IS_INTEGRATED) {
JButton btnInsertar = new JButton(TLanguage.getString("EXPORT_SEARCH_FRAME.INSERT"));
panel_3.add(btnInsertar);
btnInsertar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (selectedImageName == null) {
JOptionPane.showMessageDialog(null,
TLanguage.getString("EXPORT_SEARCH_FRAME.AT_LEAST_THREE_CHARACTERS_WARNING"),
TLanguage.getString("EXPORT_SEARCH_FRAME.AT_LEAST_THREE_CHARACTERS_WARNING_TITLE"),
JOptionPane.WARNING_MESSAGE);
} else {
mainFrame.dispose();
}
}
});
}
JButton btnCancelar = new JButton(TLanguage.getString("EXPORT_SEARCH_FRAME.CANCEL"));
btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
mainFrame.dispose();
}
});
JButton btnExportarBsqueda = new JButton(TLanguage.getString("EXPORT_SEARCH_FRAME.EXPORT_SEARCH"));
panel_3.add(btnExportarBsqueda);
panel_3.add(btnCancelar);
JPanel panel_4 = new JPanel();
contentPane.add(panel_4);
btnExportarBsqueda.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (queryLoaded == null) {
JOptionPane.showMessageDialog(null,
TLanguage.getString("EXPORT_SEARCH_FRAME.YOU_SHOULD_SELECT_AN_IMAGE"),
TLanguage.getString("EXPORT_SEARCH_FRAME.AT_LEAST_THREE_CHARACTERS_WARNING_TITLE"),
JOptionPane.WARNING_MESSAGE);
} else {
final JFileChooser f = new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = f.showOpenDialog(contentPane);
if (returnVal == JFileChooser.APPROVE_OPTION) {
new Thread(new Runnable() {
@Override
public void run() {
mainFrame.setEnabled(false);
DBTasks.exportDB(f.getSelectedFile().getAbsolutePath(), progressBar, queryLoaded);
JOptionPane.showMessageDialog(contentPane,
TLanguage.getString("EXPORT_SEARCH_FRAME.IMPORT_OK"));
mainFrame.setEnabled(true);
progressBar.setValue(0);
}
}).start();
}
}
}
});
progressBar = new JProgressBar();
progressBar.setPreferredSize(new Dimension(680, 30));
panel_4.add(progressBar);
}
private void prepareTermsTable(ResultSet rs) {
try {
imageTableModel.setDataVector(null, imageTableHeader);
// Image resizedImage;
String imagePath = DB.getInstance().getImagesPath();
Vector<String> listNames = new Vector<String>();
int totalImages = 0;
while (rs.next()) {
listNames
.add(imagePath + File.separator + rs.getString("name"));
totalImages++;
}
// Updating total images found
this.labelTotalImages.setText(String.valueOf(totalImages));
imageTableModel.setData(listNames);
imageTableModel.fireTableDataChanged();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getSelectedImageName() {
return this.selectedImageName;
}
}
|
public class SinglyLinkedList<Item extends Comparable> {
private Node head;
private int size;
private class Node {
Item data;
Node next;
}
public void append(Item data) {
if (isEmpty()) {
head = new Node();
head.data = data;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = new Node();
current.next.data = data;
}
size++;
}
public void insert(Item data) {
if (isEmpty()) {
head = new Node();
head.data = data;
} else {
Node first = new Node();
first.data = data;
first.next = head;
head = first;
}
size++;
}
public Item remove(Item data) {
if (isEmpty()) {
throw new java.util.NoSuchElementException("The list is empty!");
} else {
if (head.data.compareTo(data) == 0) {
Item victim = head.data;
head = head.next;
size
return victim;
} else {
Node current = head;
while (current.next != null) {
if (current.next.data.compareTo(data) == 0) {
Item victim = current.next.data;
current.next = current.next.next;
size
return victim;
}
current = current.next;
}
return null;
}
}
}
public Item nthFromEnd(int n) {
if (n > size) {
return null;
}
Node ahead = head;
Node behind = head;
for (int i = 0; i < n; i++) {
ahead = ahead.next;
}
while (ahead != null) {
behind = behind.next;
ahead = ahead.next;
}
return behind.data;
}
public boolean isEmpty() {
return head == null;
}
public int size() {
return size;
}
public boolean contains(Item data) {
Node current = head;
while (current != null) {
if (current.data.compareTo(data) == 0) {
return true;
} else {
current = current.next;
}
}
return false;
}
public Item getMiddle() {
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow.data;
}
public void deleteList() {
head = null;
}
public int countOccurences(Item data) {
nullCheck(data);
Node current = head;
int count = 0;
while (current != null) {
if (current.data.compareTo(data) == 0) {
count++;
}
current = current.next;
}
return count;
}
public boolean hasLoop() {
Node slow = head;
Node fast = head.next;
while (slow != null && fast != null && fast.next != null) {
if (slow == fast) {
return true;
} else {
slow = slow.next;
fast = fast.next;
}
}
return false;
}
public void reverse() {
if (size == 1 || isEmpty()) {
return;
}
Node current = head;
Node next = head;
Node previous = null;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
head = previous;
}
public boolean isPalindrome() {
if (isEmpty() || size == 1) {
return true;
}
Node slow = head;
Node fast = head.next;
while (slow != null && fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
Node previous = null;
Node current = head;
Node next = head;
Node flag = slow.next;
while (current != flag) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
if (fast == null){
previous = previous.next;
}
while (previous != null && current != null) {
if (previous.data.compareTo(current.data) != 0) {
return false;
} else {
previous = previous.next;
current = current.next;
}
}
return true;
}
public void sortedInsert(Item data) {
nullCheck(data);
if (isEmpty()) {
head = new Node();
head.data = data;
} else {
Node lower = head;
Node higher = head.next;
while (lower != null) {
if ((higher == null) ||
(data.compareTo(lower.data) >= 0) && (data.compareTo(higher.data) <= 0)) {
Node n = new Node();
n.data = data;
n.next = higher;
lower.next = n;
return;
} else if (data.compareTo(lower.data) <= 0) {
Node n = new Node();
n.data = data;
n.next = lower;
if (lower == head) {
head = n; // If lower is head, reset head
}
return;
}
lower = lower.next;
higher = higher.next;
}
}
size++;
}
private Node intersectionPoint(Node head1, Node head2) {
if (head1 == null || head2 == null) {
return null;
}
Node firstHead = head1;
Node secondHead = head2;
int firstLength = 0;
int secondLength = 0;
while (firstHead != null || secondHead != null) {
if (firstHead == null) {
secondHead = secondHead.next;
secondLength++;
} else if (secondHead == null) {
firstHead = firstHead.next;
firstLength++;
} else {
firstHead = firstHead.next;
secondHead = secondHead.next;
firstLength++;
secondLength++;
}
}
firstHead = head1;
secondHead = head2;
if (firstLength > secondLength) {
int difference = firstLength-secondLength;
while (difference != 0) {
firstHead = firstHead.next;
difference
}
} else if (secondLength > firstLength) {
int difference = secondLength-firstLength;
while (difference != 0) {
secondHead = secondHead.next;
difference
}
}
while (firstHead != null && secondHead != null) {
if (firstHead == secondHead) {
return firstHead;
}
}
return null; // If the lists are not connected
}
public void removeDuplicates() {
if (isEmpty() || size == 1) {
return;
} else {
Node second = head;
Node first = head.next;
while (first != null) {
if (second.data.compareTo(first.data) == 0) {
while (first != null && second.data.compareTo(first.data) == 0) {
first = first.next;
}
second.next = first;
} else {
first = first.next;
second = second.next;
}
}
}
}
public void moveLastToFront() {
Node current = head;
while (current.next.next != null) {
current = current.next;
}
Item data = current.next.data;
current.next = null;
Node first = new Node();
first.data = data;
first.next = head;
head = first;
}
public void deleteAlternateElements() {
Node current = head;
while (current != null && current.next != null) {
current.next = current.next.next;
current = current.next;
}
}
public void alternatingSplit() {
SinglyLinkedList<Item> odds = new SinglyLinkedList<Item>();
SinglyLinkedList<Item> evens = new SinglyLinkedList<Item>();
Node odd = head;
Node even = head.next;
if (size % 2 == 0) {
while (even.next != null) {
odds.append(odd.data);
evens.append(even.data);
odd = odd.next.next;
even = even.next.next;
}
odds.append(odd.data);
evens.append(even.data);
} else {
while (odd.next != null) {
odds.append(odd.data);
evens.append(even.data);
odd = odd.next.next;
even = even.next.next;
}
odds.append(odd.data);
}
System.out.println("Odds: " + odds);
System.out.println("Evens: " + evens);
}
public void printReverse() {
if (size == 1 || isEmpty()) {
return;
}
printReverse(head);
}
private void printReverse(Node current) {
if (current.next == null) {
System.out.print("[ " + current.data + ", ");
} else {
printReverse(current.next);
System.out.print(current.data + (current == head ? " ]\n" : ", "));
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
if (isEmpty()) {
sb.append("[]");
} else {
sb.append("[ ");
for (Node cur = head; cur != null; cur = cur.next) {
if (cur.next != null) {
sb.append(cur.data + ", ");
} else {
sb.append(cur.data + " ]");
}
}
}
return sb.toString();
}
/* Helper Methods */
private void nullCheck(Item data) {
if (data == null) {
throw new NullPointerException("Null items are not allowed in the list.");
}
}
private void emptyCheck() {
if (isEmpty()) {
throw new java.util.NoSuchElementException("Cannot remove from empty list!");
}
}
/* For testing purposes */
public static void main(String[] args) {
SinglyLinkedList<String> animals = new SinglyLinkedList<String>();
System.out.println("List is initially empty: " + animals);
animals.append("cat");
animals.append("dog");
animals.append("horse");
animals.append("pigeon");
animals.append("fish");
animals.append("seagull");
System.out.println("After adding some animals: " + animals);
animals.reverse();
System.out.println("Reversed the list: " + animals);
System.out.println("Middle element: " + animals.getMiddle());
System.out.println("Does the list contain pigeon? " + animals.contains("pigeon"));
System.out.println("Does the list contain BMW? " + animals.contains("BMW"));
System.out.println("The size of the list is: " + animals.size());
System.out.println("2nd from end: " + animals.nthFromEnd(2));
animals.deleteList();
System.out.println("Deleted list: " + animals);
palindromeTest(animals);
animals.deleteList();
System.out.print("Appending cat, dog, horse, pigeon, fish and seagull: ");
animals.append("cat");
animals.append("dog");
animals.append("horse");
animals.append("pigeon");
animals.append("fish");
animals.append("seagull");
System.out.println(animals);
System.out.print("Printing the reverse of the list recursively: ");
animals.printReverse();
SinglyLinkedList<Integer> numbers = new SinglyLinkedList<Integer>();
numbers.append(1);
numbers.append(2);
numbers.append(3);
numbers.append(5);
System.out.println("looking at new list of numbers:" + numbers);
sortedInsertTest(numbers);
numbers.removeDuplicates();
System.out.println("Removed duplicates from sorted list: " + numbers);
numbers.moveLastToFront();
System.out.println("Moved last element to the front:" + numbers);
numbers.deleteAlternateElements();
System.out.println("Delete alternate elements:" + numbers);
alternatingSplitTest();
}
public static void palindromeTest(SinglyLinkedList<String> list) {
list.append("A");
list.append("B");
list.append("C");
System.out.println("Is the list " + list + " a palindrome? " + list.isPalindrome());
list.deleteList();
list.append("A");
list.append("B");
list.append("C");
list.append("B");
list.append("A");
System.out.println("Is the list " + list + " a palindrome? " + list.isPalindrome());
list.deleteList();
list.append("A");
list.append("B");
list.append("C");
list.append("C");
list.append("B");
list.append("A");
System.out.println("Is the list " + list + " a palindrome? " + list.isPalindrome());
}
public static void sortedInsertTest(SinglyLinkedList<Integer> list) {
for (int i = 0; i < 2; i++) {
System.out.print("Insert 4 in sorted order into the list: ");
list.sortedInsert(4);
System.out.println(list);
}
for (int i = 0; i < 4; i++) {
System.out.print("Inserting 6 in sorted order into the list: ");
list.sortedInsert(6);
System.out.println(list);
}
System.out.print("Inserting 0 in sorted order into the list: ");
list.sortedInsert(0);
System.out.println(list);
}
public static void alternatingSplitTest() {
SinglyLinkedList<Integer> list = new SinglyLinkedList<Integer>();
for (int i = 0; i < 11; i++) {
if (i % 2 == 0) {
list.append(1);
} else {
list.append(0);
}
}
System.out.println("Original list of elements: " + list);
list.alternatingSplit();
}
}
|
package gov.nih.nci.cabig.caaers.domain;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.CaaersTestCase;
import static gov.nih.nci.cabig.caaers.CaaersUseCase.CREATE_EXPEDITED_REPORT;
import gov.nih.nci.cabig.caaers.CaaersUseCases;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;
/**
* @author Rhett Sutphin
*/
@CaaersUseCases({CREATE_EXPEDITED_REPORT})
public class ExpeditedAdverseEventReportTest extends CaaersTestCase {
private static final Timestamp CREATED_AT = DateTools.createTimestamp(2006, Calendar.MAY, 8, 9,
8, 7);
private ExpeditedAdverseEventReport report;
private BeanWrapper wrappedReport;
private CtcTerm ctcTerm;
private AdverseEvent adverseEvent;
private StudyParticipantAssignment assignment;
private AdverseEventReportingPeriod reportingPeriod;
private String publicId;
@Override
protected void setUp() throws Exception {
super.setUp();
report = new ExpeditedAdverseEventReport();
report.setCreatedAt(CREATED_AT);
publicId = "str id";
report.setPublicIdentifier(publicId);
adverseEvent = new AdverseEvent();
report.addAdverseEvent(adverseEvent);
adverseEvent.setGrade(Grade.MODERATE);
ctcTerm = new CtcTerm();
ctcTerm.setTerm("Term");
ctcTerm.setCtepTerm("CTEP term");
ctcTerm.setSelect("Select");
ctcTerm.setOtherRequired(false);
adverseEvent.getAdverseEventCtcTerm().setCtcTerm(this.ctcTerm);
report.setReportingPeriod(Fixtures.createReportingPeriod());
wrappedReport = new BeanWrapperImpl(report);
assignment = new StudyParticipantAssignment();
assignment.addConcomitantMedication(new StudyParticipantConcomitantMedication());
assignment.addPriorTherapy(new StudyParticipantPriorTherapy());
assignment.addPreExistingCondition(new StudyParticipantPreExistingCondition());
StudyParticipantDiseaseHistory studyParticipantDiseaseHistory = new StudyParticipantDiseaseHistory();
studyParticipantDiseaseHistory.addMetastaticDiseaseSite(new StudyParticipantMetastaticDiseaseSite());
assignment.setDiseaseHistory(studyParticipantDiseaseHistory);
reportingPeriod = new AdverseEventReportingPeriod();
reportingPeriod.setAssignment(assignment);
}
public void testCopyLab() {
// report.addLab(new Lab());
// assertFalse(report.getLabs().isEmpty());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertEquals(1, copiedReport.getLabs().size());
// for (Lab object : copiedReport.getLabs()) {
// assertSame("must change reference", copiedReport, object.getReport());
}
public void testAdverseEvents() {
// assertFalse(report.getAdverseEvents().isEmpty());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertEquals(report.getAdverseEvents().size(), copiedReport.getAdverseEvents().size());
// for (AdverseEvent event : copiedReport.getAdverseEvents()) {
// assertSame("must change reference", copiedReport, event.getReport());
assertTrue(true);
}
public void testPriorTherapies() {
// report.addSaeReportPriorTherapies(new SAEReportPriorTherapy());
// assertFalse(report.getSaeReportPriorTherapies().isEmpty());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertEquals(report.getSaeReportPriorTherapies().size(), copiedReport.getSaeReportPriorTherapies().size());
// for (SAEReportPriorTherapy priorTherapy : copiedReport.getSaeReportPriorTherapies()) {
// assertSame("must change reference", copiedReport, priorTherapy.getReport());
assertTrue(true);
}
public void testTreatmentInformation() {
// report.setTreatmentInformation(new TreatmentInformation());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertNotNull(copiedReport.getTreatmentInformation());
// assertSame("must change reference", copiedReport, copiedReport.getTreatmentInformation().getReport());
assertTrue(true);
}
public void testCopyPhysician() {
// report.setPhysician(new Physician());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertNotNull(copiedReport.getPhysician());
// assertSame("must change reference", copiedReport, copiedReport.getPhysician().getExpeditedReport());
assertTrue(true);
}
public void testCopyReporter() {
// report.setReporter(new Reporter());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertNotNull(copiedReport.getReporter());
// assertSame("must change reference", copiedReport, copiedReport.getReporter().getExpeditedReport());
assertTrue(true);
}
public void testCopyAdditionalInformation() {
// report.setAdditionalInformation(new AdditionalInformation());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertNotNull(copiedReport.getAdditionalInformation());
// assertSame("must change reference", copiedReport, copiedReport.getAdditionalInformation().getReport());
assertTrue(true);
}
public void testCopyResponseDescription() {
// report.setResponseDescription(new AdverseEventResponseDescription());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertNotNull(copiedReport.getResponseDescription());
// assertSame("must change reference", copiedReport, copiedReport.getResponseDescription().getReport());
assertTrue(true);
}
public void testCopyDiseaseHistory() {
// report.setDiseaseHistory(new DiseaseHistory());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertNotNull(copiedReport.getDiseaseHistory());
// assertSame("must change reference", copiedReport, copiedReport.getDiseaseHistory().getReport());
assertTrue(true);
}
public void testCopyParticipantHistory() {
// report.setParticipantHistory(new ParticipantHistory());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertNotNull(copiedReport.getParticipantHistory());
// assertSame("must change reference", copiedReport, copiedReport.getParticipantHistory().getReport());
assertTrue(true);
}
public void testCopyMedicalDevices() {
// report.addMedicalDevice(new MedicalDevice());
// assertFalse(report.getMedicalDevices().isEmpty());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertEquals(1, copiedReport.getMedicalDevices().size());
// for (MedicalDevice object : copiedReport.getMedicalDevices()) {
// assertSame("must change reference", copiedReport, object.getReport());
assertTrue(true);
}
public void testCopyPreExistingConditions() {
// report.addSaeReportPreExistingCondition(new SAEReportPreExistingCondition());
// assertFalse(report.getSaeReportPreExistingConditions().isEmpty());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertEquals(1, copiedReport.getSaeReportPreExistingConditions().size());
// for (SAEReportPreExistingCondition object : copiedReport.getSaeReportPreExistingConditions()) {
// assertSame("must change reference", copiedReport, object.getReport());
assertTrue(true);
}
public void testCopyOtherCauses() {
// report.addOtherCause(new OtherCause());
// assertFalse(report.getOtherCauses().isEmpty());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertEquals(1, copiedReport.getOtherCauses().size());
// for (OtherCause object : copiedReport.getOtherCauses()) {
// assertSame("must change reference", copiedReport, object.getReport());
assertTrue(true);
}
public void testCopyRadiationIntervention() {
// report.addRadiationIntervention(new RadiationIntervention());
// assertFalse(report.getRadiationInterventions().isEmpty());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertEquals(1, copiedReport.getRadiationInterventions().size());
// for (RadiationIntervention object : copiedReport.getRadiationInterventions()) {
// assertSame("must change reference", copiedReport, object.getReport());
assertTrue(true);
}
public void testCopySurgeryIntervention() {
// report.addSurgeryIntervention(new SurgeryIntervention());
// assertFalse(report.getSurgeryInterventions().isEmpty());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertEquals(report.getSurgeryInterventions().size(), copiedReport.getSurgeryInterventions().size());
// for (SurgeryIntervention object : copiedReport.getSurgeryInterventions()) {
// assertSame("must change reference", copiedReport, object.getReport());
assertTrue(true);
}
public void testCopyConMed() {
// report.addConcomitantMedication(new ConcomitantMedication());
// assertFalse(report.getConcomitantMedications().isEmpty());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertEquals(1, copiedReport.getConcomitantMedications().size());
// for (ConcomitantMedication concomitantMedication : copiedReport.getConcomitantMedications()) {
// assertSame("must change reference", copiedReport, concomitantMedication.getReport());
assertTrue(true);
}
public void testMustNotCopyReports() {
// report.addReport(new Report());
// assertFalse(report.getReports().isEmpty());
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertTrue("must not copy report", copiedReport.getReports().isEmpty());
}
// public void testCopyBasicProperties() {
// ExpeditedAdverseEventReport copiedReport = report.copy();
// assertNull("must not copy id", copiedReport.getId());
// assertNull("must not copy version ", copiedReport.getGridId());
// assertNull("must not copy grid id", copiedReport.getVersion());
// assertEquals(report.getReportingPeriod(), copiedReport.getReportingPeriod());
// assertSame(report.getReportingPeriod(), copiedReport.getReportingPeriod());
// assertEquals(report.getReportingPeriod().getAssignment(), copiedReport.getAssignment());
// assertSame(report.getReportingPeriod().getAssignment(), copiedReport.getAssignment());
// assertEquals(CREATED_AT, copiedReport.getCreatedAt());
// assertEquals(report.getPublicIdentifier(), copiedReport.getPublicIdentifier());
public void testWrongUsesOfSyncrhonizeMethod() {
report.setAssignment(null);
String message = String.format("Must set assignment before calling synchronizeMedicalHistoryFromAssignmentToReport");
try {
report.synchronizeMedicalHistoryFromAssignmentToReport();
fail();
} catch (CaaersSystemException e) {
assertEquals(message, e.getMessage());
}
}
public void testSyncrhonizePriorTherapies() {
report.setReportingPeriod(reportingPeriod);
report.synchronizeMedicalHistoryFromAssignmentToReport();
assertEquals("must copy the prior therapy", 1, report.getSaeReportPriorTherapies().size());
report.synchronizeMedicalHistoryFromAssignmentToReport();
assertEquals("must not copy prior therapy twice", 1, report.getSaeReportPriorTherapies().size());
}
public void testSyncrhonizeDiseaseHistory() {
report.setReportingPeriod(reportingPeriod);
report.synchronizeMedicalHistoryFromAssignmentToReport();
assertNotNull("must copy the diseaseHistory", report.getDiseaseHistory());
assertEquals("must copy the MetastaticDiseaseSite", 1, report.getDiseaseHistory().getMetastaticDiseaseSites().size());
report.synchronizeMedicalHistoryFromAssignmentToReport();
assertNotNull("must not copy the diseaseHistory twice", report.getDiseaseHistory());
assertEquals("must copy the MetastaticDiseaseSite twice", 1, report.getDiseaseHistory().getMetastaticDiseaseSites().size());
}
public void testSyncrhonizePreExistingCondition() {
report.setReportingPeriod(reportingPeriod);
report.synchronizeMedicalHistoryFromAssignmentToReport();
assertEquals("must copy the pre existing condition", 1, report.getSaeReportPreExistingConditions().size());
report.synchronizeMedicalHistoryFromAssignmentToReport();
assertEquals("must not copy the pre existing condition twice", 1, report.getSaeReportPreExistingConditions().size());
}
public void testSyncrhonizeConcomitantMedication() {
report.setReportingPeriod(reportingPeriod);
report.synchronizeMedicalHistoryFromAssignmentToReport();
assertEquals("must copy the concomitantMedication", 1, report.getConcomitantMedications().size());
report.synchronizeMedicalHistoryFromAssignmentToReport();
assertEquals("must not copy the concomitantMedication twice", 1, report.getConcomitantMedications().size());
}
public void testGetAdverseEventNeverThrowsIndexOutOfBounds() throws Exception {
AdverseEvent e4 = report.getAdverseEvents().get(4);
assertNotNull(e4);
assertSame(report, e4.getReport());
}
public void testSetAdverseEventsInternalReflectedInAdverseEvents() throws Exception {
report.setAdverseEventsInternal(new ArrayList<AdverseEvent>(Arrays.asList(Fixtures.setId(
10, new AdverseEvent()), Fixtures.setId(12, new AdverseEvent()), Fixtures
.setId(14, new AdverseEvent()))));
assertEquals(10, (int) report.getAdverseEvents().get(0).getId());
assertEquals(12, (int) report.getAdverseEvents().get(1).getId());
assertEquals(14, (int) report.getAdverseEvents().get(2).getId());
}
public void testDynamicallyCreatedAdverseEventsInInternal() throws Exception {
AdverseEvent e4 = report.getAdverseEvents().get(4);
assertSame(e4, report.getAdverseEventsInternal().get(4));
}
public void testGetLabNeverThrowsIndexOutOfBounds() throws Exception {
Lab l4 = report.getLabs().get(4);
assertNotNull(l4);
assertSame(report, l4.getReport());
}
public void testSetLabsInternalReflectedInLabs() throws Exception {
report.setLabsInternal(new ArrayList<Lab>(Arrays.asList(Fixtures.setId(10, new Lab()),
Fixtures.setId(12, new Lab()), Fixtures.setId(14, new Lab()))));
assertEquals(10, (int) report.getLabs().get(0).getId());
assertEquals(12, (int) report.getLabs().get(1).getId());
assertEquals(14, (int) report.getLabs().get(2).getId());
}
public void testDynamicallyCreatedLabsInInternal() throws Exception {
Lab l4 = report.getLabs().get(4);
assertSame(l4, report.getLabsInternal().get(4));
}
public void testGetConMedNeverThrowsIndexOutOfBounds() throws Exception {
ConcomitantMedication cm4 = report.getConcomitantMedications().get(4);
assertNotNull(cm4);
assertSame(report, cm4.getReport());
}
public void testNotificationMessage() throws Exception {
assertEquals("Grade 2 adverse event with term Term - Select", report
.getNotificationMessage());
}
public void testNotificationMessageWithOther() throws Exception {
ctcTerm.setOtherRequired(true);
adverseEvent.setDetailsForOther("other");
assertEquals("Grade 2 adverse event with term Term - Select (other)", report
.getNotificationMessage());
}
public void testNotificationMessageExceptionForNoAe() throws Exception {
report.getAdverseEventsInternal().clear();
assertFalse(report.isNotificationMessagePossible());
try {
report.getNotificationMessage();
fail("Exception not thrown");
} catch (CaaersSystemException cse) {
assertEquals("Cannot create notification message until primary AE is filled in", cse
.getMessage());
}
}
public void testNotificationMessageExceptionForNoGrade() throws Exception {
adverseEvent.setGrade(null);
assertFalse(report.isNotificationMessagePossible());
try {
report.getNotificationMessage();
fail("Exception not thrown");
} catch (CaaersSystemException cse) {
assertEquals("Cannot create notification message until primary AE is filled in", cse
.getMessage());
}
}
public void testNotificationMessageExceptionForNoTerm() throws Exception {
adverseEvent.getAdverseEventCtcTerm().setCtcTerm(null);
assertFalse(report.isNotificationMessagePossible());
try {
report.getNotificationMessage();
fail("Exception not thrown");
} catch (CaaersSystemException cse) {
assertEquals("Cannot create notification message until primary AE is filled in", cse
.getMessage());
}
}
public void testSummaryIncludesStudy() throws Exception {
Participant participant = Fixtures.createParticipant("Joe", "Shabadoo");
Study study = Fixtures.createStudy("El Study");
report.setAssignment(Fixtures.assignParticipant(participant, study, Fixtures.SITE));
Map<String, String> summary = report.getSummary();
assertEquals("El Study", summary.get("Study"));
}
public void testSummaryStudyIncludesPrimaryIdentifier() throws Exception {
Participant participant = Fixtures.createParticipant("Joe", "Shabadoo");
Study study = Fixtures.createStudy("El Study");
study.addIdentifier(Identifier.createTemplate("1845"));
study.getIdentifiers().get(0).setPrimaryIndicator(true);
report.setAssignment(Fixtures.assignParticipant(participant, study, Fixtures.SITE));
Map<String, String> summary = report.getSummary();
assertEquals("El Study (1845)", summary.get("Study"));
}
public void testSummaryIncludesParticipant() throws Exception {
Participant participant = Fixtures.createParticipant("Joe", "Shabadoo");
Study study = Fixtures.createStudy("El Study");
report.setAssignment(Fixtures.assignParticipant(participant, study, Fixtures.SITE));
Map<String, String> summary = report.getSummary();
assertEquals("Joe Shabadoo", summary.get("Participant"));
}
public void testSummaryParticipantIncludesPrimaryIdentifier() throws Exception {
Participant participant = Fixtures.createParticipant("Joe", "Shabadoo");
participant.addIdentifier(Identifier.createTemplate("MRN1138"));
participant.getIdentifiers().get(0).setPrimaryIndicator(true);
Study study = Fixtures.createStudy("El Study");
report.setAssignment(Fixtures.assignParticipant(participant, study, Fixtures.SITE));
Map<String, String> summary = report.getSummary();
assertEquals("Joe Shabadoo (MRN1138)", summary.get("Participant"));
}
public void testSummaryIncludesFirstAETerm() throws Exception {
Map<String, String> summary = report.getSummary();
assertEquals("Term - Select", summary.get("Primary AE"));
}
public void testSummaryIncludesAECount() throws Exception {
Map<String, String> summary = report.getSummary();
assertEquals("1", summary.get("AE count"));
}
public void testSummaryIncludesCreatedAt() throws Exception {
Map<String, String> summary = report.getSummary();
assertEquals("2006-05-08 09:08:07.0", summary.get("Report created at"));
}
public void testTreatmentInformationNeverNull() throws Exception {
assertChildNeverNull("treatmentInformation");
}
public void testResponseNeverNull() throws Exception {
assertChildNeverNull("responseDescription");
}
public void testParticipantHistoryNeverNull() throws Exception {
assertChildNeverNull("participantHistory");
}
public void testDiseaseHistoryNeverNull() throws Exception {
assertChildNeverNull("diseaseHistory");
}
private void assertChildNeverNull(String childProp) {
assertNotNull(childProp + " null initially", wrappedReport.getPropertyValue(childProp));
wrappedReport.setPropertyValue(childProp, null);
ExpeditedAdverseEventReportChild actual = (ExpeditedAdverseEventReportChild) wrappedReport
.getPropertyValue(childProp);
assertNotNull(childProp + " not reinited after set null", actual);
assertSame("Reverse link not set", report, actual.getReport());
}
public void testExpeditedRequiredReportWhenReqd() throws Exception {
report.addReport(new Report());
report.addReport(new Report());
Report reqd = new Report();
reqd.setRequired(true);
report.addReport(reqd);
assertTrue(report.isExpeditedReportingRequired());
}
public void testExpeditedRequiredReportWhenNotReqd() throws Exception {
report.addReport(new Report());
report.addReport(new Report());
report.addReport(new Report());
assertFalse(report.isExpeditedReportingRequired());
}
public void testRequiredReportCount() throws Exception {
report.addReport(new Report());
report.addReport(new Report());
Report reqd = new Report();
reqd.setRequired(true);
report.addReport(reqd);
assertEquals(1, report.getRequiredReportCount());
}
public void testGetSponsorDefinedReports() throws Exception {
Report rep = new Report();
ReportDefinition reportDefinition = Fixtures.createReportDefinition("defn1", "NCI-CODE1");
rep.setReportDefinition(reportDefinition);
report.addReport(rep);
rep = new Report();
reportDefinition = Fixtures.createReportDefinition("defn2", "NCI-CODE2");
rep.setReportDefinition(reportDefinition);
report.addReport(rep);
rep = new Report();
reportDefinition = Fixtures.createReportDefinition("defn3", "NCI-CODE1");
rep.setReportDefinition(reportDefinition);
report.addReport(rep);
Participant participant = Fixtures.createParticipant("Joe", "Shabadoo");
Study study = Fixtures.createStudy("El Study");
Organization org = Fixtures.createOrganization("test Org");
org.setNciInstituteCode("NCI-CODE1");
StudyFundingSponsor sponsor = Fixtures.createStudyFundingSponsor(org);
sponsor.setPrimary(true);
study.addStudyFundingSponsor(sponsor);
report.setAssignment(Fixtures.assignParticipant(participant, study, Fixtures.SITE));
assertEquals(2, report.getSponsorDefinedReports().size());
}
public void testGetAllSponsorReportsCompleted() throws Exception {
Report rep = new Report();
Fixtures.createReportVersion(rep);
rep.getLastVersion().setReportStatus(ReportStatus.PENDING);
ReportDefinition reportDefinition = Fixtures.createReportDefinition("defn1", "NCI-CODE1");
reportDefinition.setExpedited(true);
rep.setReportDefinition(reportDefinition);
report.addReport(rep);
rep = new Report();
Fixtures.createReportVersion(rep);
rep.getLastVersion().setReportStatus(ReportStatus.PENDING);
reportDefinition = Fixtures.createReportDefinition("defn2", "NCI-CODE2");
reportDefinition.setExpedited(true);
rep.setReportDefinition(reportDefinition);
report.addReport(rep);
rep = new Report();
Fixtures.createReportVersion(rep);
rep.getLastVersion().setReportStatus(ReportStatus.WITHDRAWN);
reportDefinition = Fixtures.createReportDefinition("defn3", "NCI-CODE1");
reportDefinition.setExpedited(true);
rep.setReportDefinition(reportDefinition);
report.addReport(rep);
Participant participant = Fixtures.createParticipant("Joe", "Shabadoo");
Study study = Fixtures.createStudy("El Study");
Organization org = Fixtures.createOrganization("test Org");
org.setNciInstituteCode("NCI-CODE1");
StudyFundingSponsor sponsor = Fixtures.createStudyFundingSponsor(org);
sponsor.setPrimary(true);
study.addStudyFundingSponsor(sponsor);
report.setAssignment(Fixtures.assignParticipant(participant, study, Fixtures.SITE));
assertFalse(report.getAllSponsorReportsCompleted());
}
public void testGetEarliestPendingSponsorReport() throws Exception {
Report rep = new Report();
Fixtures.createReportVersion(rep);
rep.getLastVersion().setReportStatus(ReportStatus.PENDING);
rep.setDueOn(new Timestamp(300));
ReportDefinition reportDefinition = Fixtures.createReportDefinition("defn1", "NCI-CODE1");
rep.setReportDefinition(reportDefinition);
report.addReport(rep);
rep = new Report();
Fixtures.createReportVersion(rep);
rep.getLastVersion().setReportStatus(ReportStatus.PENDING);
reportDefinition = Fixtures.createReportDefinition("defn2", "NCI-CODE2");
rep.setReportDefinition(reportDefinition);
report.addReport(rep);
rep = new Report();
Fixtures.createReportVersion(rep);
rep.getLastVersion().setReportStatus(ReportStatus.PENDING);
rep.setDueOn(new Timestamp(200));
reportDefinition = Fixtures.createReportDefinition("defn3", "NCI-CODE1");
rep.setReportDefinition(reportDefinition);
report.addReport(rep);
Participant participant = Fixtures.createParticipant("Joe", "Shabadoo");
Study study = Fixtures.createStudy("El Study");
Organization org = Fixtures.createOrganization("test Org");
org.setNciInstituteCode("NCI-CODE1");
StudyFundingSponsor sponsor = Fixtures.createStudyFundingSponsor(org);
sponsor.setPrimary(true);
study.addStudyFundingSponsor(sponsor);
report.setAssignment(Fixtures.assignParticipant(participant, study, Fixtures.SITE));
assertEquals(report.getReports().get(2), report.getEarliestPendingSponsorReport());
}
}
|
package com.jiahaoliuliu.pubnubaschatsystem;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import com.pubnub.api.Callback;
import com.pubnub.api.Pubnub;
import com.pubnub.api.PubnubError;
import com.pubnub.api.PubnubException;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String DEFAULT_CHANNEL_NAME = "PubNubDefaultChannel";
// Views
private CoordinatorLayout mCoordinatorLayout;
// Internal variables
private Pubnub mPubNub;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Link the views
mCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.main_coordinator_layout);
// Internal variables
mPubNub = new Pubnub(APIKeys.PUBNUB_PUBLISH_KEY, APIKeys.PUBNUB_SUBSCRIBE_KEY);
// Subscribing to the channel
try {
mPubNub.subscribe(DEFAULT_CHANNEL_NAME, new Callback() {
@Override
public void successCallback(String channel, Object message) {
Log.v(TAG, "Message received from channel " + channel + ": " + message);
}
@Override
public void errorCallback(String channel, PubnubError error) {
Log.v(TAG, "Error callback(" + error.errorCode + "):" + error.getErrorString());
}
@Override
public void connectCallback(String channel, Object message) {
Log.v(TAG, "Connect callback");
Snackbar.make
(mCoordinatorLayout,
"Correctly subscribed to the default channel",
Snackbar.LENGTH_LONG).show();
}
@Override
public void reconnectCallback(String channel, Object message) {
Log.v(TAG, "Reconnect callback");
}
@Override
public void disconnectCallback(String channel, Object message) {
Log.v(TAG, "Disconnect callback");
}
});
} catch (PubnubException pubnubException) {
Log.e(TAG, "Error with the channel channel in PubNub");
}
// Publish a simple message
mPubNub.publish(DEFAULT_CHANNEL_NAME, "Simple message", new Callback() {
@Override
public void successCallback(String channel, Object message) {
Log.v(TAG, "Message correctly published");
Snackbar.make(mCoordinatorLayout, "Message correctly published", Snackbar.LENGTH_SHORT);
}
@Override
public void errorCallback(String channel, PubnubError error) {
Log.e(TAG, "Error publishing the message(" + error.errorCode + "):" + error.getErrorString());
}
});
}
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// // Handle action bar item clicks here. The action bar will
// // automatically handle clicks on the Home/Up button, so long
// // as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// return super.onOptionsItemSelected(item);
}
|
package com.github.terma.gigaspacesqlconsole.provider;
import com.gigaspaces.client.WriteModifiers;
import com.gigaspaces.document.SpaceDocument;
import com.github.terma.gigaspacesqlconsole.core.ExecuteRequest;
import com.github.terma.gigaspacesqlconsole.core.ExecuteResponseStream;
import java.io.IOException;
import java.util.Map;
import static java.util.Arrays.asList;
class ExecutorPluginGenerate implements ExecutorPlugin {
@Override
public boolean execute(final ExecuteRequest request, final ExecuteResponseStream responseStream) throws IOException {
final GenerateSql generateSql = GenerateSqlParser.parse(request.sql);
if (generateSql == null) return false;
final SpaceDocument[] spaceDocuments = new SpaceDocument[generateSql.count];
for (int i = 0; i < spaceDocuments.length; i++) {
SpaceDocument spaceDocument = new SpaceDocument(generateSql.typeName);
for (Map.Entry<String, Object> field : generateSql.fields.entrySet()) {
spaceDocument.setProperty(field.getKey(), field.getValue());
}
spaceDocuments[i] = spaceDocument;
}
GigaSpaceUtils.getGigaSpace(request).writeMultiple(spaceDocuments, WriteModifiers.NONE);
responseStream.writeHeader(asList("affected_rows"));
responseStream.writeRow(asList(Integer.toString(spaceDocuments.length)));
responseStream.close();
return true;
}
}
|
package com.lady.viktoria.lightdrip;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.lady.viktoria.lightdrip.DatabaseModels.SensorData;
import com.lady.viktoria.lightdrip.RealmConfig.RealmBaseFragment;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import io.realm.Realm;
import io.realm.RealmResults;
import static io.realm.Realm.getInstance;
public class SensorActionFragment extends RealmBaseFragment implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
private final static String TAG = SensorActionFragment.class.getSimpleName();
public SensorActionFragment() {
}
Calendar SensorStart;
int mYear, mMonthOfYear, mDayOfMonth, mHourOfDay, mMinute;
private Realm mRealm;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sensoraction, container, false);
SensorStart = Calendar.getInstance();
Realm.init(getActivity());
mRealm = getInstance(getRealmConfig());
SensorDialog();
return view;
}
protected void SensorDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Please choice if you want to stop current Sensor or start a new Sensor");
builder.setTitle("Sensor Actions");
builder.setPositiveButton("Start Sensor", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!isSensorActive()) {
StartSensor();
dialog.dismiss();
} else {
Snackbar.make(getView(), "Please stop current Sensor fist!", Snackbar.LENGTH_LONG).show();
dialog.dismiss();
}
}
});
builder.setNegativeButton("Stop sensor", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
StopSensor();
dialog.dismiss();
}
});
builder.create().show();
}
private void StartSensor() {
Calendar now = Calendar.getInstance();
DatePickerDialog dpd = DatePickerDialog.newInstance(
SensorActionFragment.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
dpd.show(getFragmentManager(), "Datepickerdialog");
}
private void StopSensor() {
long stopped_at = new Date().getTime();
RealmResults<SensorData> results = mRealm.where(SensorData.class).findAll();
String lastUUID = results.last().getuuid();
SensorData mSensorData = mRealm.where(SensorData.class).equalTo("uuid", lastUUID).findFirst();
mRealm.beginTransaction();
mSensorData.setstopped_at(stopped_at);
mRealm.commitTransaction();
mRealm.close();
}
private void CurrentSensor() {
}
private boolean isSensorActive() {
RealmResults<SensorData> results = mRealm.where(SensorData.class).findAll();
String lastUUID = results.last().getuuid();
SensorData mSensorData = mRealm.where(SensorData.class).equalTo("uuid", lastUUID).findFirst();
mRealm.beginTransaction();
mRealm.commitTransaction();
mRealm.close();
if (mSensorData.getstopped_at() == 0L) {
return true;
}
return false;
}
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonthOfYear = monthOfYear;
mDayOfMonth = dayOfMonth;
Calendar now = Calendar.getInstance();
TimePickerDialog tpd = TimePickerDialog.newInstance(
SensorActionFragment.this,
now.get(Calendar.HOUR_OF_DAY),
now.get(Calendar.MINUTE),
true
);
tpd.show(getFragmentManager(), "Timepickerdialog");
}
@Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
mHourOfDay = Integer.parseInt(hourOfDay < 10 ? "0"+hourOfDay : ""+hourOfDay);
mMinute = Integer.parseInt(minute < 10 ? "0"+minute : ""+minute);
SensorStart.set(mYear, mMonthOfYear, mDayOfMonth, mHourOfDay, mMinute, 0);
long startTime = SensorStart.getTime().getTime();
String uuid = UUID.randomUUID().toString();
mRealm.beginTransaction();
SensorData mSensorData = mRealm.createObject(SensorData.class, uuid);
mSensorData.setstarted_at(startTime);
mRealm.commitTransaction();
mRealm.close();
getActivity().getFragmentManager().popBackStack();
}
}
|
package com.marverenic.music.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.marverenic.music.JockeyApplication;
import com.marverenic.music.R;
import com.marverenic.music.data.store.MediaStoreUtil;
import com.marverenic.music.data.store.PreferencesStore;
import com.marverenic.music.dialog.AppendPlaylistDialogFragment;
import com.marverenic.music.dialog.CreatePlaylistDialogFragment;
import com.marverenic.music.fragments.QueueFragment;
import com.marverenic.music.instances.Song;
import com.marverenic.music.player.MusicPlayer;
import com.marverenic.music.player.PlayerController;
import com.marverenic.music.view.GestureView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
import static android.support.design.widget.Snackbar.LENGTH_LONG;
import static android.support.design.widget.Snackbar.LENGTH_SHORT;
public class NowPlayingActivity extends BaseActivity implements GestureView.OnGestureListener {
private static final String TAG_MAKE_PLAYLIST = "CreatePlaylistDialog";
private static final String TAG_APPEND_PLAYLIST = "AppendPlaylistDialog";
@Inject PreferencesStore mPrefStore;
private ImageView artwork;
private GestureView artworkWrapper;
private Song lastPlaying;
private QueueFragment queueFragment;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onNewIntent(getIntent());
setContentView(R.layout.activity_now_playing);
JockeyApplication.getComponent(this).inject(this);
boolean landscape = getResources().getConfiguration().orientation == ORIENTATION_LANDSCAPE;
if (!landscape) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
findViewById(R.id.artworkSwipeFrame).getLayoutParams().height = getArtworkHeight();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
artwork = (ImageView) findViewById(R.id.imageArtwork);
queueFragment =
(QueueFragment) getSupportFragmentManager().findFragmentById(R.id.listFragment);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
if (!landscape) {
actionBar.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
actionBar.setElevation(getResources().getDimension(R.dimen.header_elevation));
}
actionBar.setTitle("");
actionBar.setHomeAsUpIndicator(R.drawable.ic_clear_24dp);
}
artworkWrapper = (GestureView) findViewById(R.id.artworkSwipeFrame);
if (artworkWrapper != null) {
artworkWrapper.setGestureListener(this);
artworkWrapper.setGesturesEnabled(mPrefStore.enableNowPlayingGestures());
}
onUpdate();
}
private int getArtworkHeight() {
int reservedHeight = (int) getResources().getDimension(R.dimen.player_frame_peek);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
// Default to a square view, so set the height equal to the width
//noinspection SuspiciousNameCombination
int preferredHeight = metrics.widthPixels;
int maxHeight = metrics.heightPixels - reservedHeight;
return Math.min(preferredHeight, maxHeight);
}
@Override
public void onNewIntent(Intent intent) {
// Handle incoming requests to play media from other applications
if (intent.getData() == null) return;
// If this intent is a music intent, process it
if (intent.getType().contains("audio") || intent.getType().contains("application/ogg")
|| intent.getType().contains("application/x-ogg")
|| intent.getType().contains("application/itunes")) {
// The queue to be passed to the player service
ArrayList<Song> queue = new ArrayList<>();
int position = 0;
try {
position = MediaStoreUtil.getSongListFromFile(this,
new File(intent.getData().getPath()), intent.getType(), queue);
} catch (Exception e) {
e.printStackTrace();
queue = new ArrayList<>();
}
if (queue.isEmpty()) {
// No music was found
Toast toast = Toast.makeText(this, R.string.message_play_error_not_found,
Toast.LENGTH_SHORT);
toast.show();
finish();
} else {
if (PlayerController.isServiceStarted()) {
PlayerController.setQueue(queue, position);
PlayerController.begin();
} else {
// If the service hasn't been bound yet, then we need to wait for the service to
// start before we can pass data to it. This code will bind a short-lived
// BroadcastReceiver to wait for the initial UPDATE broadcast to be sent before
// sending data. Once it has fulfilled its purpose it will unbind itself to
// avoid a lot of problems later on.
final ArrayList<Song> pendingQueue = queue;
final int pendingPosition = position;
final BroadcastReceiver binderWaiter = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
PlayerController.setQueue(pendingQueue, pendingPosition);
PlayerController.begin();
NowPlayingActivity.this.unregisterReceiver(this);
}
};
registerReceiver(binderWaiter, new IntentFilter(MusicPlayer.UPDATE_BROADCAST));
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_now_playing, menu);
updateShuffleIcon(menu.findItem(R.id.action_shuffle));
updateRepeatIcon(menu.findItem(R.id.action_repeat));
return true;
}
private void updateShuffleIcon(MenuItem shuffleMenuItem) {
if (mPrefStore.isShuffled()) {
shuffleMenuItem.getIcon().setAlpha(255);
shuffleMenuItem.setTitle(getResources().getString(R.string.action_disable_shuffle));
} else {
shuffleMenuItem.getIcon().setAlpha(128);
shuffleMenuItem.setTitle(getResources().getString(R.string.action_enable_shuffle));
}
}
private void updateRepeatIcon(MenuItem repeatMenuItem) {
if (mPrefStore.getRepeatMode() == MusicPlayer.REPEAT_ALL) {
repeatMenuItem.getIcon().setAlpha(255);
repeatMenuItem.setTitle(getResources().getString(R.string.action_enable_repeat_one));
} else if (mPrefStore.getRepeatMode() == MusicPlayer.REPEAT_ONE) {
repeatMenuItem.setIcon(R.drawable.ic_repeat_one_24dp);
repeatMenuItem.setTitle(getResources().getString(R.string.action_disable_repeat));
} else {
repeatMenuItem.setIcon(R.drawable.ic_repeat_24dp);
repeatMenuItem.getIcon().setAlpha(128);
repeatMenuItem.setTitle(getResources().getString(R.string.action_enable_repeat));
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_shuffle:
toggleShuffle(item);
return true;
case R.id.action_repeat:
toggleRepeat(item);
return true;
case R.id.save:
saveQueueAsPlaylist();
return true;
case R.id.add_to_playlist:
addQueueToPlaylist();
return true;
case R.id.clear_queue:
clearQueue();
return true;
}
return super.onOptionsItemSelected(item);
}
private void toggleShuffle(MenuItem shuffleMenuItem) {
mPrefStore.toggleShuffle();
PlayerController.updatePlayerPreferences(mPrefStore);
if (mPrefStore.isShuffled()) {
showSnackbar(R.string.confirm_enable_shuffle);
} else {
showSnackbar(R.string.confirm_disable_shuffle);
}
updateShuffleIcon(shuffleMenuItem);
queueFragment.updateShuffle();
}
private void toggleRepeat(MenuItem repeatMenuItem) {
mPrefStore.cycleRepeatMode();
PlayerController.updatePlayerPreferences(mPrefStore);
if (mPrefStore.getRepeatMode() == MusicPlayer.REPEAT_ALL) {
showSnackbar(R.string.confirm_enable_repeat);
} else if (mPrefStore.getRepeatMode() == MusicPlayer.REPEAT_ONE) {
showSnackbar(R.string.confirm_enable_repeat_one);
} else {
showSnackbar(R.string.confirm_disable_repeat);
}
updateRepeatIcon(repeatMenuItem);
}
private void saveQueueAsPlaylist() {
CreatePlaylistDialogFragment.newInstance()
.setSongs(PlayerController.getQueue())
.showSnackbarIn(R.id.imageArtwork)
.show(getSupportFragmentManager(), TAG_MAKE_PLAYLIST);
}
private void addQueueToPlaylist() {
AppendPlaylistDialogFragment.newInstance()
.setTitle(getString(R.string.header_add_queue_to_playlist))
.setSongs(PlayerController.getQueue())
.showSnackbarIn(R.id.imageArtwork)
.show(getSupportFragmentManager(), TAG_APPEND_PLAYLIST);
}
private void clearQueue() {
List<Song> previousQueue = PlayerController.getQueue();
int previousQueueIndex = PlayerController.getQueuePosition();
int previousSeekPosition = PlayerController.getCurrentPosition();
boolean wasPlaying = PlayerController.isPlaying();
PlayerController.clearQueue();
Snackbar.make(findViewById(R.id.imageArtwork), R.string.confirm_clear_queue, LENGTH_LONG)
.setAction(R.string.action_undo, view -> {
PlayerController.editQueue(previousQueue, previousQueueIndex);
PlayerController.seek(previousSeekPosition);
if (wasPlaying) {
PlayerController.begin();
}
})
.show();
}
@Override
public void onUpdate() {
super.onUpdate();
final Song nowPlaying = PlayerController.getNowPlaying();
if (lastPlaying == null || !lastPlaying.equals(nowPlaying)) {
Bitmap image = PlayerController.getArtwork();
if (image == null) {
artwork.setImageResource(R.drawable.art_default_xl);
} else {
artwork.setImageBitmap(image);
}
lastPlaying = nowPlaying;
}
}
private void showSnackbar(@StringRes int stringId) {
showSnackbar(getString(stringId));
}
@Override
protected void showSnackbar(String message) {
Snackbar.make(findViewById(R.id.imageArtwork), message, LENGTH_SHORT).show();
}
@Override
public void onLeftSwipe() {
PlayerController.skip();
}
@Override
public void onRightSwipe() {
int queuePosition = PlayerController.getQueuePosition() - 1;
if (queuePosition < 0 && mPrefStore.getRepeatMode() == MusicPlayer.REPEAT_ALL) {
queuePosition += PlayerController.getQueueSize();
}
if (queuePosition >= 0) {
PlayerController.changeSong(queuePosition);
} else {
PlayerController.seek(0);
}
}
@Override
public void onTap() {
PlayerController.togglePlay();
//noinspection deprecation
artworkWrapper.setTapIndicator(getResources().getDrawable(
(PlayerController.isPlaying())
? R.drawable.ic_play_arrow_36dp
: R.drawable.ic_pause_36dp));
}
}
|
package modulo4.ddam.markmota.tk.ejercicio1;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import modulo4.ddam.markmota.tk.ejercicio1.model.ModelUser;
import modulo4.ddam.markmota.tk.ejercicio1.service.ServiceTimer;
import modulo4.ddam.markmota.tk.ejercicio1.sql.UserDataSource;
import modulo4.ddam.markmota.tk.ejercicio1.util.PreferenceUtil;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etUser;
private EditText etPass;
private CheckBox rememberCheck;
private UserDataSource userDataSource;
private PreferenceUtil preferenceUtil;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferenceUtil= new PreferenceUtil(getApplicationContext());
userDataSource= new UserDataSource(getApplicationContext());
// Linking layout elements with objects
etUser=(EditText) findViewById(R.id.activity_main_input_user);
etPass=(EditText) findViewById(R.id.activity_main_input_password);
rememberCheck= (CheckBox) findViewById(R.id.activity_main_check_remember);
// Setting click listener to buttons
findViewById(R.id.activity_main_btn_login).setOnClickListener(this);
findViewById(R.id.activity_main_btn_register).setOnClickListener(this);
// checking if we have an user id saved
checkSavedData();
}
private void checkSavedData() {
// Getting user from preferences if is the option remember on
// and setting the text in the layout elements
int user_id= preferenceUtil.getUserId();
if(user_id!=0){
ModelUser userDataSaver=userDataSource.getUser(user_id);
etUser.setText(userDataSaver.username);
etPass.setText(userDataSaver.password);
rememberCheck.setChecked(true);
// Hack to skip the layout log
validateLogin(userDataSaver.username,userDataSaver.password);
}
}
// This implements the button actions
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.activity_main_btn_login:
checkValues();
break;
case R.id.activity_main_btn_register:
addUser();
break;
}
}
// Sanitising data
private void checkValues() {
// Setting data object from variables
final String user= etUser.getText().toString();
final String pass= etPass.getText().toString();
// check if fields are no empty
if(TextUtils.isEmpty(user))
showMessage(R.string.activity_main_message_empty_user);
else if(TextUtils.isEmpty(pass))
showMessage(R.string.activity_main_message_empty_pass);
else //If is not empty we proceed to validate user
validateLogin(user,pass);
}
// Validating data and starting new activity
private void validateLogin(String user, String pass) {
// Establish connexion to the database and check the user and password
ModelUser user_data=userDataSource.checkLog(user,pass);
if(user_data != null){
if(user_data.last_log!=null){
// Show welcome and last log
String welcome= String.format(getString(R.string.activity_main_message_success_login),user_data.last_log);
Toast.makeText(getApplicationContext(),welcome,Toast.LENGTH_LONG).show();
}
else{
String welcome= String.format(getString(R.string.activity_main_message_success_login)," First Time.");
Toast.makeText(getApplicationContext(),welcome,Toast.LENGTH_LONG).show();
}
// Check if the check box remember user is on, if is I have to remember the user id
if(rememberCheck.isChecked()){
preferenceUtil.saveUserId(user_data.id);
}
else{
preferenceUtil.saveUserId(0);
}
// Now I get the session time form the preference util
int session_time= preferenceUtil.getSessionTime();
// Clean layout fields
etPass.setText("");
etUser.setText("");
rememberCheck.setChecked(false);
// Start to configure the start of the next activity
Intent intent= new Intent(getApplicationContext(),HomeActivity.class);
// Variables to send to the next activity
intent.putExtra("user_name",user);
intent.putExtra("last_log",user_data.last_log);
intent.putExtra("session_time",session_time);
startActivity(intent);
// Start service, the session counter
Intent service=new Intent(getApplicationContext(), ServiceTimer.class);
// Variables to send to the service
service.putExtra("initial_counter_value",session_time);
startService(service);
}
else {
// clean the password in the layout field
etPass.setText("");
showMessage(R.string.activity_main_message_error_login);
}
}
// Start activity to the register activity
private void addUser() {
Intent intent= new Intent(getApplicationContext(),RegisterActivity.class);
startActivity(intent);
}
// Showing toast messages
private void showMessage(int resourceString) {
Toast.makeText(getApplicationContext(),resourceString,Toast.LENGTH_SHORT).show();
}
@Override
protected void onResume() {
super.onResume();
checkSavedData();
}
}
|
package org.cnodejs.android.md.model.api;
import org.cnodejs.android.md.model.entity.Result;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CallbackAdapter<T extends Result> implements Callback<T> {
@Override
public final void onResponse(Call<T> call, Response<T> response) {
boolean interrupt;
if (response.isSuccessful()) {
interrupt = onResultOk(response, response.body());
} else {
interrupt = onResultError(response, Result.buildError(response));
}
if (!interrupt) {
onFinish();
}
}
@Override
public final void onFailure(Call<T> call, Throwable t) {
boolean interrupt;
if (call.isCanceled()) {
interrupt = onCallCancel();
} else {
interrupt = onCallException(t, Result.buildError(t));
}
if (!interrupt) {
onFinish();
}
}
public boolean onResultOk(Response<T> response, T result) {
return false;
}
public boolean onResultError(Response<T> response, Result.Error error) {
return false;
}
public boolean onCallCancel() {
return false;
}
public boolean onCallException(Throwable t, Result.Error error) {
return false;
}
public void onFinish() {}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.